Spark_Quiz / app.py
nnsohamnn's picture
Update app.py
bb48f32 verified
from flask import Flask, render_template, request, jsonify
import os
import google.generativeai as genai
app = Flask(__name__)
# Retrieve the Gemini API key from environment variables
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
# Set the Gemini 2.5 Flash Preview model name
MODEL = "gemini-2.5-flash"
def generate_quiz(parameters):
"""
Builds a prompt based on user parameters, sends it to the Gemini 2.5 Flash API,
and returns the quiz generated by the LLM in Markdown format.
"""
total_questions = sum(parameters['type_counts'].get(t, 0) for t in parameters['question_types'])
if total_questions <= 0:
return {
"quiz_text": "Error: Please request at least one question.\n\nNo questions were requested. Please select at least one question type with a quantity greater than 0."
}
if not GEMINI_API_KEY:
return {
"quiz_text": "Error: API key not configured.\n\nThe GEMINI_API_KEY environment variable is not set. Please configure it to use the Gemini API."
}
# Build the prompt dynamically using the provided parameters
prompt = f"Generate a quiz with the following parameters:\n"
prompt += f"- Topic: {parameters['topic']}\n"
prompt += f"- Difficulty: {parameters['difficulty']}\n"
type_lines = []
for t in parameters['question_types']:
count = parameters['type_counts'].get(t, 1)
type_lines.append(f"{t} ({count})")
prompt += f"- Question types: {', '.join(type_lines)}\n"
if parameters.get("subtopics"):
prompt += f"- Sub-topics: {', '.join(parameters['subtopics'])}\n"
if parameters.get("keywords"):
prompt += f"- Context keywords: {', '.join(parameters['keywords'])}\n"
if parameters.get("audience"):
prompt += f"- Target audience: {parameters['audience']}\n"
if parameters.get("language", "en") != "en":
prompt += f"- Language: {parameters['language']}\n"
prompt += f"- Include explanations: {'Yes' if parameters.get('include_explanations', False) else 'No'}\n"
if parameters.get("max_length"):
prompt += f"- Maximum length per question: {parameters['max_length']} words\n"
prompt += (
"Please format the quiz in Markdown as follows:\n"
"1. Start with a heading like # Topic Quiz\n"
"2. For each question, use a subheading like ## Question X: Type (e.g., ## Question 1: Multiple Choice)\n"
"3. For multiple choice questions, label options as - A), - B), - C), - D)\n"
"4. For other question types (e.g., Short Answer, True/False, or custom types like Fill-in-the-blank), present the question clearly and provide the answer format expected (e.g., for Short Answer, provide a brief sentence; for True/False, state True or False; for custom types, follow a similar clear format).\n"
"5. If explanations are requested, include them after each question in a paragraph starting with **Explanation:**\n"
"6. Make sure all information is factually correct\n"
"7. Ensure each question's answer matches its explanation, and place the explanation after the answer.\n"
)
try:
genai.configure(api_key=GEMINI_API_KEY)
model = genai.GenerativeModel(model_name=MODEL)
response = model.generate_content(prompt)
quiz_text = response.text
if not quiz_text or not quiz_text.strip():
return {
"quiz_text": "Error: No quiz content generated.\n\nThe API returned an empty response. This might be due to rate limits or an unexpected response format."
}
return {
"quiz_text": quiz_text
}
except Exception as e:
return {
"quiz_text": f"Error: API request failed.\n\nThe request to the Gemini API failed: {str(e)}. Please check your network connection or try again later."
}
@app.route('/')
def index():
# You should have an 'index.html' template in your templates folder
return render_template('index.html')
@app.route('/generate_quiz', methods=['POST'])
def generate_quiz_endpoint():
parameters = request.get_json()
result = generate_quiz(parameters)
return jsonify(result)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860)