Kiruthikaramalingam's picture
Update app.py
bdf02b1 verified
import os
import openai
import gradio as gr
from openai import OpenAI
api_key = os.getenv("openai")
client = OpenAI(api_key=api_key)
system_message = {
"role": "system",
"content": "You are an interactive Python tutor bot designed to assist beginners by answering Python-related questions. Politely decline any questions that are not related to Python programming. Provide only simple explanations, and if a user asks for a detailed explanation, explain everything in detail. Always answer with an example and also give one small question to try for them so they can learn and try. Keep it interactive and interesting."
}
practice_questions = {
"Variables": ["Assign your name to a variable and print it.", "Create a variable with your age and print it."],
"Loops": ["Write a for loop to print numbers 1 to 5.", "Use a while loop to print numbers from 10 to 6."],
"Functions": ["Define a function that returns the square of a number.", "Write a function that adds two numbers and returns the result."],
"Lists": ["Create a list of 5 numbers and print the third element.", "Append an item to a list and print the result."],
"Dictionaries": ["Create a dictionary with your name and age and print both.", "Add a key-value pair to a dictionary."],
"Classes": ["Create a simple class 'Car' with an attribute 'color'.", "Write a class that initializes with a name and prints it."],
"Inheritance": ["Create a class 'Animal' and a subclass 'Dog'. Make Dog inherit from Animal.", "Demonstrate method overriding with parent and child classes."],
"Recursion": ["Write a recursive function to calculate factorial.", "Write a recursive function to print numbers from n to 1."],
"String Methods": ["Use string method to convert text to uppercase.", "Find the length of a string and print it."],
"File Handling": ["Open a file and write 'Hello World' to it.", "Read content from a file and print it."]
}
last_practice_question = ""
def ask_python_tutor(user_input):
try:
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[system_message, {"role": "user", "content": user_input}],
temperature=0.1,
max_tokens=1500
)
return response.choices[0].message.content
except Exception as e:
return f"Error: {e}"
def get_practice_question(topic):
import random
global last_practice_question
questions = practice_questions.get(topic, [])
if not questions:
return "No questions available for this topic."
q = random.choice(questions)
last_practice_question = q
return q
def check_practice_answer(user_answer):
prompt = f"The user answered this prompt: '{last_practice_question}'.\nTheir answer:\n{user_answer}\nGive friendly feedback."
try:
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "system", "content": "You are a friendly Python tutor reviewing beginner code."}, {"role": "user", "content": prompt}],
temperature=0.2,
max_tokens=500
)
return response.choices[0].message.content
except Exception as e:
return f"Error: {e}"
def get_daily_tip():
import random
tip_prompts = [
"Share one beginner-friendly Python tip.",
"Give a helpful Python trick for someone just starting out.",
"What’s a common Python mistake beginners should avoid?",
"Suggest a short and practical Python tip.",
"Tell me a best practice when writing Python code for beginners."
]
prompt = random.choice(tip_prompts)
try:
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "user", "content": prompt}],
temperature=0.7,
max_tokens=120
)
return response.choices[0].message.content
except Exception as e:
return f"Error: {e}"
project_list = [
"Number Guessing Game",
"BMI Calculator",
"To-Do List App",
"Rock Paper Scissors",
"Palindrome Checker",
"Password Generator",
"Simple Calculator",
"Expense Tracker",
"Tic Tac Toe Game",
"Age Calculator"
]
def get_project_code(project_name):
prompt = f"Write beginner-friendly Python code for a '{project_name}' project with clear comments and a short introduction."
try:
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "user", "content": prompt}],
temperature=0.6,
max_tokens=600
)
code = response.choices[0].message.content
motivation = "\n\n🧠 Here's a starting point. Try to enhance it!\n✨ Add features, personalize it, or rebuild it from scratch. That's how real learning happens!"
return code + motivation
except Exception as e:
return f"Error: {e}"
with gr.Blocks() as demo:
gr.Markdown("## 🐍 Python Tutor App ")
with gr.Tab("💬 Python Tutor"):
chatbot_input = gr.Textbox(label="Ask a Python Question")
chatbot_output = gr.Textbox(label="Tutor's Response", lines=6)
with gr.Row():
ask_btn = gr.Button("Ask")
clear_btn = gr.Button("Clear")
ask_btn.click(fn=ask_python_tutor, inputs=chatbot_input, outputs=chatbot_output)
clear_btn.click(fn=lambda: ("", ""), inputs=[], outputs=[chatbot_input, chatbot_output])
with gr.Tab("🧪 Practice Python"):
topic_dropdown = gr.Dropdown(choices=list(practice_questions.keys()), label="Choose Topic", value="Variables")
practice_display = gr.Textbox(label="Practice Prompt", interactive=False)
user_input = gr.Textbox(label="Your Answer", lines=10)
feedback_box = gr.Textbox(label="Tutor's Feedback", lines=5)
with gr.Row():
get_q = gr.Button("Get Question")
submit_a = gr.Button("Submit Answer")
get_q.click(fn=get_practice_question, inputs=topic_dropdown, outputs=practice_display)
submit_a.click(fn=check_practice_answer, inputs=user_input, outputs=feedback_box)
with gr.Tab("💡 Daily Python Tip"):
tip_display = gr.Textbox(label="Today's Tip", lines=3)
get_tip_btn = gr.Button("Get Daily Tip")
get_tip_btn.click(fn=get_daily_tip, inputs=[], outputs=tip_display)
with gr.Tab("🔧 Project Ideas"):
project_selector = gr.Dropdown(choices=project_list, label="Choose a Project", value="Number Guessing Game")
project_display = gr.Textbox(label="Project Idea + Code", lines=14)
gen_btn = gr.Button("Generate Project Code")
gen_btn.click(fn=get_project_code, inputs=project_selector, outputs=project_display)
demo.launch()