File size: 15,573 Bytes
02a7328
 
 
 
14a460b
02a7328
228ac3e
6540a09
02a7328
bf9c842
02a7328
bf9c842
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02a7328
 
 
aa55439
 
14a460b
02a7328
6540a09
02a7328
 
 
 
 
 
 
bf9c842
02a7328
 
 
 
 
 
 
 
 
 
bf9c842
02a7328
 
b77cf12
 
 
 
 
 
 
 
 
 
 
 
 
14a460b
 
 
 
 
 
bf9c842
 
 
 
14a460b
 
 
 
 
 
 
 
 
 
 
 
b77cf12
14a460b
 
 
 
 
 
 
 
 
 
 
b77cf12
 
 
 
14a460b
 
 
 
 
 
 
b77cf12
14a460b
b77cf12
 
 
 
14a460b
b77cf12
b701b16
 
 
 
 
b77cf12
 
 
 
14a460b
 
b77cf12
14a460b
b77cf12
14a460b
 
 
 
 
 
 
02a7328
 
 
 
 
14a460b
02a7328
 
14a460b
02a7328
 
14a460b
02a7328
 
 
 
 
 
 
 
 
 
 
 
 
 
6540a09
02a7328
 
 
 
 
 
 
14a460b
 
 
 
 
 
953f861
 
 
14a460b
bf9c842
 
 
 
 
 
 
 
14a460b
 
 
b701b16
14a460b
 
bf9c842
14a460b
 
 
b701b16
 
02a7328
 
 
 
3629b3d
02a7328
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6540a09
 
 
 
02a7328
6540a09
02a7328
 
 
6540a09
 
14a460b
6540a09
6490836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02a7328
 
 
 
6490836
 
02a7328
6490836
02a7328
 
6490836
235380d
 
 
 
 
 
 
 
 
14a460b
 
 
 
 
 
02a7328
 
 
 
c76d028
 
02a7328
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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()

title = "Schogini Toys - AI Chatbot V1.03"

# with gr.Blocks() as demo:
#     gr.Markdown("# sadasd" . title)
#     with gr.Row():
#         # inp = gr.Textbox(placeholder="What is your name?")
#         inp = [gr.Textbox(label="Ask your questions!", lines=6)]
#         # out = gr.Textbox()
#         out = gr.Markdown()
#     btn = gr.Button("Submit Query", examples = examples_list)
#     btn.click(fn=greet, inputs=inp, outputs=out)
    
#     examples_per_page = 50
#     allow_flagging="never"
#     description="Your Python Projects Coding Companion!"

# demo = gr.Blocks()

# with demo:
# 	with gr.Row():
# 		title = title
# 	with gr.Row():
# 		title = title

# demo.launch(auth=sree_auth)

# with gr.Blocks() as demo:
# 	with gr.Row():
# 		inp = [gr.Textbox(label="Ask your questions!", lines=6)]
# 	with gr.Row():	
# 		exa = examples_list
# 	with gr.Row():
# 		out = gr.Markdown()
# 	gr.Interface(
# 	fn=greet, 
# 	inputs = inp,
# 	examples = exa,
# 	outputs = out,

# 	#outputs = [gr.Textbox(label="Result", lines=8)], # 
# 	title = title, 
# 	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 = gr.Interface(
	# fn=CustomChatGPT, 
	fn=greet, 
	inputs = [gr.Textbox(label="Ask your questions!", lines=6)], 
	examples = examples_list,
	outputs = gr.Markdown(), #"markdown", 
	#outputs = [gr.Textbox(label="Result", lines=8)], # 
	title = title, 
	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)