schoginitoys commited on
Commit
6490836
1 Parent(s): b701b16
Files changed (2) hide show
  1. app-i.py +412 -0
  2. app.py +66 -3
app-i.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from datetime import datetime
3
+ import smtplib
4
+ import requests
5
+ import re
6
+ import time
7
+ #import examples
8
+ import os
9
+
10
+ THANKS = """
11
+
12
+ # THANKS FOR YOUR QUERY
13
+
14
+ ### You have two more options to get AI assistance
15
+
16
+ ### 1) Use ChatGPT with the below prompt
17
+ #### === MicroPython Script Guidelines ===
18
+ #### - Import: Use 'from schoginitoys import *'
19
+ #### - Joystick: Use Config.xValue, Config.yValue, Config.up, Config.down, Config.right, Config.left, Config.button_pressed
20
+ #### - Buzzer: Use beep() for 0.1s beep, beep(2) for 2s beep
21
+ #### - Display: Use show("text"), scroll("text"), display_bitmap(bitmap_data, col), display.set_pixel(col, row, value)
22
+ #### - Exit: Use Config.left or Config.button_pressed to exit
23
+ #### - Libraries: No need to import random, time, urandom, string; we handle it
24
+ #### - Output: Use show() for strings <= 4 chars, scroll() for longer strings
25
+ #### - Reset: No need to call display_reset(); it's handled in our library
26
+ #### - Formatting: Ensure all code is formatted
27
+ #### - Explanations: Include kid-friendly explanations below each code snippet
28
+ #### - Hyperlinks: Add a link to https://schoginitoys.com for more info
29
+ #### - LED Specs: 32 columns x 8 rows; use display.show() after display.set_pixel()
30
+ - LED Connections: GP12=Red, GP13=Yellow, GP14=Green; use these for LED-based projects
31
+ - Ask your question here.
32
+
33
+ ### 2) Register at https://schoginitoys.com/p01 to gain access to
34
+ ### our AI Chatbot: Coding Assistance
35
+
36
+ ## Schogini Toys Tech Team!
37
+
38
+ """
39
+
40
+ def post_it(q=''):
41
+ # Define the URL and parameters
42
+ if q=='':
43
+ return
44
+ url = os.environ.get('BLUEHOST_ENDPOINT')+"/index-cb.php"
45
+ params = {
46
+ "password": os.environ.get('BLUEHOST_API_PASS'),
47
+ "q": q
48
+ }
49
+ headers = {
50
+ 'Accept': 'application/json',
51
+ 'Content-Type': 'application/json',
52
+ 'User-Agent': 'my-app'
53
+ }
54
+ # print(url)
55
+ # Make the POST request
56
+ # response = requests.post(url, params=params)
57
+ response = requests.get(url, params=params, headers=headers)
58
+
59
+ # Check if the request was successful
60
+ if response.status_code == 200:
61
+ #print("Successfully posted data.")
62
+ #print("Response:", response.text)
63
+ pass
64
+ else:
65
+ #print(response)
66
+ print(f"Failed to post data. Status code: {response.status_code}")
67
+
68
+ def insert_newlines(text, max_line_length=80):
69
+ new_text = ""
70
+ for line in text.split('\n'):
71
+ while len(line) > max_line_length:
72
+ # Find the last space before the max_line_length
73
+ last_space = line[:max_line_length].rfind(' ')
74
+ if last_space == -1: # No space found, just break at max_line_length
75
+ last_space = max_line_length
76
+ new_text += line[:last_space] + '\n'
77
+ line = line[last_space:].strip()
78
+ new_text += line + '\n'
79
+ return new_text
80
+
81
+ def get_menu_item(m=''):
82
+ url = os.environ.get('BLUEHOST_ENDPOINT')+"/index-e.php"
83
+ password_token = os.environ.get('BLUEHOST_API_PASS')
84
+ headers = {
85
+ 'Accept': 'application/json',
86
+ 'Content-Type': 'application/json',
87
+ 'User-Agent': 'my-app',
88
+ 'Cache-Control': 'no-cache, no-store, must-revalidate',
89
+ 'Pragma': 'no-cache',
90
+ 'Expires': '0',
91
+ }
92
+ params = {
93
+ 'password_token': password_token,
94
+ 'menu': m
95
+ }
96
+ # Make an HTTP GET request with the password token as a query parameter
97
+ response = requests.get(url, params=params, headers=headers)
98
+ # Check if the request was successful
99
+ if response.status_code == 200:
100
+ output_text = response.text
101
+ # Now, output_text contains the content fetched from the PHP script
102
+ #print(f"Received output:\n{output_text}")
103
+ return insert_newlines(output_text)
104
+ else:
105
+ #print(f"Failed to fetch data. Status code: {response.status_code}")
106
+ return ""
107
+
108
+
109
+ def get_buttons():
110
+ url = os.environ.get('BLUEHOST_ENDPOINT')+"/index-e.php"
111
+ password_token = os.environ.get('BLUEHOST_API_PASS')
112
+ headers = {
113
+ 'Accept': 'application/json',
114
+ 'Content-Type': 'application/json',
115
+ 'User-Agent': 'my-app',
116
+ 'Cache-Control': 'no-cache, no-store, must-revalidate',
117
+ 'Pragma': 'no-cache',
118
+ 'Expires': '0',
119
+ }
120
+ # Make an HTTP GET request with the password token as a query parameter
121
+ response = requests.get(url, params={'password_token': password_token}, headers=headers)
122
+ # Check if the request was successful
123
+ list_values = []
124
+ if response.status_code == 200:
125
+ # Extract the plain text from the response
126
+
127
+ text_content = response.text
128
+ # print("RAW1")
129
+ # print(response)
130
+ # print("RAW2")
131
+ # print(text_content)
132
+ # Use regular expression to find all the list values, assuming they're always formatted as "Lxxx"
133
+ #list_values = re.findall(r'"L\d+"', text_content)
134
+
135
+ # list_values = re.findall(r'"(L\d+|L.*)"', text_content)
136
+ list_values = re.findall(r'"(.*)"', text_content)
137
+
138
+
139
+ #list_values = re.findall(r'"L(?:\d+|-MENU)"', text_content))
140
+ #list_values = re.findall(r'"L"', text_content)
141
+ #list_values = text_content
142
+ #print(list_values)
143
+ # Remove the quotes to get the actual values
144
+ list_values = [value.strip('"') for value in list_values]
145
+ #list_values = [value.strip("'") for value in list_values]
146
+
147
+ #print(list_values)
148
+ # Print or use the list
149
+ #print("Extracted list values:", list_values)
150
+
151
+ # else:
152
+ # print(f"Failed to fetch data. Status code: {response.status_code}")
153
+ # pass
154
+ return list_values
155
+
156
+ def greet(name):
157
+ # return "Hello " + name + "!!"
158
+
159
+ # Get the current date and time
160
+ #now = datetime.now()
161
+
162
+ # Format the datetime object as a string in the format YYYYMMDD_HHMMSS
163
+ #timestamp_str = now.strftime("%Y%m%d_%H%M%S")
164
+
165
+ # Create a unique filename by appending the timestamp to the base filename
166
+ #unique_filename = f"query_{timestamp_str}"
167
+
168
+ #print(f"Unique Filename: {unique_filename}")
169
+ #In this example, unique_filename will contain a
170
+ #filename like myfile_20231001_123456.txt, where 20231001 represents the date (YYYYMMDD)
171
+
172
+
173
+
174
+
175
+ # # Open a file called 'example.txt' in write mode ('w')
176
+ # with open(unique_filename, 'w') as file:
177
+ # # Write the string "Hello, world!" to the file
178
+ # file.write(name)
179
+
180
+ #send_email(name, unique_filename)
181
+
182
+
183
+ # f"Failed to post data. Status code: {response.status_code}"
184
+
185
+
186
+
187
+ time.sleep(2)
188
+
189
+
190
+
191
+
192
+
193
+
194
+
195
+ if name=='':
196
+ msg="Please click any button below or enter your query."
197
+ else:
198
+ menu_code = get_menu_item(name)
199
+ #print("menu_code: " + menu_code)
200
+ # if "not found" in menu_code:
201
+ if re.search(r"not found", menu_code):
202
+ tpl=THANKS #examples.PROJECT_TEMPLATE
203
+ post_it(name) # Save the query in bluehost
204
+ msg = tpl
205
+ #menu_code = tpl
206
+ return msg
207
+ if menu_code =='':
208
+ try:
209
+ tpl=eval("examples." + name)
210
+ # print("examples." + name)
211
+ msg = "```python\n" + tpl + "\n```\n"
212
+ except:
213
+ tpl=THANKS #PROJECT_TEMPLATE
214
+ post_it(name) # Save the query in bluehost
215
+ msg = tpl
216
+ else:
217
+ msg = menu_code
218
+ # msg = "```python\n"+menu_code+"\n```\n"
219
+
220
+
221
+
222
+ # return "\n```python\n" + "\n\nimport schoginitoys\n\nprint(\"abcd\")\n" + "\n\n```"
223
+ return msg
224
+
225
+
226
+ # iface = gr.Interface(fn=greet, inputs="text", outputs="text")
227
+ # iface.launch()
228
+
229
+
230
+ import openai
231
+ import gradio as gr
232
+
233
+
234
+ messages = [{"role": "system",
235
+ "content": '''
236
+ === MicroPython Script Guidelines ===
237
+
238
+ - Import: Use 'from schoginitoys import *'
239
+ - Joystick: Use Config.xValue, Config.yValue, Config.up, Config.down, Config.right, Config.left, Config.button_pressed
240
+ - Buzzer: Use beep() for 0.1s beep, beep(2) for 2s beep
241
+ - Display: Use show("text"), scroll("text"), display_bitmap(bitmap_data, col), display.set_pixel(col, row, value)
242
+ - Exit: Use Config.left or Config.button_pressed to exit
243
+ - Libraries: No need to import random, time, urandom, string; we handle it
244
+ - Output: Use show() for strings <= 4 chars, scroll() for longer strings
245
+ - Reset: No need to call display_reset(); it's handled in our library
246
+ - Formatting: Ensure all code is formatted
247
+ - Explanations: Include kid-friendly explanations below each code snippet
248
+ - Hyperlinks: Add a link to https://schoginitoys.com for more info
249
+ - LED Specs: 32 columns x 8 rows; use display.show() after display.set_pixel()
250
+ - LED Connections: GP12=Red, GP13=Yellow, GP14=Green; use these for LED-based projects
251
+ '''
252
+ }]
253
+ # messages = [{"role": "system",
254
+ # "content": """You are MicroPython expert.
255
+ # Make sure that the python scripts you output contains import line from schoginitoys import *.
256
+ # All code sections should be code formatted.
257
+
258
+ # Our DIY Kit uses Raspberry Pi PICO.
259
+
260
+ # Our DIY kit has a joystick and the user inputs are mapped as below.
261
+
262
+ # Config.xValue has the x value.
263
+ # Config.yValue has the y value.
264
+
265
+ # Config.up will be True if user moves joystick fully up.
266
+ # Config.down will be True if user moves joystick fully down.
267
+ # Config.right will be True if user moves joystick fully right.
268
+ # Config.left will be True if user moves joystick fully left.
269
+
270
+ # Config.button_pressed will be True if the user pushes the joystick middle button.
271
+
272
+ # Our DIY kit has a buzzer with these functions.
273
+
274
+ # beep() function will beep for 0.1 second.
275
+ # beep(2) function will beep for 2 seconds.
276
+
277
+ # Our DIY kit has a 4 digit Max7219 display, but do not use any setup initializations,
278
+ # we have these fucntions.
279
+ # display_reset() will initialize and erases the display.
280
+ # show("good") will show good on the display.
281
+ # scroll("good morning") will scroll good morning on the display.
282
+ # In addtion you can use these functions.
283
+ # display_bitmap(bitmap_data,col) will show the bitmap at the col position.
284
+ # display.set_pixel(col, row, value) will set the col, row with value.
285
+
286
+ # Normally when the user moves the joystick to left, Config.left becomes true and we use
287
+ # this to exit the script. Certain cases if your code needs the Config.left flag you may
288
+ # instead Config.button_pressed to exit the script.
289
+
290
+ # Please note that you don't need to import these libraries we are doing it.
291
+
292
+ # import random
293
+ # import time
294
+ # import urandom
295
+ # import string
296
+
297
+ # Anytime you need to output a result using the print statement, please follow this condition.
298
+ # If the string is 4 characters or less use show(string), if the string is more than
299
+ # 4 characters use scroll(string), this is instead of print(string).
300
+
301
+ # You don't need to use display_reset() as we are already doing it in schoginitoys library.
302
+ # Use display_reset() only when you want to explicitly fill the display with zeros.
303
+
304
+ # Again, remember that never user the print() statement, use only show() or scroll() functions.
305
+ # You don't need to call display_reset() before show() or scroll() as we are calling that anyway
306
+ # in these functions.
307
+
308
+
309
+ # Please don't import random, we are doing it via schoginitoys import.
310
+
311
+ # Again, please remember to code format the output scripts.
312
+
313
+ # Please provide a kid friendly explanation below the code snippet to explain each and every
314
+ # this so that your responses are educative for kids learning python.
315
+
316
+ # All responses should include a well formatted explanation outside on the code block
317
+ # with heading and subheadings.
318
+
319
+ # All responses should include a hyperlink to https://schoginitoys.com saying for more info.
320
+
321
+ # Display has 32 horizontal led columns and 8 led rows.
322
+
323
+ # Remember to add display.show() after each display.set_pixel().
324
+
325
+ # Please these connection provided in the Kit.
326
+
327
+ # Raspberry Pi PICO Port GP12 is connected to Red LED.
328
+ # Raspberry Pi PICO Port GP13 is connected to Yellow LED.
329
+ # Raspberry Pi PICO Port GP14 is connected to Green LED.
330
+
331
+ # For LED signal based projects like traffic signal etc. use the above LEDs using the Raspberry Pi PICO Machine library PIN class
332
+ # instead of the matrix display.
333
+
334
+ # """}]
335
+
336
+ # display_row(value, row) will fill the whole row with value.
337
+ # display_col(value, col) will fill the whole col with value.
338
+
339
+ def CustomChatGPT(user_input):
340
+ messages.append({"role": "user", "content": user_input})
341
+ response = openai.ChatCompletion.create(
342
+ model = "gpt-3.5-turbo", #"gpt-4", #https://platform.openai.com/docs/models/gpt-4
343
+ messages = messages
344
+ )
345
+ ChatGPT_reply = response["choices"][0]["message"]["content"]
346
+ messages.append({"role": "assistant", "content": ChatGPT_reply})
347
+ return ChatGPT_reply
348
+
349
+ # demo = gradio.Interface(
350
+ # fn=CustomChatGPT,
351
+ # inputs = "text",
352
+ # outputs = "markdown",
353
+ # title = "Schogini Toys: AI Chatbot Your Coding Companion!")
354
+
355
+ gr.close_all()
356
+ # demo = gr.Interface(fn=summarize,
357
+ # inputs=[gr.Textbox(label="Text to summarize", lines=6)],
358
+ # outputs=[gr.Textbox(label="Result", lines=3)],
359
+ # title="Text summarization with distilbart-cnn",
360
+ # description="Summarize any text using the `shleifer/distilbart-cnn-12-6` model under the hood!"
361
+ # )
362
+ # demo.launch(share=True, server_port=int(os.environ['PORT2']))
363
+
364
+ #css_code='body{background-image:url("https://picsum.photos/seed/picsum/200/300");}'
365
+
366
+ def sree_auth(username='', password=''):
367
+ # print(os.environ.get('ABHI_PASS'))
368
+ # print(os.environ.get('SREE_PASS'))
369
+
370
+ if username=='abhi' and password==os.environ.get('ABHI_PASS'):
371
+ return True
372
+ if username=='sree' and password==os.environ.get('SREE_PASS'):
373
+ return True
374
+ return False
375
+
376
+ # print(os.environ.get('ABHI_PASS'))
377
+ # print(os.environ.get('SREE_PASS'))
378
+ examples_list = get_buttons()
379
+
380
+ demo = gr.Interface(
381
+ # fn=CustomChatGPT,
382
+ fn=greet,
383
+ inputs = [gr.Textbox(label="Ask your questions!", lines=6)],
384
+ outputs = "markdown",
385
+ #outputs = [gr.Textbox(label="Result", lines=8)], #
386
+ title = "Schogini Toys - AI Chatbot V1.03",
387
+ description="Your Python Projects Coding Companion!",
388
+ allow_flagging="never",
389
+ examples = examples_list,
390
+ examples_per_page = 50,
391
+ # examples = gr.Examples(
392
+ # examples = examples_list,
393
+ # examples_per_page = 20,
394
+ # run_on_click = True,
395
+ # inputs = 0,
396
+ # #fn=mirror,
397
+ # #cache_examples=True,
398
+ # ),
399
+ # examples=[
400
+ # "L201",
401
+ # "L202",
402
+ # "L203",
403
+ # "L204",
404
+ # ],
405
+ # theme=gr.themes.Soft(),
406
+ theme=gr.themes.Default(),
407
+ )
408
+
409
+ # demo.launch()
410
+ demo.launch(auth=sree_auth)
411
+ # demo.launch(share=True)
412
+
app.py CHANGED
@@ -377,16 +377,79 @@ def sree_auth(username='', password=''):
377
  # print(os.environ.get('SREE_PASS'))
378
  examples_list = get_buttons()
379
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
380
  demo = gr.Interface(
381
  # fn=CustomChatGPT,
382
  fn=greet,
383
  inputs = [gr.Textbox(label="Ask your questions!", lines=6)],
384
- outputs = "markdown",
 
385
  #outputs = [gr.Textbox(label="Result", lines=8)], #
386
- title = "Schogini Toys - AI Chatbot V1.03",
387
  description="Your Python Projects Coding Companion!",
388
  allow_flagging="never",
389
- examples = examples_list,
390
  examples_per_page = 50,
391
  # examples = gr.Examples(
392
  # examples = examples_list,
 
377
  # print(os.environ.get('SREE_PASS'))
378
  examples_list = get_buttons()
379
 
380
+ title = "Schogini Toys - AI Chatbot V1.03"
381
+
382
+ # with gr.Blocks() as demo:
383
+ # gr.Markdown("# sadasd" . title)
384
+ # with gr.Row():
385
+ # # inp = gr.Textbox(placeholder="What is your name?")
386
+ # inp = [gr.Textbox(label="Ask your questions!", lines=6)]
387
+ # # out = gr.Textbox()
388
+ # out = gr.Markdown()
389
+ # btn = gr.Button("Submit Query", examples = examples_list)
390
+ # btn.click(fn=greet, inputs=inp, outputs=out)
391
+
392
+ # examples_per_page = 50
393
+ # allow_flagging="never"
394
+ # description="Your Python Projects Coding Companion!"
395
+
396
+ # demo = gr.Blocks()
397
+
398
+ # with demo:
399
+ # with gr.Row():
400
+ # title = title
401
+ # with gr.Row():
402
+ # title = title
403
+
404
+ # demo.launch(auth=sree_auth)
405
+
406
+ # with gr.Blocks() as demo:
407
+ # with gr.Row():
408
+ # inp = [gr.Textbox(label="Ask your questions!", lines=6)]
409
+ # with gr.Row():
410
+ # exa = examples_list
411
+ # with gr.Row():
412
+ # out = gr.Markdown()
413
+ # gr.Interface(
414
+ # fn=greet,
415
+ # inputs = inp,
416
+ # examples = exa,
417
+ # outputs = out,
418
+
419
+ # #outputs = [gr.Textbox(label="Result", lines=8)], #
420
+ # title = title,
421
+ # description="Your Python Projects Coding Companion!",
422
+ # allow_flagging="never",
423
+ # # examples = examples_list,
424
+ # examples_per_page = 50,
425
+ # # examples = gr.Examples(
426
+ # # examples = examples_list,
427
+ # # examples_per_page = 20,
428
+ # # run_on_click = True,
429
+ # # inputs = 0,
430
+ # # #fn=mirror,
431
+ # # #cache_examples=True,
432
+ # # ),
433
+ # # examples=[
434
+ # # "L201",
435
+ # # "L202",
436
+ # # "L203",
437
+ # # "L204",
438
+ # # ],
439
+ # # theme=gr.themes.Soft(),
440
+ # theme=gr.themes.Default(),
441
+ # )
442
  demo = gr.Interface(
443
  # fn=CustomChatGPT,
444
  fn=greet,
445
  inputs = [gr.Textbox(label="Ask your questions!", lines=6)],
446
+ examples = examples_list,
447
+ outputs = gr.Markdown(), #"markdown",
448
  #outputs = [gr.Textbox(label="Result", lines=8)], #
449
+ title = title,
450
  description="Your Python Projects Coding Companion!",
451
  allow_flagging="never",
452
+ # examples = examples_list,
453
  examples_per_page = 50,
454
  # examples = gr.Examples(
455
  # examples = examples_list,