rickey67 commited on
Commit
8090962
·
verified ·
1 Parent(s): f802dc9

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +599 -157
  2. requirements.txt +2 -1
app.py CHANGED
@@ -1,7 +1,14 @@
1
  import spaces # MUST BE THE VERY FIRST IMPORT FOR ZEROGPU
2
  import os
3
  import io
 
 
 
 
4
  import threading
 
 
 
5
  from pathlib import Path
6
 
7
  import requests
@@ -17,6 +24,8 @@ from transformers import (
17
  AutoModelForCausalLM,
18
  AutoTokenizer,
19
  BitsAndBytesConfig,
 
 
20
  TextIteratorStreamer,
21
  )
22
  from peft import PeftModel
@@ -44,8 +53,10 @@ ASSETS = {
44
 
45
  ADAPTER_DIR = Path("adapters") / RELEASE_TAG
46
 
47
- MAX_FILE_CHARS = 16000
48
- MAX_HISTORY_CHARS = 24000
 
 
49
 
50
  # Your adapters were trained on Qwen3-8B, so the base model MUST be Qwen3-8B.
51
  BASE_MODEL = os.environ.get("BASE_MODEL") or "Qwen/Qwen3-8B"
@@ -58,6 +69,18 @@ MODES = {
58
  "Math": {"adapter": "math_adapter"},
59
  }
60
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  # ----------------------------- MODEL LOADING -----------------------------
62
 
63
 
@@ -131,83 +154,187 @@ print("Model ready.")
131
 
132
  # ----------------------------- FILE PARSING -----------------------------
133
 
134
- TEXT_EXTENSIONS = {
135
- ".txt", ".md", ".markdown", ".py", ".js", ".ts", ".jsx", ".tsx", ".java",
136
- ".c", ".cpp", ".h", ".hpp", ".cs", ".go", ".rs", ".rb", ".php", ".sh",
137
- ".sql", ".json", ".yaml", ".yml", ".toml", ".ini", ".csv", ".tsv", ".tex",
138
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
 
141
  def file_path_of(file_obj) -> Path:
142
- """Gradio may give a str path or an object with .name, depending on version."""
143
- return Path(file_obj if isinstance(file_obj, str) else file_obj.name)
 
 
 
 
144
 
145
 
146
  def extract_text_from_upload(file_obj) -> str:
147
- if not file_obj:
148
- return ""
149
  path = file_path_of(file_obj)
150
  ext = path.suffix.lower()
151
- data = path.read_bytes()
152
-
153
- if ext in TEXT_EXTENSIONS:
154
- return data.decode("utf-8", errors="replace")
155
- if ext == ".pdf":
156
- try:
157
- from pypdf import PdfReader
158
- reader = PdfReader(io.BytesIO(data))
159
- pages = []
160
- for p in reader.pages:
161
- t = p.extract_text()
162
- if t:
163
- pages.append(t)
164
- return "\n".join(pages)
165
- except Exception:
166
- return "[PDF extraction error]"
167
- if ext == ".docx":
168
- try:
169
- from docx import Document
170
- doc = Document(io.BytesIO(data))
171
- return "\n".join(p.text for p in doc.paragraphs if p.text.strip())
172
- except Exception:
173
- return "[DOCX extraction error]"
174
- if ext == ".xlsx":
175
- try:
176
- from openpyxl import load_workbook
177
- wb = load_workbook(io.BytesIO(data), read_only=True, data_only=True)
178
- parts = []
179
- for sheet in wb.worksheets:
180
- for row in sheet.iter_rows(values_only=True):
181
- row_str = " | ".join(str(v) for v in row if v is not None)
182
- if row_str.strip():
183
- parts.append(row_str)
184
- return "\n".join(parts)
185
- except Exception:
186
- return "[XLSX extraction error]"
187
- if ext == ".pptx":
188
- try:
189
- from pptx import Presentation
190
- prs = Presentation(io.BytesIO(data))
191
- parts = []
192
- for slide in prs.slides:
193
- for shape in slide.shapes:
194
- if getattr(shape, "has_text_frame", False) and shape.text_frame.text.strip():
195
- parts.append(shape.text_frame.text)
196
- return "\n".join(parts)
197
- except Exception:
198
- return "[PPTX extraction error]"
199
- return "[Unsupported file format]"
200
-
201
-
202
- def build_file_context(files) -> str:
203
- if not files:
204
- return ""
205
- chunks = []
206
- for f in files:
207
- name = file_path_of(f).name
208
- text = extract_text_from_upload(f)[:MAX_FILE_CHARS]
209
- chunks.append(f"--- File: {name} ---\n{text}")
210
- return "\n\n".join(chunks)
211
 
212
 
213
  # ----------------------------- MATH CHECKER -----------------------------
@@ -248,36 +375,34 @@ def run_sympy(expression: str) -> str:
248
  return f"SymPy Error: {e}"
249
 
250
 
251
- # ----------------------------- GENERATION WORKER -----------------------------
252
 
253
 
254
- def trim_history(messages):
255
- """Drop the oldest turns until the history fits MAX_HISTORY_CHARS (keep the last user msg)."""
256
  def total(ms):
257
  return sum(len(m["content"]) for m in ms)
258
 
259
  while len(messages) > 1 and total(messages) > MAX_HISTORY_CHARS:
260
  messages.pop(0)
261
- # never start with an assistant message
262
- while messages and messages[0]["role"] == "assistant":
263
  messages.pop(0)
264
  return messages
265
 
266
 
267
- @spaces.GPU(duration=120)
268
- def generate_response(history, mode, file_context, temperature, max_new_tokens):
269
- adapter_name = MODES.get(mode, MODES["General"])["adapter"]
270
 
271
- messages = []
272
- for user_msg, assistant_msg in history:
273
- messages.append({"role": "user", "content": user_msg})
274
- if assistant_msg:
275
- messages.append({"role": "assistant", "content": assistant_msg})
276
 
277
- if messages and messages[-1]["role"] == "user" and file_context:
278
- messages[-1]["content"] += f"\n\nAttached files context:\n{file_context}"
279
 
280
- messages = trim_history(messages)
 
 
 
281
 
282
  prompt = tokenizer.apply_chat_template(
283
  messages,
@@ -285,9 +410,9 @@ def generate_response(history, mode, file_context, temperature, max_new_tokens):
285
  add_generation_prompt=True,
286
  enable_thinking=False,
287
  )
288
-
289
  inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
290
  streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
 
291
  errors = []
292
 
293
  temperature = float(temperature)
@@ -296,6 +421,7 @@ def generate_response(history, mode, file_context, temperature, max_new_tokens):
296
  repetition_penalty=1.05,
297
  pad_token_id=tokenizer.pad_token_id,
298
  eos_token_id=tokenizer.convert_tokens_to_ids("<|im_end|>"),
 
299
  )
300
  if temperature > 0.01:
301
  gen_kwargs.update(do_sample=True, temperature=temperature, top_p=0.8)
@@ -315,90 +441,406 @@ def generate_response(history, mode, file_context, temperature, max_new_tokens):
315
  t = threading.Thread(target=worker, daemon=True)
316
  t.start()
317
 
318
- partial_message = ""
319
- for new_text in streamer:
320
- partial_message += new_text
321
- yield partial_message
322
- t.join()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
323
 
324
- if errors:
325
- yield partial_message + f"\n\n⚠️ Generation error: {errors[0]}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
 
327
 
328
  # ----------------------------- GRADIO UI -----------------------------
329
 
330
- css = """
331
- .gradio-container { background-color: #0f172a !important; color: #f8fafc !important; font-family: 'Inter', sans-serif; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332
  """
333
 
334
- with gr.Blocks(css=css, theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="cyan")) as demo:
335
- gr.Markdown("# ✨ Tutor Studio (English · Math · General AI)")
336
- gr.Markdown("A multi-adapter workspace powered by Qwen3 & PEFT, running on Hugging Face ZeroGPU.")
337
-
338
- with gr.Row():
339
- with gr.Column(scale=3):
340
- chatbot = gr.Chatbot(height=500, label="Chat Workspace")
341
- with gr.Row():
342
- msg = gr.Textbox(
343
- placeholder="Ask anything or enter a prompt...",
344
- container=False,
345
- scale=4,
346
- )
347
- submit_btn = gr.Button("Send", variant="primary", scale=1)
348
- with gr.Row():
349
- clear_btn = gr.Button("Clear Conversation")
350
- stop_btn = gr.Button("Stop Generation", variant="stop")
351
-
352
- with gr.Column(scale=1):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
353
  mode_radio = gr.Radio(
354
- choices=list(MODES.keys()),
355
- value="General",
356
- label="Assistant Mode",
357
- interactive=True,
358
  )
359
- file_upload = gr.File(
360
- label="Attach Files (PDF, Word, Excel, PowerPoint, Code, etc.)",
 
 
 
361
  file_count="multiple",
 
 
 
362
  )
363
- with gr.Accordion("Generation Settings", open=False):
364
- temp_slider = gr.Slider(0.0, 1.0, value=0.35, step=0.05, label="Creativity (Temperature)")
365
- tokens_slider = gr.Slider(256, 4096, value=1600, step=128, label="Max Response Tokens")
 
 
 
 
 
 
366
 
367
- with gr.Accordion("🧮 SymPy Math Checker", open=False):
368
- sympy_input = gr.Textbox(label="Expression", value="diff(x**3 + 5*x, x)")
369
- sympy_output = gr.Textbox(label="Result", interactive=False)
370
- sympy_btn = gr.Button("Calculate", variant="secondary")
371
- sympy_btn.click(run_sympy, inputs=sympy_input, outputs=sympy_output)
 
 
372
 
373
- def user(user_message, history):
374
- history = history or []
375
- if not user_message or not user_message.strip():
376
- return "", history
377
- return "", history + [[user_message, None]]
378
-
379
- def bot(history, mode, files, temp, tokens):
380
- # Skip if there is no pending user message (e.g. empty submit)
381
- if not history or history[-1][1] is not None:
382
- yield history
383
- return
384
-
385
- file_context = build_file_context(files)
386
- # Pass the FULL history including the current user message
387
- prompt_history = [list(turn) for turn in history]
388
- history[-1][1] = ""
389
- for resp in generate_response(prompt_history, mode, file_context, temp, tokens):
390
- history[-1][1] = resp
391
- yield history
392
-
393
- submit_event = msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
394
- bot, [chatbot, mode_radio, file_upload, temp_slider, tokens_slider], chatbot
395
  )
396
- click_event = submit_btn.click(user, [msg, chatbot], [msg, chatbot], queue=False).then(
397
- bot, [chatbot, mode_radio, file_upload, temp_slider, tokens_slider], chatbot
 
398
  )
 
399
 
400
- clear_btn.click(lambda: None, None, chatbot, queue=False)
401
- stop_btn.click(fn=None, cancels=[submit_event, click_event])
402
 
403
  if __name__ == "__main__":
404
- demo.queue().launch()
 
1
  import spaces # MUST BE THE VERY FIRST IMPORT FOR ZEROGPU
2
  import os
3
  import io
4
+ import re
5
+ import json
6
+ import uuid
7
+ import zipfile
8
  import threading
9
+ import xml.etree.ElementTree as ET
10
+ from html.parser import HTMLParser
11
+ from datetime import datetime, timezone
12
  from pathlib import Path
13
 
14
  import requests
 
24
  AutoModelForCausalLM,
25
  AutoTokenizer,
26
  BitsAndBytesConfig,
27
+ StoppingCriteria,
28
+ StoppingCriteriaList,
29
  TextIteratorStreamer,
30
  )
31
  from peft import PeftModel
 
53
 
54
  ADAPTER_DIR = Path("adapters") / RELEASE_TAG
55
 
56
+ MAX_FILE_CHARS = 12000 # per attached file
57
+ MAX_HISTORY_CHARS = 40000 # prompt budget (oldest turns are dropped first)
58
+ MAX_CHATS = 40 # chats kept in the browser
59
+ STORAGE_KEY = "tutor_studio_chats_v1"
60
 
61
  # Your adapters were trained on Qwen3-8B, so the base model MUST be Qwen3-8B.
62
  BASE_MODEL = os.environ.get("BASE_MODEL") or "Qwen/Qwen3-8B"
 
69
  "Math": {"adapter": "math_adapter"},
70
  }
71
 
72
+ # ----------------------------- SUPPORTED FILE TYPES (30) -----------------------------
73
+
74
+ DOC_TYPES = [".pdf", ".docx", ".xlsx", ".pptx", ".odt", ".rtf", ".epub", ".html", ".ipynb"]
75
+ DATA_TYPES = [".txt", ".md", ".csv", ".tsv", ".json", ".xml", ".yaml", ".log", ".ini"]
76
+ CODE_TYPES = [".py", ".js", ".ts", ".java", ".c", ".cpp", ".cs", ".go", ".php", ".sql", ".sh", ".css"]
77
+ ALIAS_TYPES = [".htm", ".yml", ".toml", ".cfg", ".markdown", ".jsx", ".tsx", ".h", ".hpp", ".rb", ".rs"]
78
+
79
+ SUPPORTED_30 = DOC_TYPES + DATA_TYPES + CODE_TYPES
80
+ ACCEPTED_TYPES = SUPPORTED_30 + ALIAS_TYPES
81
+ SPECIAL_TYPES = set(DOC_TYPES) | {".htm"}
82
+ PLAIN_TEXT_TYPES = set(ACCEPTED_TYPES) - SPECIAL_TYPES
83
+
84
  # ----------------------------- MODEL LOADING -----------------------------
85
 
86
 
 
154
 
155
  # ----------------------------- FILE PARSING -----------------------------
156
 
157
+
158
+ class _HTMLText(HTMLParser):
159
+ def __init__(self):
160
+ super().__init__()
161
+ self.parts, self._skip = [], 0
162
+
163
+ def handle_starttag(self, tag, attrs):
164
+ if tag in ("script", "style"):
165
+ self._skip += 1
166
+
167
+ def handle_endtag(self, tag):
168
+ if tag in ("script", "style") and self._skip:
169
+ self._skip -= 1
170
+
171
+ def handle_data(self, data):
172
+ if not self._skip and data.strip():
173
+ self.parts.append(data.strip())
174
+
175
+
176
+ def html_to_text(raw: str) -> str:
177
+ p = _HTMLText()
178
+ p.feed(raw)
179
+ return "\n".join(p.parts)
180
+
181
+
182
+ def _read_pdf(data: bytes) -> str:
183
+ from pypdf import PdfReader
184
+ reader = PdfReader(io.BytesIO(data))
185
+ pages = []
186
+ for i, page in enumerate(reader.pages, 1):
187
+ t = (page.extract_text() or "").strip()
188
+ if t:
189
+ pages.append(f"[Page {i}]\n{t}")
190
+ return "\n\n".join(pages) or "[No extractable text found - this PDF may be a scan.]"
191
+
192
+
193
+ def _read_docx(data: bytes) -> str:
194
+ from docx import Document
195
+ doc = Document(io.BytesIO(data))
196
+ parts = [p.text for p in doc.paragraphs if p.text.strip()]
197
+ for table in doc.tables:
198
+ for row in table.rows:
199
+ cells = [c.text.strip() for c in row.cells]
200
+ if any(cells):
201
+ parts.append(" | ".join(cells))
202
+ return "\n".join(parts)
203
+
204
+
205
+ def _read_xlsx(data: bytes) -> str:
206
+ from openpyxl import load_workbook
207
+ wb = load_workbook(io.BytesIO(data), read_only=True, data_only=True)
208
+ parts, size = [], 0
209
+ for sheet in wb.worksheets:
210
+ parts.append(f"## Sheet: {sheet.title}")
211
+ for row in sheet.iter_rows(values_only=True):
212
+ row_str = " | ".join(str(v) for v in row if v is not None)
213
+ if row_str.strip():
214
+ parts.append(row_str)
215
+ size += len(row_str)
216
+ if size > MAX_FILE_CHARS:
217
+ return "\n".join(parts)
218
+ return "\n".join(parts)
219
+
220
+
221
+ def _read_pptx(data: bytes) -> str:
222
+ from pptx import Presentation
223
+ prs = Presentation(io.BytesIO(data))
224
+ parts = []
225
+ for i, slide in enumerate(prs.slides, 1):
226
+ parts.append(f"## Slide {i}")
227
+ for shape in slide.shapes:
228
+ if getattr(shape, "has_text_frame", False) and shape.text_frame.text.strip():
229
+ parts.append(shape.text_frame.text.strip())
230
+ return "\n".join(parts)
231
+
232
+
233
+ def _read_odt(data: bytes) -> str:
234
+ with zipfile.ZipFile(io.BytesIO(data)) as z:
235
+ root = ET.fromstring(z.read("content.xml"))
236
+ parts = []
237
+ for el in root.iter():
238
+ if el.tag.endswith("}p") or el.tag.endswith("}h"):
239
+ text = "".join(el.itertext()).strip()
240
+ if text:
241
+ parts.append(text)
242
+ return "\n".join(parts)
243
+
244
+
245
+ def _read_epub(data: bytes) -> str:
246
+ parts = []
247
+ with zipfile.ZipFile(io.BytesIO(data)) as z:
248
+ for name in sorted(z.namelist()):
249
+ if name.lower().endswith((".xhtml", ".html", ".htm")):
250
+ text = html_to_text(z.read(name).decode("utf-8", errors="replace"))
251
+ if text.strip():
252
+ parts.append(text)
253
+ return "\n\n".join(parts)
254
+
255
+
256
+ def _read_rtf(data: bytes) -> str:
257
+ raw = data.decode("utf-8", errors="replace")
258
+ try:
259
+ from striprtf.striprtf import rtf_to_text
260
+ return rtf_to_text(raw)
261
+ except Exception:
262
+ text = re.sub(r"\\[a-z]+-?\d* ?|[{}]", "", raw)
263
+ return text.strip()
264
+
265
+
266
+ def _read_ipynb(data: bytes) -> str:
267
+ nb = json.loads(data.decode("utf-8", errors="replace"))
268
+ parts = []
269
+ for cell in nb.get("cells", []):
270
+ src = cell.get("source", "")
271
+ src = "".join(src) if isinstance(src, list) else str(src)
272
+ if not src.strip():
273
+ continue
274
+ if cell.get("cell_type") == "code":
275
+ parts.append(f"```python\n{src}\n```")
276
+ else:
277
+ parts.append(src)
278
+ return "\n\n".join(parts)
279
 
280
 
281
  def file_path_of(file_obj) -> Path:
282
+ """Gradio may hand us a str path, a dict with 'path', or an object with .name."""
283
+ if isinstance(file_obj, str):
284
+ return Path(file_obj)
285
+ if isinstance(file_obj, dict):
286
+ return Path(file_obj.get("path") or file_obj.get("name"))
287
+ return Path(file_obj.name)
288
 
289
 
290
  def extract_text_from_upload(file_obj) -> str:
 
 
291
  path = file_path_of(file_obj)
292
  ext = path.suffix.lower()
293
+ if ext not in ACCEPTED_TYPES:
294
+ return f"[Unsupported file type: {ext or 'no extension'}]"
295
+ try:
296
+ data = path.read_bytes()
297
+ if ext in PLAIN_TEXT_TYPES:
298
+ return data.decode("utf-8", errors="replace")
299
+ if ext == ".pdf":
300
+ return _read_pdf(data)
301
+ if ext == ".docx":
302
+ return _read_docx(data)
303
+ if ext == ".xlsx":
304
+ return _read_xlsx(data)
305
+ if ext == ".pptx":
306
+ return _read_pptx(data)
307
+ if ext == ".odt":
308
+ return _read_odt(data)
309
+ if ext == ".epub":
310
+ return _read_epub(data)
311
+ if ext == ".rtf":
312
+ return _read_rtf(data)
313
+ if ext == ".ipynb":
314
+ return _read_ipynb(data)
315
+ if ext in (".html", ".htm"):
316
+ return html_to_text(data.decode("utf-8", errors="replace"))
317
+ except Exception as e:
318
+ return f"[Could not read {path.name}: {e}]"
319
+ return "[Unsupported file type]"
320
+
321
+
322
+ def build_file_context(files):
323
+ """Returns (context_text, file_names, skipped_names)."""
324
+ chunks, names, skipped = [], [], []
325
+ for f in files or []:
326
+ path = file_path_of(f)
327
+ names.append(path.name)
328
+ if path.suffix.lower() not in ACCEPTED_TYPES:
329
+ skipped.append(path.name)
330
+ continue
331
+ text = extract_text_from_upload(f)
332
+ total = len(text)
333
+ text = text[:MAX_FILE_CHARS]
334
+ if total > MAX_FILE_CHARS:
335
+ text += f"\n...[truncated: showing {MAX_FILE_CHARS} of {total} characters]"
336
+ chunks.append(f"--- File: {path.name} ---\n{text}")
337
+ return "\n\n".join(chunks), names, skipped
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338
 
339
 
340
  # ----------------------------- MATH CHECKER -----------------------------
 
375
  return f"SymPy Error: {e}"
376
 
377
 
378
+ # ----------------------------- GENERATION -----------------------------
379
 
380
 
381
+ def trim_messages(messages):
382
+ """Drop the oldest turns until the prompt fits MAX_HISTORY_CHARS (always keep the last message)."""
383
  def total(ms):
384
  return sum(len(m["content"]) for m in ms)
385
 
386
  while len(messages) > 1 and total(messages) > MAX_HISTORY_CHARS:
387
  messages.pop(0)
388
+ while len(messages) > 1 and messages[0]["role"] == "assistant":
 
389
  messages.pop(0)
390
  return messages
391
 
392
 
393
+ class StopOnFlag(StoppingCriteria):
394
+ """Lets us stop generation (and free the GPU) when the user presses Stop."""
 
395
 
396
+ def __init__(self, flag: threading.Event):
397
+ self.flag = flag
 
 
 
398
 
399
+ def __call__(self, input_ids, scores, **kwargs):
400
+ return torch.full((input_ids.shape[0],), self.flag.is_set(), dtype=torch.bool, device=input_ids.device)
401
 
402
+
403
+ @spaces.GPU(duration=120)
404
+ def generate_response(messages, mode, temperature, max_new_tokens):
405
+ adapter_name = MODES.get(mode, MODES["General"])["adapter"]
406
 
407
  prompt = tokenizer.apply_chat_template(
408
  messages,
 
410
  add_generation_prompt=True,
411
  enable_thinking=False,
412
  )
 
413
  inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
414
  streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
415
+ stop_flag = threading.Event()
416
  errors = []
417
 
418
  temperature = float(temperature)
 
421
  repetition_penalty=1.05,
422
  pad_token_id=tokenizer.pad_token_id,
423
  eos_token_id=tokenizer.convert_tokens_to_ids("<|im_end|>"),
424
+ stopping_criteria=StoppingCriteriaList([StopOnFlag(stop_flag)]),
425
  )
426
  if temperature > 0.01:
427
  gen_kwargs.update(do_sample=True, temperature=temperature, top_p=0.8)
 
441
  t = threading.Thread(target=worker, daemon=True)
442
  t.start()
443
 
444
+ partial = ""
445
+ try:
446
+ for new_text in streamer:
447
+ partial += new_text
448
+ yield partial
449
+ t.join()
450
+ if errors:
451
+ yield partial + f"\n\n⚠️ Generation error: {errors[0]}"
452
+ finally:
453
+ stop_flag.set() # also fires when the user presses Stop
454
+ t.join(timeout=10)
455
+
456
+
457
+ # ----------------------------- CHAT STORE (kept in the visitor's own browser) -----------------------------
458
+
459
+
460
+ def now_iso():
461
+ return datetime.now(timezone.utc).isoformat()
462
+
463
+
464
+ def new_chat_obj():
465
+ return {"id": uuid.uuid4().hex[:12], "title": "New chat", "updated": now_iso(), "turns": []}
466
+
467
+
468
+ def ensure_store(store):
469
+ if not isinstance(store, dict) or not isinstance(store.get("chats"), dict):
470
+ store = {"chats": {}, "current": None}
471
+ if store.get("current") not in store["chats"]:
472
+ if store["chats"]:
473
+ store["current"] = max(store["chats"].values(), key=lambda c: c["updated"])["id"]
474
+ else:
475
+ chat = new_chat_obj()
476
+ store["chats"][chat["id"]] = chat
477
+ store["current"] = chat["id"]
478
+ return store
479
+
480
+
481
+ def current_chat(store):
482
+ return store["chats"][store["current"]]
483
 
484
+
485
+ def normalize_store(store):
486
+ """Turns that never got an answer (stopped / interrupted) get a note instead of staying blank."""
487
+ for cid, chat in store["chats"].items():
488
+ if cid == store.get("busy"):
489
+ continue
490
+ for turn in chat["turns"]:
491
+ if not turn.get("a"):
492
+ turn["a"] = "*(no response)*"
493
+ return store
494
+
495
+
496
+ def make_title(text, names):
497
+ base = (text or "").strip().splitlines()[0] if (text or "").strip() else ""
498
+ if not base and names:
499
+ base = f"📎 {names[0]}"
500
+ base = base or "New chat"
501
+ return base if len(base) <= 38 else base[:37] + "…"
502
+
503
+
504
+ def history_update(store):
505
+ chats = sorted(store["chats"].values(), key=lambda c: c["updated"], reverse=True)
506
+ return gr.update(choices=[(c["title"], c["id"]) for c in chats], value=store["current"])
507
+
508
+
509
+ def user_display(turn):
510
+ parts = []
511
+ if turn.get("u"):
512
+ parts.append(turn["u"])
513
+ if turn.get("files"):
514
+ parts.append("\n".join(f"📎 {n}" for n in turn["files"]))
515
+ return "\n\n".join(parts)
516
+
517
+
518
+ def chat_display(chat):
519
+ return [[user_display(t), (t.get("a") or "…")] for t in chat["turns"]]
520
+
521
+
522
+ def store_to_json(store):
523
+ store = ensure_store(store)
524
+ data = {"chats": store["chats"], "current": store["current"]}
525
+ s = json.dumps(data)
526
+ # localStorage is ~5 MB: drop the oldest chats if we are getting close
527
+ while len(s) > 3_500_000 and len(data["chats"]) > 1:
528
+ oldest = min(
529
+ (c for cid, c in data["chats"].items() if cid != data["current"]),
530
+ key=lambda c: c["updated"],
531
+ )
532
+ del data["chats"][oldest["id"]]
533
+ s = json.dumps(data)
534
+ return s
535
+
536
+
537
+ def prune_chats(store):
538
+ while len(store["chats"]) > MAX_CHATS:
539
+ oldest = min(
540
+ (c for cid, c in store["chats"].items() if cid != store["current"]),
541
+ key=lambda c: c["updated"],
542
+ )
543
+ del store["chats"][oldest["id"]]
544
+
545
+
546
+ def build_messages(chat):
547
+ msgs = []
548
+ for t in chat["turns"]:
549
+ content = t.get("u") or ""
550
+ if t.get("ctx"):
551
+ content += "\n\nAttached files:\n" + t["ctx"]
552
+ msgs.append({"role": "user", "content": content})
553
+ if t.get("a"):
554
+ msgs.append({"role": "assistant", "content": t["a"]})
555
+ return trim_messages(msgs)
556
+
557
+
558
+ # ----------------------------- UI HANDLERS -----------------------------
559
+
560
+
561
+ def on_load(raw):
562
+ try:
563
+ parsed = json.loads(raw) if raw else None
564
+ except Exception:
565
+ parsed = None
566
+ store = normalize_store(ensure_store(parsed))
567
+ return store, history_update(store), chat_display(current_chat(store))
568
+
569
+
570
+ def new_chat(store):
571
+ store = ensure_store(store)
572
+ if store.get("busy"):
573
+ return store, history_update(store), chat_display(current_chat(store))
574
+ if not current_chat(store)["turns"]: # already on an empty chat
575
+ return store, history_update(store), chat_display(current_chat(store))
576
+ chat = new_chat_obj()
577
+ store["chats"][chat["id"]] = chat
578
+ store["current"] = chat["id"]
579
+ prune_chats(store)
580
+ return store, history_update(store), []
581
+
582
+
583
+ def select_chat(chat_id, store):
584
+ store = ensure_store(store)
585
+ if not store.get("busy") and chat_id in store["chats"]:
586
+ store["current"] = chat_id
587
+ normalize_store(store)
588
+ return store, history_update(store), chat_display(current_chat(store))
589
+
590
+
591
+ def delete_chat(store):
592
+ store = ensure_store(store)
593
+ if store.get("busy"):
594
+ return store, history_update(store), chat_display(current_chat(store))
595
+ del store["chats"][store["current"]]
596
+ store["current"] = None
597
+ store = normalize_store(ensure_store(store))
598
+ return store, history_update(store), chat_display(current_chat(store))
599
+
600
+
601
+ def add_user(msg, store):
602
+ store = ensure_store(store)
603
+ chat = current_chat(store)
604
+ keep = gr.skip()
605
+ if store.get("busy"):
606
+ gr.Warning("Please wait for the current answer to finish (or press Stop).")
607
+ return store, chat_display(chat), keep, history_update(store)
608
+
609
+ msg = msg or {}
610
+ text = (msg.get("text") or "").strip()
611
+ files = msg.get("files") or []
612
+ if not text and not files:
613
+ return store, chat_display(chat), keep, history_update(store)
614
+
615
+ ctx, names, skipped = build_file_context(files)
616
+ if skipped:
617
+ gr.Warning("Unsupported file type skipped: " + ", ".join(skipped))
618
+ if not text:
619
+ text = "Please summarize the attached file(s)."
620
+
621
+ chat["turns"].append({"u": text, "files": names, "ctx": ctx, "a": ""})
622
+ if len(chat["turns"]) == 1:
623
+ chat["title"] = make_title(text, names)
624
+ chat["updated"] = now_iso()
625
+ store["pending"] = True
626
+ return store, chat_display(chat), {"text": "", "files": []}, history_update(store)
627
+
628
+
629
+ def respond(store, mode, temperature, max_new_tokens):
630
+ store = ensure_store(store)
631
+ chat = current_chat(store)
632
+ if not store.get("pending") or not chat["turns"]:
633
+ yield store, chat_display(chat), gr.skip()
634
+ return
635
+
636
+ store["pending"] = False
637
+ store["busy"] = chat["id"]
638
+ turn = chat["turns"][-1]
639
+ messages = build_messages(chat)
640
+ yield store, chat_display(chat), gr.skip()
641
+
642
+ try:
643
+ for partial in generate_response(messages, mode, temperature, max_new_tokens):
644
+ turn["a"] = partial
645
+ if store.get("current") == chat["id"]:
646
+ yield store, chat_display(chat), gr.skip()
647
+ except Exception as e:
648
+ turn["a"] = (turn.get("a") or "") + f"\n\n⚠️ {e}"
649
+ finally:
650
+ store["busy"] = None
651
+
652
+ if not turn.get("a"):
653
+ turn["a"] = "*(no response)*"
654
+ chat["updated"] = now_iso()
655
+ yield store, chat_display(chat), history_update(store)
656
+
657
+
658
+ def stop_save(store):
659
+ store = ensure_store(store)
660
+ store["busy"] = None
661
+ store["pending"] = False
662
+ normalize_store(store)
663
+ return store, chat_display(current_chat(store))
664
 
665
 
666
  # ----------------------------- GRADIO UI -----------------------------
667
 
668
+ CSS = """
669
+ :root { --bg:#faf9f5; --side:#f0eee6; --line:#e5e2d8; --ink:#1f1e1d; --muted:#6b6a65; --accent:#c96442; --accent-d:#b5573a; }
670
+ body, .gradio-container { background: var(--bg) !important; color: var(--ink) !important; }
671
+ .gradio-container { max-width: 100% !important; padding: 0 !important; font-family: 'Inter', system-ui, sans-serif !important; }
672
+ footer { display: none !important; }
673
+
674
+ /* ---- sidebar ---- */
675
+ #sidebar { background: var(--side); border-right: 1px solid var(--line); padding: 18px 14px !important;
676
+ min-height: 100vh; position: sticky; top: 0; align-self: flex-start; max-height: 100vh; overflow-y: auto; gap: 10px !important; }
677
+ #brand { font-family: Georgia, 'Times New Roman', serif; font-size: 1.35rem; color: var(--ink); margin: 2px 4px 6px; }
678
+ #brand p { margin: 0 !important; }
679
+ #new-chat { background: var(--accent) !important; color: #fff !important; border: none !important; border-radius: 10px !important; font-weight: 600; }
680
+ #new-chat:hover { background: var(--accent-d) !important; }
681
+ #recents-label { color: var(--muted); font-size: .75rem; text-transform: uppercase; letter-spacing: .06em; margin: 8px 6px 0; }
682
+ #recents-label p { margin: 0 !important; }
683
+ #history, #history .wrap { background: transparent !important; border: none !important; padding: 0 !important; box-shadow: none !important; }
684
+ #history .wrap { display: flex; flex-direction: column; gap: 2px; }
685
+ #history label { background: transparent !important; border: none !important; border-radius: 8px !important; padding: 8px 10px !important;
686
+ width: 100%; cursor: pointer; color: var(--ink) !important; box-shadow: none !important; }
687
+ #history label:hover { background: #e8e5da !important; }
688
+ #history label.selected { background: #e3dfd2 !important; font-weight: 600; }
689
+ #history label span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: block; max-width: 210px; }
690
+ #history input { display: none !important; }
691
+ #delete-chat { background: transparent !important; border: 1px solid var(--line) !important; color: var(--muted) !important; border-radius: 10px !important; }
692
+ #delete-chat:hover { color: #b3261e !important; border-color: #b3261e !important; }
693
+ #sidebar .block, #sidebar .form { background: transparent !important; border: none !important; box-shadow: none !important; }
694
+ #sidebar .accordion, #sidebar .label-wrap { background: transparent !important; color: var(--ink) !important; }
695
+
696
+ /* ---- main column ---- */
697
+ #main { max-width: 860px; margin: 0 auto; padding: 18px 20px 10px !important; }
698
+ #chatbot { background: transparent !important; border: none !important; box-shadow: none !important; }
699
+ #chatbot .message-row .message { border: none !important; box-shadow: none !important; font-size: 1rem; line-height: 1.65; }
700
+ #chatbot .message.bot, #chatbot .bot.message { background: transparent !important; color: var(--ink) !important; padding-left: 4px !important; }
701
+ #chatbot .message.user, #chatbot .user.message { background: var(--side) !important; color: var(--ink) !important; border-radius: 16px !important; }
702
+ #chatbot .placeholder-content, #chatbot .placeholder { text-align: center; font-family: Georgia, serif; color: var(--ink); }
703
+ #chatbot .placeholder h2 { font-weight: 400; font-size: 2rem; }
704
+ #chatbot .placeholder p { font-family: 'Inter', sans-serif; color: var(--muted); }
705
+ #mode-pills, #mode-pills .wrap { background: transparent !important; border: none !important; box-shadow: none !important; padding: 0 !important; justify-content: center; }
706
+ #mode-pills label { border-radius: 999px !important; border: 1px solid var(--line) !important; background: #fff !important; padding: 6px 16px !important;
707
+ color: var(--ink) !important; cursor: pointer; box-shadow: none !important; }
708
+ #mode-pills label.selected { background: var(--accent) !important; border-color: var(--accent) !important; color: #fff !important; }
709
+ #mode-pills input { display: none !important; }
710
+ #composer { background: #fff !important; border: 1px solid var(--line) !important; border-radius: 22px !important;
711
+ box-shadow: 0 2px 10px rgba(0,0,0,.05) !important; }
712
+ #composer textarea { background: #fff !important; color: var(--ink) !important; }
713
+ #composer button.submit-button, #composer .submit-button { background: var(--accent) !important; color: #fff !important; border-radius: 10px !important; }
714
+ #stop-btn { background: transparent !important; border: 1px solid var(--line) !important; color: var(--muted) !important; border-radius: 10px !important; max-width: 160px; margin: 0 auto; }
715
+ #hint { color: var(--muted); font-size: .8rem; text-align: center; }
716
+ #hint p { margin: 0 !important; }
717
+ @media (max-width: 800px) { #sidebar { min-height: auto; position: static; max-height: none; } }
718
  """
719
 
720
+ FORCE_LIGHT_JS = "() => { document.body.classList.remove('dark'); document.documentElement.classList.remove('dark'); }"
721
+
722
+ LOAD_JS = f"""(v) => {{
723
+ try {{ return [localStorage.getItem('{STORAGE_KEY}') || '']; }} catch (e) {{ return ['']; }}
724
+ }}"""
725
+
726
+ SAVE_JS = f"""(v) => {{
727
+ try {{ localStorage.setItem('{STORAGE_KEY}', v); }} catch (e) {{ console.warn('Could not save chats', e); }}
728
+ }}"""
729
+
730
+ LATEX = [
731
+ {"left": "$$", "right": "$$", "display": True},
732
+ {"left": "\\[", "right": "\\]", "display": True},
733
+ {"left": "\\(", "right": "\\)", "display": False},
734
+ {"left": "$", "right": "$", "display": False},
735
+ ]
736
+
737
+ WELCOME = "## ✨ How can I help you today?\n\nPick a mode, ask a question, or attach a file with the 📎 button."
738
+
739
+ SUPPORTED_MD = (
740
+ "**Documents:** " + ", ".join(DOC_TYPES) + " \n"
741
+ "**Data & text:** " + ", ".join(DATA_TYPES) + " \n"
742
+ "**Code:** " + ", ".join(CODE_TYPES) + " \n"
743
+ "**Also accepted:** " + ", ".join(ALIAS_TYPES) + " \n\n"
744
+ f"Long files are cut to {MAX_FILE_CHARS:,} characters each. Images, audio and legacy "
745
+ ".doc/.xls/.ppt files are not supported (save them as .docx/.xlsx/.pptx first)."
746
+ )
747
+
748
+ theme = gr.themes.Base(
749
+ primary_hue="orange",
750
+ neutral_hue="stone",
751
+ font=[gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"],
752
+ ).set(
753
+ body_background_fill="#faf9f5",
754
+ body_text_color="#1f1e1d",
755
+ block_background_fill="transparent",
756
+ block_border_width="0px",
757
+ input_background_fill="#ffffff",
758
+ button_primary_background_fill="#c96442",
759
+ button_primary_background_fill_hover="#b5573a",
760
+ button_primary_text_color="#ffffff",
761
+ )
762
+
763
+ with gr.Blocks(theme=theme, css=CSS, title="Tutor Studio", js=FORCE_LIGHT_JS) as demo:
764
+ session = gr.State(None) # the chat store for this visitor (server-side, per session)
765
+ persist_in = gr.Textbox(visible=False) # receives localStorage content on page load
766
+ persist_out = gr.Textbox(visible=False) # carries JSON to the browser for saving
767
+
768
+ with gr.Row(equal_height=False):
769
+ # ---------------- sidebar ----------------
770
+ with gr.Column(scale=1, min_width=270, elem_id="sidebar"):
771
+ gr.Markdown("✨ Tutor Studio", elem_id="brand")
772
+ new_btn = gr.Button("+ New chat", elem_id="new-chat")
773
+ gr.Markdown("Recents", elem_id="recents-label")
774
+ history_list = gr.Radio(choices=[], value=None, show_label=False, container=False, elem_id="history")
775
+ delete_btn = gr.Button("🗑 Delete this chat", elem_id="delete-chat", size="sm")
776
+
777
+ with gr.Accordion("Generation settings", open=False):
778
+ temp_slider = gr.Slider(0.0, 1.0, value=0.35, step=0.05, label="Creativity (temperature)")
779
+ tokens_slider = gr.Slider(256, 4096, value=1600, step=128, label="Max response tokens")
780
+
781
+ with gr.Accordion("🧮 SymPy math checker", open=False):
782
+ sympy_input = gr.Textbox(label="Expression", value="diff(x**3 + 5*x, x)")
783
+ sympy_output = gr.Textbox(label="Result", interactive=False)
784
+ sympy_btn = gr.Button("Calculate")
785
+ sympy_btn.click(run_sympy, inputs=sympy_input, outputs=sympy_output)
786
+
787
+ with gr.Accordion("📎 Supported file types (30)", open=False):
788
+ gr.Markdown(SUPPORTED_MD)
789
+
790
+ # ---------------- main chat ----------------
791
+ with gr.Column(scale=4, elem_id="main"):
792
+ chatbot = gr.Chatbot(
793
+ elem_id="chatbot",
794
+ show_label=False,
795
+ height="62vh",
796
+ bubble_full_width=False,
797
+ show_copy_button=True,
798
+ latex_delimiters=LATEX,
799
+ placeholder=WELCOME,
800
+ )
801
  mode_radio = gr.Radio(
802
+ choices=list(MODES.keys()), value="General",
803
+ show_label=False, container=False, elem_id="mode-pills",
 
 
804
  )
805
+ composer = gr.MultimodalTextbox(
806
+ elem_id="composer",
807
+ show_label=False,
808
+ container=False,
809
+ file_types=ACCEPTED_TYPES,
810
  file_count="multiple",
811
+ placeholder="Message Tutor Studio… (use 📎 to attach files)",
812
+ lines=1,
813
+ max_lines=8,
814
  )
815
+ stop_btn = gr.Button("■ Stop generating", elem_id="stop-btn", size="sm")
816
+ gr.Markdown("Chats are saved only in this browser. Tutor Studio can make mistakes - check important answers.", elem_id="hint")
817
+
818
+ # ---------------- events ----------------
819
+ def persist(event):
820
+ """After any change: serialize the store and save it to the browser's localStorage."""
821
+ return event.then(store_to_json, [session], [persist_out], show_progress="hidden").then(
822
+ None, [persist_out], None, js=SAVE_JS
823
+ )
824
 
825
+ sidebar_outputs = [session, history_list, chatbot]
826
+
827
+ demo.load(on_load, [persist_in], sidebar_outputs, js=LOAD_JS)
828
+
829
+ persist(new_btn.click(new_chat, [session], sidebar_outputs, show_progress="hidden"))
830
+ persist(history_list.input(select_chat, [history_list, session], sidebar_outputs, show_progress="hidden"))
831
+ persist(delete_btn.click(delete_chat, [session], sidebar_outputs, show_progress="hidden"))
832
 
833
+ send = composer.submit(
834
+ add_user, [composer, session], [session, chatbot, composer, history_list], show_progress="hidden"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
835
  )
836
+ generate = send.then(
837
+ respond, [session, mode_radio, temp_slider, tokens_slider], [session, chatbot, history_list],
838
+ show_progress="hidden",
839
  )
840
+ persist(generate)
841
 
842
+ stop_event = stop_btn.click(stop_save, [session], [session, chatbot], cancels=[generate], show_progress="hidden")
843
+ persist(stop_event)
844
 
845
  if __name__ == "__main__":
846
+ demo.queue(max_size=20).launch()
requirements.txt CHANGED
@@ -11,4 +11,5 @@ pypdf
11
  python-docx
12
  openpyxl
13
  python-pptx
14
- requests
 
 
11
  python-docx
12
  openpyxl
13
  python-pptx
14
+ striprtf
15
+ requests