import gradio as gr from datetime import datetime import smtplib import requests import re import time #import examples import os THANKS = """ # THANKS FOR YOUR QUERY ### You have two more options to get AI assistance ### 1) Use ChatGPT with the below prompt #### === MicroPython Script Guidelines === #### - Import: Use 'from schoginitoys import *' #### - Joystick: Use Config.xValue, Config.yValue, Config.up, Config.down, Config.right, Config.left, Config.button_pressed #### - Buzzer: Use beep() for 0.1s beep, beep(2) for 2s beep #### - Display: Use show("text"), scroll("text"), display_bitmap(bitmap_data, col), display.set_pixel(col, row, value) #### - Exit: Use Config.left or Config.button_pressed to exit #### - Libraries: No need to import random, time, urandom, string; we handle it #### - Output: Use show() for strings <= 4 chars, scroll() for longer strings #### - Reset: No need to call display_reset(); it's handled in our library #### - Formatting: Ensure all code is formatted #### - Explanations: Include kid-friendly explanations below each code snippet #### - Hyperlinks: Add a link to https://schoginitoys.com for more info #### - LED Specs: 32 columns x 8 rows; use display.show() after display.set_pixel() - LED Connections: GP12=Red, GP13=Yellow, GP14=Green; use these for LED-based projects - Ask your question here. ### 2) Register at https://schoginitoys.com/p01 to gain access to ### our AI Chatbot: Coding Assistance ## Schogini Toys Tech Team! """ def post_it(q=''): # Define the URL and parameters if q=='': return url = os.environ.get('BLUEHOST_ENDPOINT')+"/index-cb.php" params = { "password": os.environ.get('BLUEHOST_API_PASS'), "q": q } headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent': 'my-app' } # print(url) # Make the POST request # response = requests.post(url, params=params) response = requests.get(url, params=params, headers=headers) # Check if the request was successful if response.status_code == 200: #print("Successfully posted data.") #print("Response:", response.text) pass else: #print(response) print(f"Failed to post data. Status code: {response.status_code}") def insert_newlines(text, max_line_length=80): new_text = "" for line in text.split('\n'): while len(line) > max_line_length: # Find the last space before the max_line_length last_space = line[:max_line_length].rfind(' ') if last_space == -1: # No space found, just break at max_line_length last_space = max_line_length new_text += line[:last_space] + '\n' line = line[last_space:].strip() new_text += line + '\n' return new_text def get_menu_item(m=''): url = os.environ.get('BLUEHOST_ENDPOINT')+"/index-e.php" password_token = os.environ.get('BLUEHOST_API_PASS') headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent': 'my-app', 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', } params = { 'password_token': password_token, 'menu': m } # Make an HTTP GET request with the password token as a query parameter response = requests.get(url, params=params, headers=headers) # Check if the request was successful if response.status_code == 200: output_text = response.text # Now, output_text contains the content fetched from the PHP script #print(f"Received output:\n{output_text}") return insert_newlines(output_text) else: #print(f"Failed to fetch data. Status code: {response.status_code}") return "" def get_buttons(): url = os.environ.get('BLUEHOST_ENDPOINT')+"/index-e.php" password_token = os.environ.get('BLUEHOST_API_PASS') headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent': 'my-app', 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', } # Make an HTTP GET request with the password token as a query parameter response = requests.get(url, params={'password_token': password_token}, headers=headers) # Check if the request was successful list_values = [] if response.status_code == 200: # Extract the plain text from the response text_content = response.text # print("RAW1") # print(response) # print("RAW2") # print(text_content) # Use regular expression to find all the list values, assuming they're always formatted as "Lxxx" #list_values = re.findall(r'"L\d+"', text_content) # list_values = re.findall(r'"(L\d+|L.*)"', text_content) list_values = re.findall(r'"(.*)"', text_content) #list_values = re.findall(r'"L(?:\d+|-MENU)"', text_content)) #list_values = re.findall(r'"L"', text_content) #list_values = text_content #print(list_values) # Remove the quotes to get the actual values list_values = [value.strip('"') for value in list_values] #list_values = [value.strip("'") for value in list_values] #print(list_values) # Print or use the list #print("Extracted list values:", list_values) # else: # print(f"Failed to fetch data. Status code: {response.status_code}") # pass return list_values def greet(name): # return "Hello " + name + "!!" # Get the current date and time #now = datetime.now() # Format the datetime object as a string in the format YYYYMMDD_HHMMSS #timestamp_str = now.strftime("%Y%m%d_%H%M%S") # Create a unique filename by appending the timestamp to the base filename #unique_filename = f"query_{timestamp_str}" #print(f"Unique Filename: {unique_filename}") #In this example, unique_filename will contain a #filename like myfile_20231001_123456.txt, where 20231001 represents the date (YYYYMMDD) # # Open a file called 'example.txt' in write mode ('w') # with open(unique_filename, 'w') as file: # # Write the string "Hello, world!" to the file # file.write(name) #send_email(name, unique_filename) # f"Failed to post data. Status code: {response.status_code}" time.sleep(2) if name=='': msg="Please click any button below or enter your query." else: menu_code = get_menu_item(name) #print("menu_code: " + menu_code) # if "not found" in menu_code: if re.search(r"not found", menu_code): tpl=THANKS #examples.PROJECT_TEMPLATE post_it(name) # Save the query in bluehost msg = tpl #menu_code = tpl return msg if menu_code =='': try: tpl=eval("examples." + name) # print("examples." + name) msg = "```python\n" + tpl + "\n```\n" except: tpl=THANKS #PROJECT_TEMPLATE post_it(name) # Save the query in bluehost msg = tpl else: msg = menu_code # msg = "```python\n"+menu_code+"\n```\n" # return "\n```python\n" + "\n\nimport schoginitoys\n\nprint(\"abcd\")\n" + "\n\n```" return msg # iface = gr.Interface(fn=greet, inputs="text", outputs="text") # iface.launch() import openai import gradio as gr messages = [{"role": "system", "content": ''' === MicroPython Script Guidelines === - Import: Use 'from schoginitoys import *' - Joystick: Use Config.xValue, Config.yValue, Config.up, Config.down, Config.right, Config.left, Config.button_pressed - Buzzer: Use beep() for 0.1s beep, beep(2) for 2s beep - Display: Use show("text"), scroll("text"), display_bitmap(bitmap_data, col), display.set_pixel(col, row, value) - Exit: Use Config.left or Config.button_pressed to exit - Libraries: No need to import random, time, urandom, string; we handle it - Output: Use show() for strings <= 4 chars, scroll() for longer strings - Reset: No need to call display_reset(); it's handled in our library - Formatting: Ensure all code is formatted - Explanations: Include kid-friendly explanations below each code snippet - Hyperlinks: Add a link to https://schoginitoys.com for more info - LED Specs: 32 columns x 8 rows; use display.show() after display.set_pixel() - LED Connections: GP12=Red, GP13=Yellow, GP14=Green; use these for LED-based projects ''' }] # messages = [{"role": "system", # "content": """You are MicroPython expert. # Make sure that the python scripts you output contains import line from schoginitoys import *. # All code sections should be code formatted. # Our DIY Kit uses Raspberry Pi PICO. # Our DIY kit has a joystick and the user inputs are mapped as below. # Config.xValue has the x value. # Config.yValue has the y value. # Config.up will be True if user moves joystick fully up. # Config.down will be True if user moves joystick fully down. # Config.right will be True if user moves joystick fully right. # Config.left will be True if user moves joystick fully left. # Config.button_pressed will be True if the user pushes the joystick middle button. # Our DIY kit has a buzzer with these functions. # beep() function will beep for 0.1 second. # beep(2) function will beep for 2 seconds. # Our DIY kit has a 4 digit Max7219 display, but do not use any setup initializations, # we have these fucntions. # display_reset() will initialize and erases the display. # show("good") will show good on the display. # scroll("good morning") will scroll good morning on the display. # In addtion you can use these functions. # display_bitmap(bitmap_data,col) will show the bitmap at the col position. # display.set_pixel(col, row, value) will set the col, row with value. # Normally when the user moves the joystick to left, Config.left becomes true and we use # this to exit the script. Certain cases if your code needs the Config.left flag you may # instead Config.button_pressed to exit the script. # Please note that you don't need to import these libraries we are doing it. # import random # import time # import urandom # import string # Anytime you need to output a result using the print statement, please follow this condition. # If the string is 4 characters or less use show(string), if the string is more than # 4 characters use scroll(string), this is instead of print(string). # You don't need to use display_reset() as we are already doing it in schoginitoys library. # Use display_reset() only when you want to explicitly fill the display with zeros. # Again, remember that never user the print() statement, use only show() or scroll() functions. # You don't need to call display_reset() before show() or scroll() as we are calling that anyway # in these functions. # Please don't import random, we are doing it via schoginitoys import. # Again, please remember to code format the output scripts. # Please provide a kid friendly explanation below the code snippet to explain each and every # this so that your responses are educative for kids learning python. # All responses should include a well formatted explanation outside on the code block # with heading and subheadings. # All responses should include a hyperlink to https://schoginitoys.com saying for more info. # Display has 32 horizontal led columns and 8 led rows. # Remember to add display.show() after each display.set_pixel(). # Please these connection provided in the Kit. # Raspberry Pi PICO Port GP12 is connected to Red LED. # Raspberry Pi PICO Port GP13 is connected to Yellow LED. # Raspberry Pi PICO Port GP14 is connected to Green LED. # For LED signal based projects like traffic signal etc. use the above LEDs using the Raspberry Pi PICO Machine library PIN class # instead of the matrix display. # """}] # display_row(value, row) will fill the whole row with value. # display_col(value, col) will fill the whole col with value. def CustomChatGPT(user_input): messages.append({"role": "user", "content": user_input}) response = openai.ChatCompletion.create( model = "gpt-3.5-turbo", #"gpt-4", #https://platform.openai.com/docs/models/gpt-4 messages = messages ) ChatGPT_reply = response["choices"][0]["message"]["content"] messages.append({"role": "assistant", "content": ChatGPT_reply}) return ChatGPT_reply # demo = gradio.Interface( # fn=CustomChatGPT, # inputs = "text", # outputs = "markdown", # title = "Schogini Toys: AI Chatbot Your Coding Companion!") gr.close_all() # demo = gr.Interface(fn=summarize, # inputs=[gr.Textbox(label="Text to summarize", lines=6)], # outputs=[gr.Textbox(label="Result", lines=3)], # title="Text summarization with distilbart-cnn", # description="Summarize any text using the `shleifer/distilbart-cnn-12-6` model under the hood!" # ) # demo.launch(share=True, server_port=int(os.environ['PORT2'])) #css_code='body{background-image:url("https://picsum.photos/seed/picsum/200/300");}' def sree_auth(username='', password=''): # print(os.environ.get('ABHI_PASS')) # print(os.environ.get('SREE_PASS')) if username=='abhi' and password==os.environ.get('ABHI_PASS'): return True if username=='sree' and password==os.environ.get('SREE_PASS'): return True return False # print(os.environ.get('ABHI_PASS')) # print(os.environ.get('SREE_PASS')) examples_list = get_buttons() demo = gr.Interface( # fn=CustomChatGPT, fn=greet, inputs = [gr.Textbox(label="Ask your questions!", lines=6)], outputs = "markdown", #outputs = [gr.Textbox(label="Result", lines=8)], # title = "Schogini Toys - AI Chatbot V1.03", description="Your Python Projects Coding Companion!", allow_flagging="never", examples = examples_list, examples_per_page = 50, # examples = gr.Examples( # examples = examples_list, # examples_per_page = 20, # run_on_click = True, # inputs = 0, # #fn=mirror, # #cache_examples=True, # ), # examples=[ # "L201", # "L202", # "L203", # "L204", # ], # theme=gr.themes.Soft(), theme=gr.themes.Default(), ) # demo.launch() demo.launch(auth=sree_auth) # demo.launch(share=True)