Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
# π Load API key
|
| 7 |
+
load_dotenv()
|
| 8 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 9 |
+
client = OpenAI(api_key=api_key)
|
| 10 |
+
|
| 11 |
+
# π Python Tutor Function
|
| 12 |
+
def python_tutor(user_input):
|
| 13 |
+
response = client.chat.completions.create(
|
| 14 |
+
model="gpt-4.1-mini",
|
| 15 |
+
messages=[
|
| 16 |
+
{
|
| 17 |
+
"role": "system",
|
| 18 |
+
"content": "You are a Python tutor. Help users understand Python with short examples. Be kind, clear, and only answer Python-related questions.
|
| 19 |
+
1. Confirm if the question is Python-related. If not, politely inform the user and refrain from answering.
|
| 20 |
+
2. Provide a concise initial answer:
|
| 21 |
+
- Include a brief explanation.
|
| 22 |
+
- Provide a straightforward code example.
|
| 23 |
+
-keep the quiz simple and give optionsto choose if wrong answers selelcted correct them with explanation"
|
| 24 |
+
},
|
| 25 |
+
{"role": "user", "content": user_input}
|
| 26 |
+
],
|
| 27 |
+
temperature=0.1,
|
| 28 |
+
max_tokens=500
|
| 29 |
+
)
|
| 30 |
+
return response.choices[0].message.content
|
| 31 |
+
|
| 32 |
+
# π Simple Quiz Generator (fixed question for now)
|
| 33 |
+
def ask_question():
|
| 34 |
+
return "What is the output of print(2 + 3 * 4)?"
|
| 35 |
+
|
| 36 |
+
def evaluate_answer(user_answer):
|
| 37 |
+
correct_answer = "14"
|
| 38 |
+
if user_answer.strip() == correct_answer:
|
| 39 |
+
return "β
Correct! Great job!"
|
| 40 |
+
else:
|
| 41 |
+
return "β Incorrect. Try again. Hint: Use BODMAS."
|
| 42 |
+
|
| 43 |
+
# π¨ Gradio UI with Two Pages
|
| 44 |
+
with gr.Blocks() as app:
|
| 45 |
+
with gr.Tab("π Python Tutor"):
|
| 46 |
+
gr.Markdown("### Ask your Python question:")
|
| 47 |
+
question_input = gr.Textbox(lines=2, label="Your Question")
|
| 48 |
+
answer_output = gr.Textbox(label="Tutor's Answer")
|
| 49 |
+
gr.Button("Ask").click(python_tutor, inputs=question_input, outputs=answer_output)
|
| 50 |
+
|
| 51 |
+
with gr.Tab("π§ͺ Mini Quiz"):
|
| 52 |
+
gr.Markdown("### Let's test your Python basics!")
|
| 53 |
+
quiz_question = gr.Textbox(label="Question", interactive=False, value=ask_question())
|
| 54 |
+
user_response = gr.Textbox(label="Your Answer")
|
| 55 |
+
result_output = gr.Textbox(label="Result")
|
| 56 |
+
gr.Button("Submit Answer").click(evaluate_answer, inputs=user_response, outputs=result_output)
|
| 57 |
+
|
| 58 |
+
app.launch()
|