Spaces:
Sleeping
Sleeping
File size: 6,134 Bytes
8d04a30 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | import gradio as gr
import sqlite3
import fitz # PyMuPDF
import re
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import os
from collections import Counter
from datetime import datetime
# ==============================
# DATABASE SETUP
# ==============================
conn = sqlite3.connect("exam_trends.db", check_same_thread=False)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS past_questions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
year INTEGER,
question TEXT,
topic TEXT
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS current_questions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
question TEXT,
topic TEXT
)
""")
conn.commit()
# ==============================
# PDF TEXT EXTRACTION
# ==============================
def extract_text_from_pdf(file):
text = ""
pdf = fitz.open(stream=file.read(), filetype="pdf")
for page in pdf:
text += page.get_text()
return text
# ==============================
# SIMPLE QUESTION SEGMENTATION
# ==============================
def extract_questions(text):
questions = re.split(r'\n\d+\.|\nQ\d+', text)
return [q.strip() for q in questions if len(q.strip()) > 20]
# ==============================
# SIMPLE TOPIC CLASSIFIER
# (Basic keyword approach)
# ==============================
def classify_topic(question):
question = question.lower()
if "integral" in question or "derivative" in question:
return "Calculus"
elif "triangle" in question or "angle" in question:
return "Geometry"
elif "probability" in question:
return "Probability"
elif "matrix" in question:
return "Linear Algebra"
else:
return "Algebra"
# ==============================
# STORE PAST PAPERS
# ==============================
def upload_past_papers(files):
for file in files:
text = extract_text_from_pdf(file)
questions = extract_questions(text)
year = datetime.now().year # Simplified
for q in questions:
topic = classify_topic(q)
cursor.execute(
"INSERT INTO past_questions (year, question, topic) VALUES (?, ?, ?)",
(year, q, topic),
)
conn.commit()
return "Past papers uploaded and processed successfully."
# ==============================
# STORE CURRENT PAPER
# ==============================
def upload_current_paper(file):
text = extract_text_from_pdf(file)
questions = extract_questions(text)
for q in questions:
topic = classify_topic(q)
cursor.execute(
"INSERT INTO current_questions (question, topic) VALUES (?, ?)",
(q, topic),
)
conn.commit()
return "Current paper uploaded successfully."
# ==============================
# TREND ANALYSIS ENGINE
# ==============================
def analyze_trends():
cursor.execute("SELECT topic FROM past_questions")
past_topics = [row[0] for row in cursor.fetchall()]
cursor.execute("SELECT topic FROM current_questions")
current_topics = [row[0] for row in cursor.fetchall()]
past_count = Counter(past_topics)
current_count = Counter(current_topics)
results = []
for topic, freq in past_count.items():
frequency_weight = freq
recency_weight = freq * 0.2
gap_weight = 1 if topic not in current_count else 0
prediction_score = (
frequency_weight * 0.5
+ recency_weight * 0.3
+ gap_weight * 0.2
)
results.append((topic, prediction_score))
results.sort(key=lambda x: x[1], reverse=True)
df = pd.DataFrame(results, columns=["Topic", "Prediction Score"])
return df
# ==============================
# HEATMAP VISUALIZATION
# ==============================
def generate_heatmap():
cursor.execute("SELECT topic FROM past_questions")
topics = [row[0] for row in cursor.fetchall()]
count = Counter(topics)
df = pd.DataFrame.from_dict(count, orient='index', columns=['Frequency'])
df = df.sort_values(by='Frequency', ascending=False)
plt.figure()
plt.imshow(np.array(df['Frequency']).reshape(-1,1))
plt.yticks(range(len(df.index)), df.index)
plt.xticks([])
plt.title("Topic Heatmap")
plt.colorbar()
plt.tight_layout()
return plt
# ==============================
# AI QUESTION GENERATOR (Simple)
# ==============================
def generate_predicted_questions():
df = analyze_trends()
top_topics = df["Topic"].head(3).tolist()
output = "Predicted High Probability Questions:\n\n"
for topic in top_topics:
output += f"โข Create an exam-level question from {topic}\n"
return output
# ==============================
# GRADIO UI
# ==============================
with gr.Blocks() as demo:
gr.Markdown("# ๐ AI Predictive Exam Intelligence System")
with gr.Tab("๐ Upload Past 5 Years Papers"):
past_files = gr.File(file_count="multiple")
past_button = gr.Button("Upload & Analyze")
past_output = gr.Textbox()
past_button.click(upload_past_papers, inputs=past_files, outputs=past_output)
with gr.Tab("๐ Upload Current Year Paper"):
current_file = gr.File()
current_button = gr.Button("Upload Current Paper")
current_output = gr.Textbox()
current_button.click(upload_current_paper, inputs=current_file, outputs=current_output)
with gr.Tab("๐ Trend Analysis"):
analyze_button = gr.Button("Run Trend Analysis")
trend_output = gr.Dataframe()
analyze_button.click(analyze_trends, outputs=trend_output)
with gr.Tab("๐ฅ Topic Heatmap"):
heatmap_button = gr.Button("Generate Heatmap")
heatmap_output = gr.Plot()
heatmap_button.click(generate_heatmap, outputs=heatmap_output)
with gr.Tab("๐ฎ Predicted Questions"):
predict_button = gr.Button("Generate Predictions")
predict_output = gr.Textbox()
predict_button.click(generate_predicted_questions, outputs=predict_output)
demo.launch() |