yuvraj-yadav commited on
Commit
e9b7c7d
·
verified ·
1 Parent(s): e9ec0e9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -88
app.py CHANGED
@@ -1,97 +1,40 @@
 
 
1
  import gradio as gr
2
- import pandas as pd
3
- import os
4
- import google.generativeai as genai
5
- import fitz # PyMuPDF to read PDF
6
 
7
- # Load Gemini API key from Hugging Face secret
8
- genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
9
- model = genai.GenerativeModel("gemini-pro")
10
 
11
- # PDF reading utility
12
- def extract_text_from_pdf(pdf_file):
13
- text = ""
14
- doc = fitz.open(pdf_file.name)
15
- for page in doc:
16
- text += page.get_text()
17
- return text.strip()
18
 
19
- # Gemini prompting logic
20
- def evaluate_prompt(question, solution, instructions):
21
- prompt = f"""
22
- You are an expert math evaluator. Follow these instructions carefully:
23
-
24
- {instructions}
25
-
26
- ---
27
-
28
- **Question:**
29
- {question}
30
-
31
- **Student's Solution:**
32
- {solution}
33
-
34
- Evaluate the solution. Say whether it's correct or not. If incorrect, give a clear and detailed explanation of why it's wrong and how to fix it.
35
 
36
- Respond in this format:
37
- Correct?: [Yes/No]
38
- Reasoning: <explanation>
39
  """
40
- response = model.generate_content(prompt)
41
- return response.text.strip()
42
 
43
- # Handler for single text input
44
- def evaluate_text_inputs(question, solution, instructions_file, instructions_text):
45
- instructions = instructions_text or extract_text_from_pdf(instructions_file) if instructions_file else ""
46
- result = evaluate_prompt(question, solution, instructions)
47
- return result
48
 
49
- # Handler for CSV batch input
50
- def evaluate_csv(csv_file, instructions_file, instructions_text):
51
- instructions = instructions_text or extract_text_from_pdf(instructions_file) if instructions_file else ""
52
- df = pd.read_csv(csv_file.name)
53
-
54
- evaluations = []
55
- for _, row in df.iterrows():
56
- q = row.get('question', '')
57
- s = row.get('solution', '')
58
- try:
59
- eval_result = evaluate_prompt(q, s, instructions)
60
- evaluations.append(eval_result)
61
- except Exception as e:
62
- evaluations.append(f"Error: {e}")
63
-
64
- df['evaluation'] = evaluations
65
- output_path = "evaluated_results.csv"
66
- df.to_csv(output_path, index=False)
67
- return output_path
68
 
69
- # Gradio UI
70
- with gr.Blocks() as demo:
71
- gr.Markdown("## 🤖 Solution Evaluator (Gemini API)")
72
- gr.Markdown("Evaluate student solutions using Google's Gemini API.")
73
-
74
- with gr.Tab("📝 Single Evaluation"):
75
- with gr.Row():
76
- question_input = gr.Textbox(label="Question", lines=3)
77
- solution_input = gr.Textbox(label="Solution", lines=6)
78
- with gr.Row():
79
- instructions_text = gr.Textbox(label="Instructions (text)", lines=6)
80
- instructions_file = gr.File(label="Upload Instructions PDF", file_types=[".pdf"])
81
- output_single = gr.Textbox(label="Evaluation Result", lines=8)
82
- btn_single = gr.Button("Evaluate Solution")
83
- btn_single.click(fn=evaluate_text_inputs,
84
- inputs=[question_input, solution_input, instructions_file, instructions_text],
85
- outputs=output_single)
86
-
87
- with gr.Tab("📄 Batch CSV Evaluation"):
88
- csv_file = gr.File(label="Upload CSV (columns: question, solution)", file_types=[".csv"])
89
- inst_text = gr.Textbox(label="Instructions (text)", lines=6)
90
- inst_pdf = gr.File(label="Upload Instructions PDF", file_types=[".pdf"])
91
- output_csv = gr.File(label="Download Evaluated CSV")
92
- btn_batch = gr.Button("Evaluate All")
93
- btn_batch.click(fn=evaluate_csv,
94
- inputs=[csv_file, inst_pdf, inst_text],
95
- outputs=output_csv)
96
-
97
- demo.launch()
 
1
+ !pip install transformers accelerate gradio
2
+ from transformers import pipeline
3
  import gradio as gr
 
 
 
 
4
 
5
+ generator = pipeline("text-generation", model="tiiuae/falcon-rw-1b") # Or try flan-t5-base
 
 
6
 
7
+ prompt = """
8
+ You are a professor of Discrete Mathematics. Generate an original and creative discrete math question (not copied or templated), suitable for university-level students.
9
+ Include only the question. Avoid multiple-choice format.
 
 
 
 
10
 
11
+ Topic: Combinatorics
12
+ Difficulty: Medium
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ Question:
 
 
15
  """
16
+ response = generator(prompt, max_new_tokens=150)[0]['generated_text']
17
+ print(response)
18
 
 
 
 
 
 
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ def generate_question(topic, difficulty):
22
+ prompt = f"""
23
+ You are a professor of Discrete Mathematics. Generate an original and creative discrete math question.
24
+ Topic: {topic}
25
+ Difficulty: {difficulty}
26
+ Question:
27
+ """
28
+ result = generator(prompt, max_new_tokens=150)[0]['generated_text']
29
+ return result.split("Question:")[-1].strip()
30
+
31
+ topics = ["Combinatorics", "Logic", "Set Theory", "Functions", "Relations", "Graph Theory"]
32
+ difficulties = ["Easy", "Medium", "Hard"]
33
+
34
+ gr.Interface(
35
+ fn=generate_question,
36
+ inputs=[gr.Dropdown(choices=topics, label="Select Topic"),
37
+ gr.Dropdown(choices=difficulties, label="Select Difficulty")],
38
+ outputs="text",
39
+ title="Discrete Math Question Generator"
40
+ ).launch()