Spaces:
Sleeping
Sleeping
Commit
Β·
7402600
1
Parent(s):
270bfd7
better script
Browse files- app.py +408 -241
- gradio_app.py +502 -465
app.py
CHANGED
@@ -1,41 +1,58 @@
|
|
1 |
import gradio as gr
|
2 |
import json
|
3 |
-
import
|
4 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
5 |
import logging
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
7 |
import tempfile
|
8 |
-
|
|
|
|
|
|
|
|
|
9 |
|
10 |
# Setup logging
|
11 |
-
logging.basicConfig(
|
|
|
|
|
|
|
12 |
logger = logging.getLogger(__name__)
|
13 |
|
14 |
class SyllabusFormatter:
|
15 |
def __init__(self, model_name="microsoft/Phi-3-mini-4k-instruct"):
|
|
|
16 |
self.model_name = model_name
|
17 |
self.tokenizer = None
|
18 |
self.model = None
|
19 |
self.pipe = None
|
20 |
-
self.
|
21 |
-
self.
|
22 |
|
23 |
-
def
|
24 |
-
"""
|
|
|
|
|
|
|
25 |
try:
|
|
|
|
|
26 |
# Load tokenizer
|
27 |
self.tokenizer = AutoTokenizer.from_pretrained(
|
28 |
self.model_name,
|
29 |
trust_remote_code=True
|
30 |
)
|
31 |
|
32 |
-
# Load model with
|
33 |
self.model = AutoModelForCausalLM.from_pretrained(
|
34 |
self.model_name,
|
35 |
-
torch_dtype=torch.float16,
|
36 |
-
device_map="auto",
|
37 |
trust_remote_code=True,
|
38 |
-
|
39 |
)
|
40 |
|
41 |
# Create pipeline
|
@@ -43,23 +60,21 @@ class SyllabusFormatter:
|
|
43 |
"text-generation",
|
44 |
model=self.model,
|
45 |
tokenizer=self.tokenizer,
|
46 |
-
|
47 |
-
|
48 |
-
do_sample=True,
|
49 |
-
top_p=0.9,
|
50 |
-
repetition_penalty=1.1
|
51 |
)
|
52 |
|
53 |
-
|
|
|
54 |
return True
|
55 |
|
56 |
except Exception as e:
|
57 |
-
logger.error(f"Error
|
58 |
return False
|
59 |
-
|
60 |
def create_formatting_prompt(self, unit_content: str, unit_name: str, subject_name: str = "") -> str:
|
61 |
-
"""Create a
|
62 |
-
prompt = f"""<|system|>You are a professional academic syllabus formatter. Your
|
63 |
|
64 |
RULES:
|
65 |
1. PRESERVE every single word, topic, and concept from the original
|
@@ -83,254 +98,406 @@ Unit: {unit_name}
|
|
83 |
Original content (poorly formatted):
|
84 |
{unit_content}
|
85 |
|
86 |
-
Task: Reformat this content to be beautifully organized and readable. Do NOT add any new information - only restructure what's already there
|
87 |
|
88 |
<|assistant|>"""
|
89 |
return prompt
|
90 |
|
91 |
-
def
|
92 |
-
"""Format a single unit's content
|
|
|
|
|
93 |
try:
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
# Generate formatted content
|
98 |
-
response = self.pipe(prompt)
|
99 |
-
|
100 |
-
# Extract formatted content
|
101 |
-
generated_text = response[0]['generated_text']
|
102 |
-
assistant_start = generated_text.find("<|assistant|>")
|
103 |
-
if assistant_start != -1:
|
104 |
-
formatted_content = generated_text[assistant_start + len("<|assistant|>"):].strip()
|
105 |
-
else:
|
106 |
-
formatted_content = generated_text.strip()
|
107 |
-
|
108 |
-
# Clean up and validate
|
109 |
-
formatted_content = self.clean_generated_content(formatted_content)
|
110 |
-
if not self.validate_formatted_content(unit_content, formatted_content):
|
111 |
-
return unit_content
|
112 |
|
113 |
-
|
114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
except Exception as e:
|
116 |
-
logger.error(f"Error formatting
|
117 |
-
return unit_content
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
def validate_formatted_content(self, original: str, formatted: str) -> bool:
|
120 |
-
"""Validate that formatted content preserves
|
121 |
-
# Basic validation
|
122 |
if len(formatted) < len(original) * 0.4:
|
123 |
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
124 |
return True
|
125 |
-
|
126 |
-
def
|
127 |
-
"""
|
128 |
-
|
129 |
-
for token in ["<|system|>", "<|user|>", "<|assistant|>"]:
|
130 |
-
content = content.replace(token, "")
|
131 |
-
|
132 |
-
# Clean up extra whitespace
|
133 |
-
content = "\n".join(line.strip() for line in content.split("\n") if line.strip())
|
134 |
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
total_units = 0
|
142 |
-
processed = 0
|
143 |
-
|
144 |
-
def count_units(data):
|
145 |
-
count = 0
|
146 |
-
if isinstance(data, dict):
|
147 |
-
for value in data.values():
|
148 |
-
if isinstance(value, dict):
|
149 |
-
count += count_units(value)
|
150 |
-
elif isinstance(value, str) and "Unit" in str(value):
|
151 |
-
count += 1
|
152 |
-
return count
|
153 |
-
|
154 |
-
total_units = count_units(syllabus_data.get("syllabus", {}))
|
155 |
-
logger.info(f"Total units to process: {total_units}")
|
156 |
-
|
157 |
-
# Process each branch
|
158 |
-
for branch_name, branch_data in syllabus_data.get("syllabus", {}).items():
|
159 |
-
if not isinstance(branch_data, dict):
|
160 |
continue
|
161 |
|
162 |
-
|
163 |
-
|
164 |
-
if not isinstance(sem_data, dict):
|
165 |
continue
|
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 |
-
if formatter is None:
|
217 |
-
formatter = SyllabusFormatter()
|
218 |
-
return formatter.setup_model()
|
219 |
-
return True
|
220 |
|
221 |
-
def
|
222 |
-
"""
|
223 |
try:
|
224 |
-
#
|
225 |
-
|
226 |
-
|
|
|
|
|
|
|
|
|
227 |
|
228 |
-
|
229 |
-
content = file.read()
|
230 |
-
syllabus_data = json.loads(content)
|
231 |
|
232 |
-
#
|
233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
234 |
|
235 |
# Save to temporary file
|
236 |
-
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as
|
237 |
-
json.dump(formatted_data,
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
|
|
|
|
242 |
except Exception as e:
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
theme = gr.themes.Soft(
|
247 |
-
primary_hue="indigo",
|
248 |
-
secondary_hue="blue",
|
249 |
-
).set(
|
250 |
-
body_background_fill="#fafafa",
|
251 |
-
body_background_fill_dark="#1a1a1a",
|
252 |
-
button_primary_background_fill="*primary_500",
|
253 |
-
button_primary_background_fill_hover="*primary_600"
|
254 |
-
)
|
255 |
-
|
256 |
-
# Gradio interface
|
257 |
-
title = "π Syllabus Formatter"
|
258 |
-
description = """
|
259 |
-
Transform your syllabus into a beautifully formatted, easy-to-read document using AI.
|
260 |
-
|
261 |
-
### Features:
|
262 |
-
- Preserves all original content
|
263 |
-
- Improves readability and organization
|
264 |
-
- Creates logical grouping and sections
|
265 |
-
- Adds professional formatting
|
266 |
-
|
267 |
-
Simply upload your JSON syllabus file and get a formatted version back!
|
268 |
-
"""
|
269 |
-
|
270 |
-
css = """
|
271 |
-
.feedback {
|
272 |
-
margin-top: 20px;
|
273 |
-
padding: 10px;
|
274 |
-
border-radius: 8px;
|
275 |
-
background-color: #f0f9ff;
|
276 |
-
border: 1px solid #bae6fd;
|
277 |
-
}
|
278 |
-
.dark .feedback {
|
279 |
-
background-color: #082f49;
|
280 |
-
border-color: #075985;
|
281 |
-
}
|
282 |
-
"""
|
283 |
|
284 |
-
|
285 |
-
|
286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
287 |
|
288 |
-
with
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
296 |
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
305 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
306 |
|
307 |
-
|
308 |
-
return "Processing your syllabus... This may take a few minutes depending on the size."
|
309 |
-
|
310 |
-
# Setup click event
|
311 |
-
process_btn.click(
|
312 |
-
fn=update_feedback,
|
313 |
-
inputs=[file_input],
|
314 |
-
outputs=[feedback],
|
315 |
-
queue=False
|
316 |
-
).then(
|
317 |
-
fn=process_file,
|
318 |
-
inputs=[file_input],
|
319 |
-
outputs=[output_file]
|
320 |
-
).success(
|
321 |
-
fn=lambda: "β¨ Syllabus formatting complete! You can now download the formatted file.",
|
322 |
-
outputs=[feedback]
|
323 |
-
)
|
324 |
-
|
325 |
-
gr.Markdown("""
|
326 |
-
### π Notes:
|
327 |
-
- The formatter preserves all original content while improving organization
|
328 |
-
- Processing time depends on the size of your syllabus
|
329 |
-
- For large files, please be patient as the AI processes each section
|
330 |
-
|
331 |
-
Made with β€οΈ using Microsoft's Phi-3 Mini model
|
332 |
-
""")
|
333 |
|
334 |
-
# Launch
|
335 |
if __name__ == "__main__":
|
336 |
-
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
import json
|
3 |
+
import time
|
|
|
4 |
import logging
|
5 |
+
import re
|
6 |
+
from typing import Dict, Any, List, Tuple
|
7 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
8 |
+
import threading
|
9 |
+
from datetime import datetime
|
10 |
+
import os
|
11 |
import tempfile
|
12 |
+
|
13 |
+
# Hugging Face Transformers
|
14 |
+
import torch
|
15 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
16 |
+
import gc
|
17 |
|
18 |
# Setup logging
|
19 |
+
logging.basicConfig(
|
20 |
+
level=logging.INFO,
|
21 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
22 |
+
)
|
23 |
logger = logging.getLogger(__name__)
|
24 |
|
25 |
class SyllabusFormatter:
|
26 |
def __init__(self, model_name="microsoft/Phi-3-mini-4k-instruct"):
|
27 |
+
"""Initialize the formatter with Phi-3 model"""
|
28 |
self.model_name = model_name
|
29 |
self.tokenizer = None
|
30 |
self.model = None
|
31 |
self.pipe = None
|
32 |
+
self.is_model_loaded = False
|
33 |
+
self.processing_lock = threading.Lock()
|
34 |
|
35 |
+
def load_model(self):
|
36 |
+
"""Load the Phi-3 model with optimizations"""
|
37 |
+
if self.is_model_loaded:
|
38 |
+
return True
|
39 |
+
|
40 |
try:
|
41 |
+
logger.info(f"Loading model: {self.model_name}")
|
42 |
+
|
43 |
# Load tokenizer
|
44 |
self.tokenizer = AutoTokenizer.from_pretrained(
|
45 |
self.model_name,
|
46 |
trust_remote_code=True
|
47 |
)
|
48 |
|
49 |
+
# Load model with optimizations
|
50 |
self.model = AutoModelForCausalLM.from_pretrained(
|
51 |
self.model_name,
|
52 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
53 |
+
device_map="auto" if torch.cuda.is_available() else None,
|
54 |
trust_remote_code=True,
|
55 |
+
low_cpu_mem_usage=True
|
56 |
)
|
57 |
|
58 |
# Create pipeline
|
|
|
60 |
"text-generation",
|
61 |
model=self.model,
|
62 |
tokenizer=self.tokenizer,
|
63 |
+
device=0 if torch.cuda.is_available() else -1,
|
64 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
|
|
|
|
|
|
|
65 |
)
|
66 |
|
67 |
+
self.is_model_loaded = True
|
68 |
+
logger.info("Model loaded successfully!")
|
69 |
return True
|
70 |
|
71 |
except Exception as e:
|
72 |
+
logger.error(f"Error loading model: {str(e)}")
|
73 |
return False
|
74 |
+
|
75 |
def create_formatting_prompt(self, unit_content: str, unit_name: str, subject_name: str = "") -> str:
|
76 |
+
"""Create a focused prompt for formatting syllabus content"""
|
77 |
+
prompt = f"""<|system|>You are a professional academic syllabus formatter. Your job is to take poorly formatted syllabus content and make it beautifully organized and readable.
|
78 |
|
79 |
RULES:
|
80 |
1. PRESERVE every single word, topic, and concept from the original
|
|
|
98 |
Original content (poorly formatted):
|
99 |
{unit_content}
|
100 |
|
101 |
+
Task: Reformat this content to be beautifully organized and readable. Do NOT add any new information - only restructure what's already there.<|end|>
|
102 |
|
103 |
<|assistant|>"""
|
104 |
return prompt
|
105 |
|
106 |
+
def format_single_unit(self, unit_data: Tuple[str, str, str, str, str]) -> Tuple[str, str, str, str, str]:
|
107 |
+
"""Format a single unit's content"""
|
108 |
+
branch, semester, subject, unit_name, unit_content = unit_data
|
109 |
+
|
110 |
try:
|
111 |
+
with self.processing_lock:
|
112 |
+
# Create prompt
|
113 |
+
prompt = self.create_formatting_prompt(unit_content, unit_name, subject)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
114 |
|
115 |
+
# Generate formatted content
|
116 |
+
response = self.pipe(
|
117 |
+
prompt,
|
118 |
+
max_new_tokens=2048,
|
119 |
+
temperature=0.1,
|
120 |
+
do_sample=True,
|
121 |
+
top_p=0.9,
|
122 |
+
repetition_penalty=1.1,
|
123 |
+
pad_token_id=self.tokenizer.eos_token_id,
|
124 |
+
eos_token_id=self.tokenizer.eos_token_id
|
125 |
+
)
|
126 |
+
|
127 |
+
# Extract formatted content
|
128 |
+
generated_text = response[0]['generated_text']
|
129 |
+
assistant_start = generated_text.find("<|assistant|>")
|
130 |
+
|
131 |
+
if assistant_start != -1:
|
132 |
+
formatted_content = generated_text[assistant_start + len("<|assistant|>"):].strip()
|
133 |
+
else:
|
134 |
+
formatted_content = generated_text[len(prompt):].strip()
|
135 |
+
|
136 |
+
# Clean up the content
|
137 |
+
formatted_content = self.clean_generated_content(formatted_content)
|
138 |
+
|
139 |
+
# Validate content
|
140 |
+
if self.validate_formatted_content(unit_content, formatted_content):
|
141 |
+
return (branch, semester, subject, unit_name, formatted_content)
|
142 |
+
else:
|
143 |
+
logger.warning(f"Validation failed for {subject} - {unit_name}")
|
144 |
+
return (branch, semester, subject, unit_name, unit_content)
|
145 |
+
|
146 |
except Exception as e:
|
147 |
+
logger.error(f"Error formatting {subject} - {unit_name}: {str(e)}")
|
148 |
+
return (branch, semester, subject, unit_name, unit_content)
|
149 |
+
|
150 |
+
def clean_generated_content(self, content: str) -> str:
|
151 |
+
"""Clean up generated content"""
|
152 |
+
# Remove special tokens
|
153 |
+
content = re.sub(r'<\|.*?\|>', '', content)
|
154 |
+
|
155 |
+
# Remove AI commentary
|
156 |
+
lines = content.split('\n')
|
157 |
+
cleaned_lines = []
|
158 |
+
|
159 |
+
for line in lines:
|
160 |
+
line = line.strip()
|
161 |
+
if (line.startswith("Here") and ("formatted" in line.lower() or "organized" in line.lower())) or \
|
162 |
+
line.startswith("I have") or line.startswith("The content has been") or \
|
163 |
+
line.startswith("Note:") or line.startswith("This formatted version"):
|
164 |
+
continue
|
165 |
+
if line:
|
166 |
+
cleaned_lines.append(line)
|
167 |
+
|
168 |
+
content = '\n'.join(cleaned_lines)
|
169 |
+
|
170 |
+
# Fix spacing
|
171 |
+
content = re.sub(r'\n\s*\n\s*\n+', '\n\n', content)
|
172 |
+
content = re.sub(r'\n([A-Z][^:\n]*:)\n', r'\n\n\1\n', content)
|
173 |
+
|
174 |
+
return content.strip()
|
175 |
+
|
176 |
def validate_formatted_content(self, original: str, formatted: str) -> bool:
|
177 |
+
"""Validate that formatted content preserves important information"""
|
|
|
178 |
if len(formatted) < len(original) * 0.4:
|
179 |
return False
|
180 |
+
|
181 |
+
# Check for preservation of key terms
|
182 |
+
original_words = set(re.findall(r'\b[A-Z][a-z]*(?:[A-Z][a-z]*)*\b', original))
|
183 |
+
formatted_words = set(re.findall(r'\b[A-Z][a-z]*(?:[A-Z][a-z]*)*\b', formatted))
|
184 |
+
|
185 |
+
missing_terms = original_words - formatted_words
|
186 |
+
if len(missing_terms) > len(original_words) * 0.3:
|
187 |
+
return False
|
188 |
+
|
189 |
return True
|
190 |
+
|
191 |
+
def extract_units_for_processing(self, syllabus_data: Dict[str, Any]) -> List[Tuple[str, str, str, str, str]]:
|
192 |
+
"""Extract all units for concurrent processing"""
|
193 |
+
units = []
|
|
|
|
|
|
|
|
|
|
|
194 |
|
195 |
+
for branch_name, branch_data in syllabus_data.get("syllabus", {}).items():
|
196 |
+
if not isinstance(branch_data, dict):
|
197 |
+
continue
|
198 |
+
|
199 |
+
for sem_name, sem_data in branch_data.items():
|
200 |
+
if not isinstance(sem_data, dict):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
201 |
continue
|
202 |
|
203 |
+
for subject_name, subject_data in sem_data.items():
|
204 |
+
if not isinstance(subject_data, dict) or "content" not in subject_data:
|
|
|
205 |
continue
|
206 |
|
207 |
+
content = subject_data["content"]
|
208 |
+
if not isinstance(content, dict):
|
209 |
+
continue
|
210 |
+
|
211 |
+
for unit_name, unit_content in content.items():
|
212 |
+
if unit_name.startswith("Unit") and isinstance(unit_content, str):
|
213 |
+
units.append((branch_name, sem_name, subject_name, unit_name, unit_content))
|
214 |
+
|
215 |
+
return units
|
216 |
+
|
217 |
+
def format_syllabus_concurrent(self, syllabus_data: Dict[str, Any], progress_callback=None, max_workers=4) -> Dict[str, Any]:
|
218 |
+
"""Format syllabus using concurrent processing"""
|
219 |
+
if not self.is_model_loaded:
|
220 |
+
if not self.load_model():
|
221 |
+
raise Exception("Failed to load model")
|
222 |
+
|
223 |
+
# Extract units for processing
|
224 |
+
units = self.extract_units_for_processing(syllabus_data)
|
225 |
+
total_units = len(units)
|
226 |
+
|
227 |
+
logger.info(f"Processing {total_units} units with {max_workers} workers")
|
228 |
+
|
229 |
+
# Process units concurrently
|
230 |
+
processed_units = {}
|
231 |
+
completed_count = 0
|
232 |
+
|
233 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
234 |
+
# Submit all tasks
|
235 |
+
future_to_unit = {executor.submit(self.format_single_unit, unit): unit for unit in units}
|
236 |
|
237 |
+
# Process completed tasks
|
238 |
+
for future in as_completed(future_to_unit):
|
239 |
+
try:
|
240 |
+
branch, semester, subject, unit_name, formatted_content = future.result()
|
241 |
+
|
242 |
+
# Store the result
|
243 |
+
key = f"{branch}|{semester}|{subject}|{unit_name}"
|
244 |
+
processed_units[key] = formatted_content
|
245 |
+
|
246 |
+
completed_count += 1
|
247 |
+
progress = (completed_count / total_units) * 100
|
248 |
+
|
249 |
+
if progress_callback:
|
250 |
+
progress_callback(progress, f"Processed {subject} - {unit_name}")
|
251 |
+
|
252 |
+
logger.info(f"Completed {completed_count}/{total_units} ({progress:.1f}%)")
|
253 |
+
|
254 |
+
except Exception as e:
|
255 |
+
logger.error(f"Error processing unit: {str(e)}")
|
256 |
+
|
257 |
+
# Update the syllabus data with formatted content
|
258 |
+
for branch_name, branch_data in syllabus_data.get("syllabus", {}).items():
|
259 |
+
if not isinstance(branch_data, dict):
|
260 |
+
continue
|
261 |
|
262 |
+
for sem_name, sem_data in branch_data.items():
|
263 |
+
if not isinstance(sem_data, dict):
|
264 |
+
continue
|
265 |
+
|
266 |
+
for subject_name, subject_data in sem_data.items():
|
267 |
+
if not isinstance(subject_data, dict) or "content" not in subject_data:
|
268 |
+
continue
|
269 |
+
|
270 |
+
content = subject_data["content"]
|
271 |
+
if not isinstance(content, dict):
|
272 |
+
continue
|
273 |
+
|
274 |
+
for unit_name in content.keys():
|
275 |
+
if unit_name.startswith("Unit"):
|
276 |
+
key = f"{branch_name}|{sem_name}|{subject_name}|{unit_name}"
|
277 |
+
if key in processed_units:
|
278 |
+
syllabus_data["syllabus"][branch_name][sem_name][subject_name]["content"][unit_name] = processed_units[key]
|
279 |
+
|
280 |
+
# Add metadata
|
281 |
+
if "metadata" not in syllabus_data:
|
282 |
+
syllabus_data["metadata"] = {}
|
283 |
+
|
284 |
+
syllabus_data["metadata"]["lastFormatted"] = datetime.now().isoformat()
|
285 |
+
syllabus_data["metadata"]["formattingNote"] = "Content formatted using Phi-3 AI for enhanced readability"
|
286 |
+
syllabus_data["metadata"]["originalContentPreserved"] = True
|
287 |
+
syllabus_data["metadata"]["unitsProcessed"] = completed_count
|
288 |
+
syllabus_data["metadata"]["formattingModel"] = self.model_name
|
289 |
+
syllabus_data["metadata"]["version"] = "2.0"
|
290 |
+
syllabus_data["metadata"]["processedConcurrently"] = True
|
291 |
+
syllabus_data["metadata"]["maxWorkers"] = max_workers
|
292 |
+
|
293 |
+
return syllabus_data
|
294 |
|
295 |
+
# Global formatter instance
|
296 |
+
formatter = SyllabusFormatter()
|
|
|
|
|
|
|
|
|
297 |
|
298 |
+
def format_syllabus_file(file_path, max_workers=4, progress=gr.Progress()):
|
299 |
+
"""Main function to format syllabus file"""
|
300 |
try:
|
301 |
+
# Load JSON file
|
302 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
303 |
+
syllabus_data = json.load(f)
|
304 |
+
|
305 |
+
# Count units
|
306 |
+
units = formatter.extract_units_for_processing(syllabus_data)
|
307 |
+
total_units = len(units)
|
308 |
|
309 |
+
progress(0, f"Found {total_units} units to process")
|
|
|
|
|
310 |
|
311 |
+
# Progress callback
|
312 |
+
def update_progress(percent, message):
|
313 |
+
progress(percent/100, message)
|
314 |
+
|
315 |
+
# Format the syllabus
|
316 |
+
formatted_data = formatter.format_syllabus_concurrent(
|
317 |
+
syllabus_data,
|
318 |
+
progress_callback=update_progress,
|
319 |
+
max_workers=max_workers
|
320 |
+
)
|
321 |
|
322 |
# Save to temporary file
|
323 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as f:
|
324 |
+
json.dump(formatted_data, f, indent=2, ensure_ascii=False)
|
325 |
+
temp_path = f.name
|
326 |
+
|
327 |
+
progress(1.0, f"Completed! Processed {total_units} units")
|
328 |
+
|
329 |
+
return temp_path, f"β
Successfully formatted {total_units} units!"
|
330 |
+
|
331 |
except Exception as e:
|
332 |
+
error_msg = f"β Error: {str(e)}"
|
333 |
+
logger.error(error_msg)
|
334 |
+
return None, error_msg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
335 |
|
336 |
+
def create_sample_json():
|
337 |
+
"""Create a sample JSON file for testing"""
|
338 |
+
sample_data = {
|
339 |
+
"metadata": {
|
340 |
+
"totalFiles": 1,
|
341 |
+
"generatedAt": datetime.now().isoformat(),
|
342 |
+
"source": "Sample syllabus for testing",
|
343 |
+
"description": "Sample syllabus content"
|
344 |
+
},
|
345 |
+
"syllabus": {
|
346 |
+
"CSE": {
|
347 |
+
"SEM1": {
|
348 |
+
"Mathematics": {
|
349 |
+
"extractedFrom": {
|
350 |
+
"path": "CSE > SEM1 > Mathematics",
|
351 |
+
"branch": "CSE",
|
352 |
+
"semester": "SEM1",
|
353 |
+
"subject": "Mathematics"
|
354 |
+
},
|
355 |
+
"content": {
|
356 |
+
"Unit I": "Differential Calculus: Limits, continuity, derivatives, applications of derivatives, maxima and minima, curve sketching, related rates, optimization problems, L'Hospital's rule, Taylor series, Partial derivatives, total differential, chain rule, implicit differentiation, Jacobians.",
|
357 |
+
"Unit II": "Integral Calculus: Integration techniques, definite integrals, applications of integrals, area under curves, volume of solids, arc length, surface area, Multiple integrals, double integrals, triple integrals, change of variables, applications in geometry and physics."
|
358 |
+
}
|
359 |
+
}
|
360 |
+
}
|
361 |
+
}
|
362 |
+
}
|
363 |
+
}
|
364 |
|
365 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as f:
|
366 |
+
json.dump(sample_data, f, indent=2, ensure_ascii=False)
|
367 |
+
return f.name
|
368 |
+
|
369 |
+
# Gradio Interface
|
370 |
+
def create_interface():
|
371 |
+
with gr.Blocks(
|
372 |
+
title="Syllabus Formatter - AI-Powered JSON Syllabus Formatter",
|
373 |
+
theme=gr.themes.Soft(
|
374 |
+
primary_hue="blue",
|
375 |
+
secondary_hue="purple",
|
376 |
+
neutral_hue="gray"
|
377 |
+
)
|
378 |
+
) as interface:
|
379 |
+
|
380 |
+
gr.HTML("""
|
381 |
+
<div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; margin-bottom: 20px;">
|
382 |
+
<h1 style="font-size: 2.5em; margin-bottom: 10px;">π Syllabus Formatter</h1>
|
383 |
+
<p style="font-size: 1.2em; opacity: 0.9;">AI-Powered JSON Syllabus Content Formatter using Phi-3</p>
|
384 |
+
<p style="font-size: 1em; opacity: 0.8;">Upload your JSON syllabus file and get beautifully formatted content with concurrent processing for speed!</p>
|
385 |
+
</div>
|
386 |
+
""")
|
387 |
+
|
388 |
+
with gr.Row():
|
389 |
+
with gr.Column(scale=1):
|
390 |
+
gr.HTML("""
|
391 |
+
<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
|
392 |
+
<h3>π Instructions:</h3>
|
393 |
+
<ol>
|
394 |
+
<li>Upload your JSON syllabus file</li>
|
395 |
+
<li>Choose number of concurrent workers (1-8)</li>
|
396 |
+
<li>Click "Format Syllabus" to start processing</li>
|
397 |
+
<li>Download the formatted JSON file</li>
|
398 |
+
</ol>
|
399 |
+
<p><strong>Note:</strong> Only syllabus content will be formatted, metadata remains unchanged.</p>
|
400 |
+
</div>
|
401 |
+
""")
|
402 |
+
|
403 |
+
file_input = gr.File(
|
404 |
+
label="π Upload JSON Syllabus File",
|
405 |
+
file_types=[".json"],
|
406 |
+
type="filepath"
|
407 |
+
)
|
408 |
+
|
409 |
+
workers_slider = gr.Slider(
|
410 |
+
minimum=1,
|
411 |
+
maximum=8,
|
412 |
+
value=4,
|
413 |
+
step=1,
|
414 |
+
label="π Concurrent Workers",
|
415 |
+
info="More workers = faster processing (but more memory usage)"
|
416 |
+
)
|
417 |
+
|
418 |
+
format_btn = gr.Button(
|
419 |
+
"π Format Syllabus",
|
420 |
+
variant="primary",
|
421 |
+
size="lg"
|
422 |
+
)
|
423 |
+
|
424 |
+
sample_btn = gr.Button(
|
425 |
+
"π Download Sample JSON",
|
426 |
+
variant="secondary"
|
427 |
+
)
|
428 |
|
429 |
+
with gr.Column(scale=1):
|
430 |
+
status_output = gr.Textbox(
|
431 |
+
label="π Status",
|
432 |
+
lines=3,
|
433 |
+
interactive=False
|
434 |
+
)
|
435 |
+
|
436 |
+
download_output = gr.File(
|
437 |
+
label="π₯ Download Formatted JSON",
|
438 |
+
visible=False
|
439 |
+
)
|
440 |
+
|
441 |
+
gr.HTML("""
|
442 |
+
<div style="background: #e3f2fd; padding: 15px; border-radius: 8px; margin-top: 15px;">
|
443 |
+
<h3>β¨ Features:</h3>
|
444 |
+
<ul>
|
445 |
+
<li>π€ Powered by Microsoft Phi-3 AI model</li>
|
446 |
+
<li>β‘ Concurrent processing for speed</li>
|
447 |
+
<li>π Preserves all original content</li>
|
448 |
+
<li>π Real-time progress tracking</li>
|
449 |
+
<li>π― Formats only syllabus content, not metadata</li>
|
450 |
+
<li>β
Validation to ensure content integrity</li>
|
451 |
+
</ul>
|
452 |
+
</div>
|
453 |
+
""")
|
454 |
+
|
455 |
+
# Event handlers
|
456 |
+
def format_handler(file_path, max_workers):
|
457 |
+
if file_path is None:
|
458 |
+
return "β Please upload a JSON file first.", gr.update(visible=False)
|
459 |
+
|
460 |
+
try:
|
461 |
+
result_path, message = format_syllabus_file(file_path, int(max_workers))
|
462 |
+
if result_path:
|
463 |
+
return message, gr.update(visible=True, value=result_path)
|
464 |
+
else:
|
465 |
+
return message, gr.update(visible=False)
|
466 |
+
except Exception as e:
|
467 |
+
return f"β Error: {str(e)}", gr.update(visible=False)
|
468 |
+
|
469 |
+
def sample_handler():
|
470 |
+
sample_path = create_sample_json()
|
471 |
+
return gr.update(visible=True, value=sample_path)
|
472 |
+
|
473 |
+
format_btn.click(
|
474 |
+
format_handler,
|
475 |
+
inputs=[file_input, workers_slider],
|
476 |
+
outputs=[status_output, download_output]
|
477 |
)
|
478 |
+
|
479 |
+
sample_btn.click(
|
480 |
+
sample_handler,
|
481 |
+
outputs=[gr.File(label="π₯ Sample JSON File", visible=True)]
|
482 |
+
)
|
483 |
+
|
484 |
+
gr.HTML("""
|
485 |
+
<div style="text-align: center; padding: 15px; margin-top: 20px; border-top: 1px solid #ddd;">
|
486 |
+
<p style="color: #666;">
|
487 |
+
Built with β€οΈ using Hugging Face Spaces |
|
488 |
+
Powered by Microsoft Phi-3 |
|
489 |
+
Optimized for concurrent processing
|
490 |
+
</p>
|
491 |
+
</div>
|
492 |
+
""")
|
493 |
|
494 |
+
return interface
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
495 |
|
496 |
+
# Launch the app
|
497 |
if __name__ == "__main__":
|
498 |
+
interface = create_interface()
|
499 |
+
interface.launch(
|
500 |
+
server_name="0.0.0.0",
|
501 |
+
server_port=7860,
|
502 |
+
share=True
|
503 |
+
)
|
gradio_app.py
CHANGED
@@ -1,466 +1,503 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
|
3 |
-
import
|
4 |
-
import
|
5 |
-
import
|
6 |
-
import
|
7 |
-
import
|
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 |
-
content:
|
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 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
#
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
466 |
)
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import json
|
3 |
+
import time
|
4 |
+
import logging
|
5 |
+
import re
|
6 |
+
from typing import Dict, Any, List, Tuple
|
7 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
8 |
+
import threading
|
9 |
+
from datetime import datetime
|
10 |
+
import os
|
11 |
+
import tempfile
|
12 |
+
|
13 |
+
# Hugging Face Transformers
|
14 |
+
import torch
|
15 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
16 |
+
import gc
|
17 |
+
|
18 |
+
# Setup logging
|
19 |
+
logging.basicConfig(
|
20 |
+
level=logging.INFO,
|
21 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
22 |
+
)
|
23 |
+
logger = logging.getLogger(__name__)
|
24 |
+
|
25 |
+
class SyllabusFormatter:
|
26 |
+
def __init__(self, model_name="microsoft/Phi-3-mini-4k-instruct"):
|
27 |
+
"""Initialize the formatter with Phi-3 model"""
|
28 |
+
self.model_name = model_name
|
29 |
+
self.tokenizer = None
|
30 |
+
self.model = None
|
31 |
+
self.pipe = None
|
32 |
+
self.is_model_loaded = False
|
33 |
+
self.processing_lock = threading.Lock()
|
34 |
+
|
35 |
+
def load_model(self):
|
36 |
+
"""Load the Phi-3 model with optimizations"""
|
37 |
+
if self.is_model_loaded:
|
38 |
+
return True
|
39 |
+
|
40 |
+
try:
|
41 |
+
logger.info(f"Loading model: {self.model_name}")
|
42 |
+
|
43 |
+
# Load tokenizer
|
44 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
45 |
+
self.model_name,
|
46 |
+
trust_remote_code=True
|
47 |
+
)
|
48 |
+
|
49 |
+
# Load model with optimizations
|
50 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
51 |
+
self.model_name,
|
52 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
53 |
+
device_map="auto" if torch.cuda.is_available() else None,
|
54 |
+
trust_remote_code=True,
|
55 |
+
low_cpu_mem_usage=True
|
56 |
+
)
|
57 |
+
|
58 |
+
# Create pipeline
|
59 |
+
self.pipe = pipeline(
|
60 |
+
"text-generation",
|
61 |
+
model=self.model,
|
62 |
+
tokenizer=self.tokenizer,
|
63 |
+
device=0 if torch.cuda.is_available() else -1,
|
64 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
|
65 |
+
)
|
66 |
+
|
67 |
+
self.is_model_loaded = True
|
68 |
+
logger.info("Model loaded successfully!")
|
69 |
+
return True
|
70 |
+
|
71 |
+
except Exception as e:
|
72 |
+
logger.error(f"Error loading model: {str(e)}")
|
73 |
+
return False
|
74 |
+
|
75 |
+
def create_formatting_prompt(self, unit_content: str, unit_name: str, subject_name: str = "") -> str:
|
76 |
+
"""Create a focused prompt for formatting syllabus content"""
|
77 |
+
prompt = f"""<|system|>You are a professional academic syllabus formatter. Your job is to take poorly formatted syllabus content and make it beautifully organized and readable.
|
78 |
+
|
79 |
+
RULES:
|
80 |
+
1. PRESERVE every single word, topic, and concept from the original
|
81 |
+
2. NEVER add explanations, examples, or new content
|
82 |
+
3. ONLY restructure and format the existing text
|
83 |
+
4. Use clear headings, bullet points, and logical grouping
|
84 |
+
5. Separate different topics with proper spacing
|
85 |
+
6. Make it scannable and easy to read
|
86 |
+
|
87 |
+
FORMAT STYLE:
|
88 |
+
- Use main topic headings with proper capitalization
|
89 |
+
- Group related subtopics under main topics
|
90 |
+
- Use bullet points (β’) for lists of concepts
|
91 |
+
- Use sub-bullets (β¦) for details under main bullets
|
92 |
+
- Separate major sections with line breaks
|
93 |
+
- Keep technical terms exactly as written<|end|>
|
94 |
+
|
95 |
+
<|user|>Subject: {subject_name}
|
96 |
+
Unit: {unit_name}
|
97 |
+
|
98 |
+
Original content (poorly formatted):
|
99 |
+
{unit_content}
|
100 |
+
|
101 |
+
Task: Reformat this content to be beautifully organized and readable. Do NOT add any new information - only restructure what's already there.<|end|>
|
102 |
+
|
103 |
+
<|assistant|>"""
|
104 |
+
return prompt
|
105 |
+
|
106 |
+
def format_single_unit(self, unit_data: Tuple[str, str, str, str, str]) -> Tuple[str, str, str, str, str]:
|
107 |
+
"""Format a single unit's content"""
|
108 |
+
branch, semester, subject, unit_name, unit_content = unit_data
|
109 |
+
|
110 |
+
try:
|
111 |
+
with self.processing_lock:
|
112 |
+
# Create prompt
|
113 |
+
prompt = self.create_formatting_prompt(unit_content, unit_name, subject)
|
114 |
+
|
115 |
+
# Generate formatted content
|
116 |
+
response = self.pipe(
|
117 |
+
prompt,
|
118 |
+
max_new_tokens=2048,
|
119 |
+
temperature=0.1,
|
120 |
+
do_sample=True,
|
121 |
+
top_p=0.9,
|
122 |
+
repetition_penalty=1.1,
|
123 |
+
pad_token_id=self.tokenizer.eos_token_id,
|
124 |
+
eos_token_id=self.tokenizer.eos_token_id
|
125 |
+
)
|
126 |
+
|
127 |
+
# Extract formatted content
|
128 |
+
generated_text = response[0]['generated_text']
|
129 |
+
assistant_start = generated_text.find("<|assistant|>")
|
130 |
+
|
131 |
+
if assistant_start != -1:
|
132 |
+
formatted_content = generated_text[assistant_start + len("<|assistant|>"):].strip()
|
133 |
+
else:
|
134 |
+
formatted_content = generated_text[len(prompt):].strip()
|
135 |
+
|
136 |
+
# Clean up the content
|
137 |
+
formatted_content = self.clean_generated_content(formatted_content)
|
138 |
+
|
139 |
+
# Validate content
|
140 |
+
if self.validate_formatted_content(unit_content, formatted_content):
|
141 |
+
return (branch, semester, subject, unit_name, formatted_content)
|
142 |
+
else:
|
143 |
+
logger.warning(f"Validation failed for {subject} - {unit_name}")
|
144 |
+
return (branch, semester, subject, unit_name, unit_content)
|
145 |
+
|
146 |
+
except Exception as e:
|
147 |
+
logger.error(f"Error formatting {subject} - {unit_name}: {str(e)}")
|
148 |
+
return (branch, semester, subject, unit_name, unit_content)
|
149 |
+
|
150 |
+
def clean_generated_content(self, content: str) -> str:
|
151 |
+
"""Clean up generated content"""
|
152 |
+
# Remove special tokens
|
153 |
+
content = re.sub(r'<\|.*?\|>', '', content)
|
154 |
+
|
155 |
+
# Remove AI commentary
|
156 |
+
lines = content.split('\n')
|
157 |
+
cleaned_lines = []
|
158 |
+
|
159 |
+
for line in lines:
|
160 |
+
line = line.strip()
|
161 |
+
if (line.startswith("Here") and ("formatted" in line.lower() or "organized" in line.lower())) or \
|
162 |
+
line.startswith("I have") or line.startswith("The content has been") or \
|
163 |
+
line.startswith("Note:") or line.startswith("This formatted version"):
|
164 |
+
continue
|
165 |
+
if line:
|
166 |
+
cleaned_lines.append(line)
|
167 |
+
|
168 |
+
content = '\n'.join(cleaned_lines)
|
169 |
+
|
170 |
+
# Fix spacing
|
171 |
+
content = re.sub(r'\n\s*\n\s*\n+', '\n\n', content)
|
172 |
+
content = re.sub(r'\n([A-Z][^:\n]*:)\n', r'\n\n\1\n', content)
|
173 |
+
|
174 |
+
return content.strip()
|
175 |
+
|
176 |
+
def validate_formatted_content(self, original: str, formatted: str) -> bool:
|
177 |
+
"""Validate that formatted content preserves important information"""
|
178 |
+
if len(formatted) < len(original) * 0.4:
|
179 |
+
return False
|
180 |
+
|
181 |
+
# Check for preservation of key terms
|
182 |
+
original_words = set(re.findall(r'\b[A-Z][a-z]*(?:[A-Z][a-z]*)*\b', original))
|
183 |
+
formatted_words = set(re.findall(r'\b[A-Z][a-z]*(?:[A-Z][a-z]*)*\b', formatted))
|
184 |
+
|
185 |
+
missing_terms = original_words - formatted_words
|
186 |
+
if len(missing_terms) > len(original_words) * 0.3:
|
187 |
+
return False
|
188 |
+
|
189 |
+
return True
|
190 |
+
|
191 |
+
def extract_units_for_processing(self, syllabus_data: Dict[str, Any]) -> List[Tuple[str, str, str, str, str]]:
|
192 |
+
"""Extract all units for concurrent processing"""
|
193 |
+
units = []
|
194 |
+
|
195 |
+
for branch_name, branch_data in syllabus_data.get("syllabus", {}).items():
|
196 |
+
if not isinstance(branch_data, dict):
|
197 |
+
continue
|
198 |
+
|
199 |
+
for sem_name, sem_data in branch_data.items():
|
200 |
+
if not isinstance(sem_data, dict):
|
201 |
+
continue
|
202 |
+
|
203 |
+
for subject_name, subject_data in sem_data.items():
|
204 |
+
if not isinstance(subject_data, dict) or "content" not in subject_data:
|
205 |
+
continue
|
206 |
+
|
207 |
+
content = subject_data["content"]
|
208 |
+
if not isinstance(content, dict):
|
209 |
+
continue
|
210 |
+
|
211 |
+
for unit_name, unit_content in content.items():
|
212 |
+
if unit_name.startswith("Unit") and isinstance(unit_content, str):
|
213 |
+
units.append((branch_name, sem_name, subject_name, unit_name, unit_content))
|
214 |
+
|
215 |
+
return units
|
216 |
+
|
217 |
+
def format_syllabus_concurrent(self, syllabus_data: Dict[str, Any], progress_callback=None, max_workers=4) -> Dict[str, Any]:
|
218 |
+
"""Format syllabus using concurrent processing"""
|
219 |
+
if not self.is_model_loaded:
|
220 |
+
if not self.load_model():
|
221 |
+
raise Exception("Failed to load model")
|
222 |
+
|
223 |
+
# Extract units for processing
|
224 |
+
units = self.extract_units_for_processing(syllabus_data)
|
225 |
+
total_units = len(units)
|
226 |
+
|
227 |
+
logger.info(f"Processing {total_units} units with {max_workers} workers")
|
228 |
+
|
229 |
+
# Process units concurrently
|
230 |
+
processed_units = {}
|
231 |
+
completed_count = 0
|
232 |
+
|
233 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
234 |
+
# Submit all tasks
|
235 |
+
future_to_unit = {executor.submit(self.format_single_unit, unit): unit for unit in units}
|
236 |
+
|
237 |
+
# Process completed tasks
|
238 |
+
for future in as_completed(future_to_unit):
|
239 |
+
try:
|
240 |
+
branch, semester, subject, unit_name, formatted_content = future.result()
|
241 |
+
|
242 |
+
# Store the result
|
243 |
+
key = f"{branch}|{semester}|{subject}|{unit_name}"
|
244 |
+
processed_units[key] = formatted_content
|
245 |
+
|
246 |
+
completed_count += 1
|
247 |
+
progress = (completed_count / total_units) * 100
|
248 |
+
|
249 |
+
if progress_callback:
|
250 |
+
progress_callback(progress, f"Processed {subject} - {unit_name}")
|
251 |
+
|
252 |
+
logger.info(f"Completed {completed_count}/{total_units} ({progress:.1f}%)")
|
253 |
+
|
254 |
+
except Exception as e:
|
255 |
+
logger.error(f"Error processing unit: {str(e)}")
|
256 |
+
|
257 |
+
# Update the syllabus data with formatted content
|
258 |
+
for branch_name, branch_data in syllabus_data.get("syllabus", {}).items():
|
259 |
+
if not isinstance(branch_data, dict):
|
260 |
+
continue
|
261 |
+
|
262 |
+
for sem_name, sem_data in branch_data.items():
|
263 |
+
if not isinstance(sem_data, dict):
|
264 |
+
continue
|
265 |
+
|
266 |
+
for subject_name, subject_data in sem_data.items():
|
267 |
+
if not isinstance(subject_data, dict) or "content" not in subject_data:
|
268 |
+
continue
|
269 |
+
|
270 |
+
content = subject_data["content"]
|
271 |
+
if not isinstance(content, dict):
|
272 |
+
continue
|
273 |
+
|
274 |
+
for unit_name in content.keys():
|
275 |
+
if unit_name.startswith("Unit"):
|
276 |
+
key = f"{branch_name}|{sem_name}|{subject_name}|{unit_name}"
|
277 |
+
if key in processed_units:
|
278 |
+
syllabus_data["syllabus"][branch_name][sem_name][subject_name]["content"][unit_name] = processed_units[key]
|
279 |
+
|
280 |
+
# Add metadata
|
281 |
+
if "metadata" not in syllabus_data:
|
282 |
+
syllabus_data["metadata"] = {}
|
283 |
+
|
284 |
+
syllabus_data["metadata"]["lastFormatted"] = datetime.now().isoformat()
|
285 |
+
syllabus_data["metadata"]["formattingNote"] = "Content formatted using Phi-3 AI for enhanced readability"
|
286 |
+
syllabus_data["metadata"]["originalContentPreserved"] = True
|
287 |
+
syllabus_data["metadata"]["unitsProcessed"] = completed_count
|
288 |
+
syllabus_data["metadata"]["formattingModel"] = self.model_name
|
289 |
+
syllabus_data["metadata"]["version"] = "2.0"
|
290 |
+
syllabus_data["metadata"]["processedConcurrently"] = True
|
291 |
+
syllabus_data["metadata"]["maxWorkers"] = max_workers
|
292 |
+
|
293 |
+
return syllabus_data
|
294 |
+
|
295 |
+
# Global formatter instance
|
296 |
+
formatter = SyllabusFormatter()
|
297 |
+
|
298 |
+
def format_syllabus_file(file_path, max_workers=4, progress=gr.Progress()):
|
299 |
+
"""Main function to format syllabus file"""
|
300 |
+
try:
|
301 |
+
# Load JSON file
|
302 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
303 |
+
syllabus_data = json.load(f)
|
304 |
+
|
305 |
+
# Count units
|
306 |
+
units = formatter.extract_units_for_processing(syllabus_data)
|
307 |
+
total_units = len(units)
|
308 |
+
|
309 |
+
progress(0, f"Found {total_units} units to process")
|
310 |
+
|
311 |
+
# Progress callback
|
312 |
+
def update_progress(percent, message):
|
313 |
+
progress(percent/100, message)
|
314 |
+
|
315 |
+
# Format the syllabus
|
316 |
+
formatted_data = formatter.format_syllabus_concurrent(
|
317 |
+
syllabus_data,
|
318 |
+
progress_callback=update_progress,
|
319 |
+
max_workers=max_workers
|
320 |
+
)
|
321 |
+
|
322 |
+
# Save to temporary file
|
323 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as f:
|
324 |
+
json.dump(formatted_data, f, indent=2, ensure_ascii=False)
|
325 |
+
temp_path = f.name
|
326 |
+
|
327 |
+
progress(1.0, f"Completed! Processed {total_units} units")
|
328 |
+
|
329 |
+
return temp_path, f"β
Successfully formatted {total_units} units!"
|
330 |
+
|
331 |
+
except Exception as e:
|
332 |
+
error_msg = f"β Error: {str(e)}"
|
333 |
+
logger.error(error_msg)
|
334 |
+
return None, error_msg
|
335 |
+
|
336 |
+
def create_sample_json():
|
337 |
+
"""Create a sample JSON file for testing"""
|
338 |
+
sample_data = {
|
339 |
+
"metadata": {
|
340 |
+
"totalFiles": 1,
|
341 |
+
"generatedAt": datetime.now().isoformat(),
|
342 |
+
"source": "Sample syllabus for testing",
|
343 |
+
"description": "Sample syllabus content"
|
344 |
+
},
|
345 |
+
"syllabus": {
|
346 |
+
"CSE": {
|
347 |
+
"SEM1": {
|
348 |
+
"Mathematics": {
|
349 |
+
"extractedFrom": {
|
350 |
+
"path": "CSE > SEM1 > Mathematics",
|
351 |
+
"branch": "CSE",
|
352 |
+
"semester": "SEM1",
|
353 |
+
"subject": "Mathematics"
|
354 |
+
},
|
355 |
+
"content": {
|
356 |
+
"Unit I": "Differential Calculus: Limits, continuity, derivatives, applications of derivatives, maxima and minima, curve sketching, related rates, optimization problems, L'Hospital's rule, Taylor series, Partial derivatives, total differential, chain rule, implicit differentiation, Jacobians.",
|
357 |
+
"Unit II": "Integral Calculus: Integration techniques, definite integrals, applications of integrals, area under curves, volume of solids, arc length, surface area, Multiple integrals, double integrals, triple integrals, change of variables, applications in geometry and physics."
|
358 |
+
}
|
359 |
+
}
|
360 |
+
}
|
361 |
+
}
|
362 |
+
}
|
363 |
+
}
|
364 |
+
|
365 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as f:
|
366 |
+
json.dump(sample_data, f, indent=2, ensure_ascii=False)
|
367 |
+
return f.name
|
368 |
+
|
369 |
+
# Gradio Interface
|
370 |
+
def create_interface():
|
371 |
+
with gr.Blocks(
|
372 |
+
title="Syllabus Formatter - AI-Powered JSON Syllabus Formatter",
|
373 |
+
theme=gr.themes.Soft(
|
374 |
+
primary_hue="blue",
|
375 |
+
secondary_hue="purple",
|
376 |
+
neutral_hue="gray"
|
377 |
+
)
|
378 |
+
) as interface:
|
379 |
+
|
380 |
+
gr.HTML("""
|
381 |
+
<div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; margin-bottom: 20px;">
|
382 |
+
<h1 style="font-size: 2.5em; margin-bottom: 10px;">π Syllabus Formatter</h1>
|
383 |
+
<p style="font-size: 1.2em; opacity: 0.9;">AI-Powered JSON Syllabus Content Formatter using Phi-3</p>
|
384 |
+
<p style="font-size: 1em; opacity: 0.8;">Upload your JSON syllabus file and get beautifully formatted content with concurrent processing for speed!</p>
|
385 |
+
</div>
|
386 |
+
""")
|
387 |
+
|
388 |
+
with gr.Row():
|
389 |
+
with gr.Column(scale=1):
|
390 |
+
gr.HTML("""
|
391 |
+
<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
|
392 |
+
<h3>π Instructions:</h3>
|
393 |
+
<ol>
|
394 |
+
<li>Upload your JSON syllabus file</li>
|
395 |
+
<li>Choose number of concurrent workers (1-8)</li>
|
396 |
+
<li>Click "Format Syllabus" to start processing</li>
|
397 |
+
<li>Download the formatted JSON file</li>
|
398 |
+
</ol>
|
399 |
+
<p><strong>Note:</strong> Only syllabus content will be formatted, metadata remains unchanged.</p>
|
400 |
+
</div>
|
401 |
+
""")
|
402 |
+
|
403 |
+
file_input = gr.File(
|
404 |
+
label="π Upload JSON Syllabus File",
|
405 |
+
file_types=[".json"],
|
406 |
+
type="filepath"
|
407 |
+
)
|
408 |
+
|
409 |
+
workers_slider = gr.Slider(
|
410 |
+
minimum=1,
|
411 |
+
maximum=8,
|
412 |
+
value=4,
|
413 |
+
step=1,
|
414 |
+
label="π Concurrent Workers",
|
415 |
+
info="More workers = faster processing (but more memory usage)"
|
416 |
+
)
|
417 |
+
|
418 |
+
format_btn = gr.Button(
|
419 |
+
"π Format Syllabus",
|
420 |
+
variant="primary",
|
421 |
+
size="lg"
|
422 |
+
)
|
423 |
+
|
424 |
+
sample_btn = gr.Button(
|
425 |
+
"π Download Sample JSON",
|
426 |
+
variant="secondary"
|
427 |
+
)
|
428 |
+
|
429 |
+
with gr.Column(scale=1):
|
430 |
+
status_output = gr.Textbox(
|
431 |
+
label="π Status",
|
432 |
+
lines=3,
|
433 |
+
interactive=False
|
434 |
+
)
|
435 |
+
|
436 |
+
download_output = gr.File(
|
437 |
+
label="π₯ Download Formatted JSON",
|
438 |
+
visible=False
|
439 |
+
)
|
440 |
+
|
441 |
+
gr.HTML("""
|
442 |
+
<div style="background: #e3f2fd; padding: 15px; border-radius: 8px; margin-top: 15px;">
|
443 |
+
<h3>β¨ Features:</h3>
|
444 |
+
<ul>
|
445 |
+
<li>π€ Powered by Microsoft Phi-3 AI model</li>
|
446 |
+
<li>β‘ Concurrent processing for speed</li>
|
447 |
+
<li>π Preserves all original content</li>
|
448 |
+
<li>π Real-time progress tracking</li>
|
449 |
+
<li>π― Formats only syllabus content, not metadata</li>
|
450 |
+
<li>β
Validation to ensure content integrity</li>
|
451 |
+
</ul>
|
452 |
+
</div>
|
453 |
+
""")
|
454 |
+
|
455 |
+
# Event handlers
|
456 |
+
def format_handler(file_path, max_workers):
|
457 |
+
if file_path is None:
|
458 |
+
return "β Please upload a JSON file first.", gr.update(visible=False)
|
459 |
+
|
460 |
+
try:
|
461 |
+
result_path, message = format_syllabus_file(file_path, int(max_workers))
|
462 |
+
if result_path:
|
463 |
+
return message, gr.update(visible=True, value=result_path)
|
464 |
+
else:
|
465 |
+
return message, gr.update(visible=False)
|
466 |
+
except Exception as e:
|
467 |
+
return f"β Error: {str(e)}", gr.update(visible=False)
|
468 |
+
|
469 |
+
def sample_handler():
|
470 |
+
sample_path = create_sample_json()
|
471 |
+
return gr.update(visible=True, value=sample_path)
|
472 |
+
|
473 |
+
format_btn.click(
|
474 |
+
format_handler,
|
475 |
+
inputs=[file_input, workers_slider],
|
476 |
+
outputs=[status_output, download_output]
|
477 |
+
)
|
478 |
+
|
479 |
+
sample_btn.click(
|
480 |
+
sample_handler,
|
481 |
+
outputs=[gr.File(label="π₯ Sample JSON File", visible=True)]
|
482 |
+
)
|
483 |
+
|
484 |
+
gr.HTML("""
|
485 |
+
<div style="text-align: center; padding: 15px; margin-top: 20px; border-top: 1px solid #ddd;">
|
486 |
+
<p style="color: #666;">
|
487 |
+
Built with β€οΈ using Hugging Face Spaces |
|
488 |
+
Powered by Microsoft Phi-3 |
|
489 |
+
Optimized for concurrent processing
|
490 |
+
</p>
|
491 |
+
</div>
|
492 |
+
""")
|
493 |
+
|
494 |
+
return interface
|
495 |
+
|
496 |
+
# Launch the app
|
497 |
+
if __name__ == "__main__":
|
498 |
+
interface = create_interface()
|
499 |
+
interface.launch(
|
500 |
+
server_name="0.0.0.0",
|
501 |
+
server_port=7860,
|
502 |
+
share=True
|
503 |
)
|