in

Python – How to hide API Requests in Console


I am making a Python chatbot and I am using some API’s is there a way I can hide the requests in the console? The reason I am doing this is I don’t want all the requests visible, is there some code I can put to prevent a print? Etc. or somewhere for the import I can access to remove these prints.

Here is what the console looks like:

Code:

#######################################################
#  Initialise NLTK Inference
#######################################################
from nltk.sem import Expression
from nltk.inference import ResolutionProver
read_expr = Expression.fromstring

#######################################################
#  Initialise Knowledgebase. 
#######################################################
import pandas
kb=[]
data = pandas.read_csv('kb.csv', header=None)
[kb.append(read_expr(row)) for row in data[0]]

# >>> ADD SOME CODES here for checking KB integrity (no contradiction), 
# otherwise show an error message and terminate

#######################################################
# Initialise Wikipedia agent
#######################################################
import wikipedia

#######################################################
#  Initialise AIML agent
#######################################################
import aiml
# Create a Kernel object. No string encoding (all I/O is unicode)
kern = aiml.Kernel()
kern.setTextEncoding(None)
kern.bootstrap(learnFiles="mybot-logic.xml")

#######################################################
# Other Imports
#######################################################
import fastf1 as ff1
from fastf1 import plotting
from matplotlib import pyplot as plt
from pprint import pprint
import pandas as pd
from timple.timedelta import strftimedelta
from fastf1.core import Laps

#######################################################
# Welcome user
#######################################################
print("Welcome to the Formula 1 chat bot. Please feel free to ask questions from me!")

#######################################################
# Main loop
#######################################################
while True:
    #get user input
    try:
        userInput = input("> ")
    except (KeyboardInterrupt, EOFError) as e:
        print("Bye!")
        break
    #pre-process user input and determine response agent (if needed)
    responseAgent="aiml"
    #activate selected response agent
    if responseAgent == 'aiml':
        answer = kern.respond(userInput)
    #post-process the answer for commands
    if answer[0] == '#':
        params = answer[1:].split('$')
        cmd = int(params[0])
        if cmd == 0:
            print(params[1])
            break
        elif cmd == 1:
            try:
                wSummary = wikipedia.summary(params[1], sentences=3,auto_suggest=False)
                print(wSummary)
            except:
                print("Sorry, I do not know that. Be more specific!")
        elif cmd == 2:
            if answer:
                year,gp = params[1].split(' ', 1)
                quals = ff1.get_session(year, gp, 'Q')
                pprint(quals.results[0])
                print('nAsk me another question!')
            else:
                print('Incorrect details, try again.')#
        elif cmd == 3:
            if answer:
                year,gp = params[1].split(' ', 1)
                race = ff1.get_session(year, gp, 'R')
                pprint(race.results[0])
                print(params[1])
            else:
                print('Incorrect details, try again.')
        elif cmd == 4:
            if answer:
                
                d1,d2,year,gp = params[1].split(' ', 3)
                
                plotting.setup_mpl()

                race = ff1.get_session(year, gp, 'R')
                laps = race.load_laps()

                lec = laps.pick_driver(d1)
                ham = laps.pick_driver(d2)
                
                fig, ax = plt.subplots()
                ax.plot(lec['LapNumber'], lec['LapTime'], color="red")
                ax.plot(ham['LapNumber'], ham['LapTime'], color="cyan")
                ax.set_title(d1 + " VS " + d2)
                ax.set_xlabel("Lap Number")
                ax.set_ylabel("Lap Time")
                plt.show()
            else:
                print('Incorrect details, try again.')
                
        elif cmd == 5:
            if answer:
                
                # we only want support for timedelta plotting in this example
                ff1.plotting.setup_mpl(mpl_timedelta_support=True, color_scheme=None, misc_mpl_mods=False)
                
                year,gp = params[1].split(' ', 1)
                quali = ff1.get_session(year, gp, 'Q')
                laps = quali.load_laps()
                
                
                ##############################################################################
                # First, we need to get an array of all drivers.
                
                drivers = pd.unique(laps['Driver'])
                
                
                ##############################################################################
                # After that we'll get each drivers fastest lap, create a new laps object
                # from these laps, sort them by lap time and have pandas reindex them to
                # number them nicely by starting position.
                
                list_fastest_laps = list()
                for drv in drivers:
                    drvs_fastest_lap = laps.pick_driver(drv).pick_fastest()
                    list_fastest_laps.append(drvs_fastest_lap)
                fastest_laps = Laps(list_fastest_laps).sort_values(by='LapTime').reset_index(drop=True)
                
                
                ##############################################################################
                # The plot is nicer to look at and more easily understandable if we just plot
                # the time differences. Therefore we subtract the fastest lap time from all
                # other lap times.
                
                pole_lap = fastest_laps.pick_fastest()
                fastest_laps['LapTimeDelta'] = fastest_laps['LapTime'] - pole_lap['LapTime']
                
                
                ##############################################################################
                # Finally, we'll create a list of team colors per lap to color our plot.
                team_colors = list()
                for index, lap in fastest_laps.iterlaps():
                    color = ff1.plotting.team_color(lap['Team'])
                    team_colors.append(color)
                
                
                ##############################################################################
                # Now, we can plot all the data
                fig, ax = plt.subplots()
                ax.barh(fastest_laps.index, fastest_laps['LapTimeDelta'],
                        color=team_colors, edgecolor="grey")
                ax.set_yticks(fastest_laps.index)
                ax.set_yticklabels(fastest_laps['Driver'])
                
                # show fastest at the top
                ax.invert_yaxis()
                
                # draw vertical lines behind the bars
                ax.set_axisbelow(True)
                ax.xaxis.grid(True, which="major", linestyle="--", color="black", zorder=-1000)
                # sphinx_gallery_defer_figures
                
                
                ##############################################################################
                # Finally, give the plot a meaningful title
                
                lap_time_string = strftimedelta(pole_lap['LapTime'], '%m:%s.%ms')
                
                plt.suptitle(f"{quali.weekend.name} {quali.weekend.year} Qualifyingn"
                             f"Fastest Lap: {lap_time_string} ({pole_lap['Driver']})")
                
                plt.show()
        # Here are the processing of the new logical component:
        elif cmd == 31: # if input pattern is "I know that * is *"
            object,subject=params[1].split(' is ')
            expr=read_expr(subject + '(' + object + ')')
            # >>> ADD SOME CODES HERE to make sure expr does not contradict 
            # with the KB before appending, otherwise show an error message.
            kb.append(expr) 
            print('OK, I will remember that',object,'is', subject)
        elif cmd == 32: # if the input pattern is "check that * is *"
            object,subject=params[1].split(' is ')
            expr=read_expr(subject + '(' + object + ')')
            answer=ResolutionProver().prove(expr, kb, verbose=True)
            if answer:
               print('Correct.')
            else:
               print('It may not be true.') 
               # >> This is not an ideal answer.
               # >> ADD SOME CODES HERE to find if expr is false, then give a
               # definite response: either "Incorrect" or "Sorry I don't know." 
             
        elif cmd == 98:
            if answer:
                print('Test')
        elif cmd == 99:
            print("I did not get that, please try again.")
    else:
        print(answer)



Source: https://stackoverflow.com/questions/70632562/python-how-to-hide-api-requests-in-console

Submission to Servian Tech Challenge

Find two biggest values, issues with non bar history referencing, and % values in pine v5 strategy