aimanathar commited on
Commit
e6365ab
·
verified ·
1 Parent(s): 6d76d25

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -0
app.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch, textwrap, numpy as np, faiss
2
+ import warnings
3
+ warnings.filterwarnings("ignore")
4
+ from pdfminer.high_level import extract_text
5
+ from pdf2image import convert_from_path
6
+ import pytesseract
7
+ from sentence_transformers import SentenceTransformer
8
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
9
+ import gradio as gr
10
+
11
+ # ================== PDF Handling Functions ==================
12
+ def pdf_to_text(path):
13
+ try:
14
+ txt = extract_text(path) or ""
15
+ except Exception:
16
+ txt = ""
17
+ if len(txt.strip()) < 200:
18
+ try:
19
+ pages = convert_from_path(path, dpi=200)
20
+ ocr_all = [pytesseract.image_to_string(img) for img in pages]
21
+ txt = "\n".join(ocr_all)
22
+ except Exception:
23
+ txt = ""
24
+ return txt
25
+
26
+ def chunk_text(text, max_chars=800):
27
+ paras = [p.strip() for p in text.split("\n") if p.strip()]
28
+ chunks, buf = [], ""
29
+ for p in paras:
30
+ if len(p) > max_chars:
31
+ for piece in textwrap.wrap(p, width=max_chars, break_long_words=False):
32
+ chunks.append(piece.strip())
33
+ else:
34
+ if len(buf) + len(p) + 1 <= max_chars:
35
+ buf = (buf + "\n" + p).strip()
36
+ else:
37
+ if buf: chunks.append(buf)
38
+ buf = p
39
+ if buf: chunks.append(buf)
40
+ return [c for c in chunks if len(c) > 80]
41
+
42
+ # ================== Load Embeddings + Model ==================
43
+ embed_model = SentenceTransformer("all-MiniLM-L6-v2")
44
+
45
+ model_id = "google/flan-t5-base"
46
+ tok = AutoTokenizer.from_pretrained(model_id)
47
+ gen_model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
48
+ device = "cuda" if torch.cuda.is_available() else "cpu"
49
+ gen_model.to(device)
50
+
51
+ # ================== Chat Function ==================
52
+ def chat_fn(message, history=None):
53
+ prompt = f"Answer clearly and exam-ready:\n\nQuestion:\n{message}"
54
+ inputs = tok(prompt, return_tensors="pt", truncation=True, padding=True, max_length=1024).to(device)
55
+ out = gen_model.generate(**inputs, max_new_tokens=120, num_beams=4, do_sample=False)
56
+ return tok.decode(out[0], skip_special_tokens=True).strip()
57
+
58
+ # ================== Gradio Interface ==================
59
+ iface = gr.ChatInterface(
60
+ fn=chat_fn,
61
+ title="💬 Practical Chatbot",
62
+ description="Ask about Physics & Chemistry Practicals (Class 9–10)."
63
+ )
64
+
65
+ iface.launch()