Spaces:
Sleeping
Sleeping
| import os | |
| import gradio as gr | |
| import openai | |
| from sentence_transformers import SentenceTransformer, util | |
| # Load similarity model | |
| similarity_model = SentenceTransformer('all-MiniLM-L6-v2') | |
| # Get OpenAI API key from Hugging Face secret | |
| openai.api_key = "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" | |
| def generate_unique_questions(topic, difficulty, num_questions, constraints): | |
| base_prompt = f""" | |
| You are an AI for generating lab experiment questions. | |
| Topic: {topic} | |
| Difficulty: {difficulty} | |
| Constraints: {constraints if constraints else "None"}. | |
| Task: | |
| - Generate {num_questions} unique but equivalent lab questions | |
| - Ensure same difficulty level for all | |
| - Avoid repeating exact wording | |
| - Keep questions answerable in similar time | |
| - Return them in a numbered list. | |
| """ | |
| response = openai.ChatCompletion.create( | |
| model="gpt-3.5-turbo", | |
| messages=[{"role": "system", "content": "You are an expert question generator for labs."}, | |
| {"role": "user", "content": base_prompt}], | |
| temperature=0.9 | |
| ) | |
| # Extract questions | |
| raw_questions = response.choices[0].message['content'].strip().split("\n") | |
| questions = [q.strip() for q in raw_questions if q.strip()] | |
| # Ensure uniqueness (semantic check) | |
| final_questions = [] | |
| embeddings = [] | |
| for q in questions: | |
| emb = similarity_model.encode(q, convert_to_tensor=True) | |
| if not any(util.cos_sim(emb, e) > 0.85 for e in embeddings): | |
| embeddings.append(emb) | |
| final_questions.append(q) | |
| return "\n".join(final_questions) | |
| # Gradio UI | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# 🔬 AI Lab Question Generator") | |
| gr.Markdown("Generate **unique but equivalent** lab questions for each student.") | |
| topic = gr.Textbox(label="Lab Topic", placeholder="e.g., Ohm's Law Experiment") | |
| difficulty = gr.Dropdown(["Easy", "Medium", "Hard"], label="Difficulty", value="Medium") | |
| num_questions = gr.Slider(1, 20, value=5, step=1, label="Number of Questions") | |
| constraints = gr.Textbox(label="Extra Constraints (Optional)", placeholder="e.g., include diagram-based question") | |
| generate_btn = gr.Button("Generate Questions") | |
| output = gr.Textbox(label="Generated Questions", lines=10) | |
| generate_btn.click(generate_unique_questions, | |
| inputs=[topic, difficulty, num_questions, constraints], | |
| outputs=output) | |
| demo.launch() | |