Spaces:
Sleeping
Sleeping
File size: 7,837 Bytes
255d29d a3d7665 255d29d a3d7665 db33fda 255d29d dad8e64 255d29d a3d7665 db33fda 57e381d db33fda dad8e64 255d29d dad8e64 255d29d dad8e64 255d29d dad8e64 255d29d dad8e64 255d29d dad8e64 255d29d dad8e64 57e381d dad8e64 255d29d 57e381d db33fda dad8e64 255d29d db33fda dad8e64 255d29d dad8e64 255d29d dad8e64 255d29d db33fda 255d29d db33fda 255d29d a3d7665 dad8e64 255d29d dad8e64 db33fda 255d29d dad8e64 255d29d a3d7665 dad8e64 db33fda 255d29d db33fda 255d29d dad8e64 db33fda 255d29d dad8e64 255d29d db33fda dad8e64 255d29d dad8e64 255d29d db33fda dad8e64 255d29d dad8e64 255d29d a3d7665 255d29d db33fda 255d29d db33fda 255d29d db33fda 255d29d dad8e64 a3d7665 255d29d db33fda 255d29d 57e381d 255d29d a3d7665 255d29d a3d7665 255d29d dad8e64 db33fda 255d29d dad8e64 255d29d db33fda 57e381d db33fda 255d29d dad8e64 db33fda 255d29d dad8e64 255d29d dad8e64 255d29d db33fda 255d29d db33fda 255d29d dad8e64 712d1db dad8e64 db33fda 255d29d db33fda 255d29d dad8e64 db33fda 255d29d dad8e64 255d29d db33fda 255d29d dad8e64 db33fda 255d29d db33fda 255d29d db33fda 255d29d db33fda 255d29d db33fda 255d29d a3d7665 db33fda a3d7665 255d29d 57e381d db33fda 255d29d db33fda 712d1db 255d29d a3d7665 db33fda 255d29d db33fda 255d29d | 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 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 | from docx import Document
import pytesseract
from PIL import Image
import fitz
import gradio as gr
import threading
import pathlib
import os
# --------------------------------------------------
# TOKEN RESOLUTION
# --------------------------------------------------
def resolve_token(ui_token):
if ui_token.strip():
return ui_token.strip()
env_token = os.getenv("hgface_tok")
if env_token:
return env_token.strip()
return ""
# --------------------------------------------------
# FILE TEXT EXTRACTION
# --------------------------------------------------
SUPPORTED_EXT = (
".pdf", ".docx", ".txt", ".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tiff"
)
def extract_text_from_file(filepath):
if not filepath:
return ""
if hasattr(filepath,"name"):
filepath = filepath.name
ext = pathlib.Path(filepath).suffix.lower()
try:
if ext == ".pdf":
doc = fitz.open(filepath)
text = []
for page in doc:
text.append(page.get_text())
return "\n".join(text)
elif ext == ".docx":
doc = Document(filepath)
return "\n".join(p.text for p in doc.paragraphs)
elif ext == ".txt":
with open(filepath,"r", encoding="utf-8", errors="ignore") as f:
return f.read()
elif ext in (".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tiff"):
try:
img = Image.open(filepath)
return pytesseract.image_to_string(img)
except Exception as e:
return "OCR failed: " + str(e)
else:
return "Unsupported file type: " + ext
except Exception as e:
return "Could not read file: " + str(e)
# --------------------------------------------------
# MODELS
# --------------------------------------------------
MODELS = {
"Gemma 3 270M [0.6GB | Lightning-fast Edge]": "google/gemma-3-270m-it",
"Qwen 3 0.6B GGUF [0.5GB | Classroom Assistant]": "Qwen/Qwen3-0.6B-GGUF",
"TinyLlama 1.1B [0.5GB]": "TinyLlama/TinyLlama-1.1B-Chat-v1.0",
"Qwen 3.5 2B [2.4GB | The Student Tutor]": "Qwen/Qwen3.5-2B",
"Phi-4 Mini [1.8GB | Logical Powerhouse]": "microsoft/Phi-4-mini-instruct",
"Gemma 3 1B [2.1GB | Stable & Coherent]": "google/gemma-3-1b-it",
"Qwen 3.5 9B [7.8GB | BEST FOR LESSON PLANS]": "Qwen/Qwen3.5-9B",
"Llama 3.1 8B [5.2GB | Industry Standard]": "meta-llama/Meta-Llama-3.1-8B-Instruct",
"Mistral Small 3 [7.1GB | Concise & Accurate]": "mistralai/Mistral-Small-3-Instruct",
"Gemma 3 9B [6.3GB | Creative & Safe]": "google/gemma-3-9b-it",
"Mistral Small 12B [9.5GB | Perfect VRAM Balance]": "mistralai/Mistral-Nemo-Instruct-2407",
"Qwen 3.5 27B [18GB | Dense Curriculum Architect]": "Qwen/Qwen3.5-27B",
}
ALL_MODEL_NAMES = list(MODELS.keys())
# --------------------------------------------------
# PIPELINE CACHE
# --------------------------------------------------
_pipeline_cache = {}
_pipeline_lock = threading.Lock()
def get_pipeline(model_id, hf_token):
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
with _pipeline_lock:
if model_id not in _pipeline_cache:
try:
kwargs = {
"trust_remote_code": True
}
if hf_token:
kwargs["token"] = hf_token
tokenizer = AutoTokenizer.from_pretrained(
model_id,
**kwargs
)
model = AutoModelForCausalLM.from_pretrained(
model_id,
device_map="cpu",
**kwargs
)
pipe = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer
)
_pipeline_cache[model_id] = pipe
except Exception as e:
return None, str(e)
return _pipeline_cache[model_id], None
# --------------------------------------------------
# INFERENCE
# --------------------------------------------------
SYSTEM_MSG = "You are an expert educational assistant. Use markdown."
def ask_llm(model_label, prompt, hf_token=""):
token = resolve_token(hf_token)
model_id = MODELS[model_label]
pipe, err = get_pipeline(model_id, token)
if err:
return "Model load error:\n" + err
try:
combined = SYSTEM_MSG + "\n\n" + prompt
out = pipe(
combined,
max_new_tokens=2048,
do_sample=True,
temperature=0.6,
top_p=0.9,
repetition_penalty=1.15,
no_repeat_ngram_size=3
)
text = out[0]["generated_text"]
if text.startswith(combined):
text = text[len(combined):]
return text.strip()
except Exception as e:
return "Inference error:\n" + str(e)
# --------------------------------------------------
# PROMPTS
# --------------------------------------------------
def make_prompts(topic):
return {
"lesson":
"Create a structured lesson plan for classroom teaching.\n"
"Include:\n"
"- Learning objectives\n"
"- Introduction\n"
"- Concept explanation\n"
"- Examples\n"
"- Case study\n"
"- Classroom activity\n"
"- Assessment\n\n"
"Topic:\n"+topic,
"qa":
"Generate 10 exam questions with answers.\n\nTopic:\n"+topic,
"mcq":
"Generate 10 MCQs with 4 options and answers.\n\nTopic:\n"+topic,
"summary":
"Summarize the topic in 250-300 words.\n\nTopic:\n"+topic,
}
def generate_content(text, file, model_label, token):
file_text = extract_text_from_file(file) if file else ""
syllabus = (text + "\n\n" + file_text).strip()
if not syllabus:
yield ("Provide topic or file","","","","")
return
prompts = make_prompts(syllabus)
WAIT = "Generating..."
results = [WAIT,WAIT,WAIT,WAIT,WAIT]
yield tuple(results)
order = ["lesson", "qa", "mcq", "summary"]
for i, key in enumerate(order):
res = ask_llm(model_label, prompts[key], token)
results[i] = res
yield tuple(results)
# --------------------------------------------------
# UI
# --------------------------------------------------
CSS = """
body,.gradio-container{
font-family:Inter,sans-serif!important;
}
"""
with gr.Blocks() as demo:
gr.Markdown("# 🎓 AI Study Material Generator")
with gr.Row():
with gr.Column():
text_input = gr.Textbox(
placeholder="Paste syllabus or topic",
lines=6
)
file_input = gr.File(
label="Upload syllabus file"
)
with gr.Column():
model_selector = gr.Dropdown(
choices=ALL_MODEL_NAMES,
value=ALL_MODEL_NAMES[0],
label="Model"
)
token_box = gr.Textbox(
label="HF Token (optional)",
type="password"
)
btn = gr.Button("Generate")
with gr.Tabs():
with gr.TabItem("Lesson Plan"):
lesson = gr.Markdown()
with gr.TabItem("Q&A"):
qa = gr.Markdown()
with gr.TabItem("MCQ"):
mcq = gr.Markdown()
with gr.TabItem("Summary"):
summary = gr.Markdown()
btn.click(
fn=generate_content,
inputs=[text_input,file_input,model_selector,token_box],
outputs=[lesson, qa, mcq, summary]
)
demo.launch(
theme=gr.themes.Soft(
primary_hue="indigo",
secondary_hue="purple"
),
css=CSS
) |