damoojeje commited on
Commit
57fff59
·
verified ·
1 Parent(s): d06b252

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -100
app.py CHANGED
@@ -1,4 +1,3 @@
1
-
2
  import os
3
  import fitz
4
  import json
@@ -6,100 +5,85 @@ import gradio as gr
6
  import pytesseract
7
  import chromadb
8
  import torch
9
- import asyncio
10
- import docx2txt
11
  import nltk
12
  import traceback
 
13
  from PIL import Image
14
  from io import BytesIO
15
  from tqdm import tqdm
16
- from transformers import (
17
- pipeline,
18
- AutoModelForCausalLM,
19
- AutoTokenizer
20
- )
21
  from sentence_transformers import SentenceTransformer, util
22
  from nltk.tokenize import sent_tokenize
23
 
24
- # Ensure punkt is available
25
  try:
26
  nltk.data.find("tokenizers/punkt")
27
  except LookupError:
28
  nltk.download("punkt")
29
 
30
- # ---------------- Config ----------------
 
31
  MANUALS_DIR = "Manuals"
32
  CHROMA_PATH = "chroma_store"
33
  COLLECTION_NAME = "manual_chunks"
34
  CHUNK_SIZE = 750
35
  CHUNK_OVERLAP = 100
36
  MAX_CONTEXT_CHUNKS = 3
 
37
 
38
- MODELS = {
39
- "LLaMA 3 (8B)": "meta-llama/Llama-3.1-8B-Instruct",
40
- "Mistral 7B": "mistralai/Mistral-7B-Instruct-v0.3",
41
- "Gemma 2B": "google/gemma-1.1-2b-it",
42
- "LLaMA 4 (Scout 17B)": "meta-llama/Llama-4-Scout-17B-16E",
43
- "Qwen 30B": "Qwen/Qwen3-30B-A3B"
44
- }
45
-
46
- HF_TOKEN = os.environ.get("HF_TOKEN")
47
  device = "cuda" if torch.cuda.is_available() else "cpu"
48
 
49
- # ---------------- Utils ----------------
50
  def clean(text):
51
  return "\n".join([line.strip() for line in text.splitlines() if line.strip()])
52
 
53
  def split_sentences(text):
54
  try:
55
  return sent_tokenize(text)
56
- except Exception as e:
57
- print("[Tokenizer Error]", e)
58
  return text.split(". ")
59
 
60
- def split_into_chunks(sentences, max_tokens=CHUNK_SIZE, overlap=CHUNK_OVERLAP):
61
  chunks = []
62
- current_chunk, current_len = [], 0
63
 
64
- for sentence in sentences:
65
- words = sentence.split()
66
- if current_len + len(words) > max_tokens and current_chunk:
67
  chunks.append(" ".join(current_chunk))
68
  current_chunk = current_chunk[-overlap:]
69
- current_len = sum(len(s.split()) for s in current_chunk)
70
-
71
- current_chunk.append(sentence)
72
- current_len += len(words)
73
 
74
  if current_chunk:
75
  chunks.append(" ".join(current_chunk))
76
-
77
  return chunks
78
 
79
- def extract_pdf_text(pdf_path):
80
- text_chunks = []
 
81
  try:
82
- doc = fitz.open(pdf_path)
83
  for i, page in enumerate(doc):
84
  text = page.get_text().strip()
85
  if not text:
86
- pix = page.get_pixmap(dpi=300)
87
- img = Image.open(BytesIO(pix.tobytes("png")))
88
  text = pytesseract.image_to_string(img)
89
- text_chunks.append((pdf_path, i + 1, clean(text)))
90
  except Exception as e:
91
- print("❌ Error reading PDF:", pdf_path, e)
92
- return text_chunks
93
 
94
- def extract_docx_text(docx_path):
95
  try:
96
- text = clean(docx2txt.process(docx_path))
97
- return [(docx_path, 1, text)]
98
  except Exception as e:
99
- print("❌ Error reading DOCX:", docx_path, e)
100
  return []
101
 
102
- # ---------------- Background Embed ----------------
103
  def embed_all():
104
  embedder = SentenceTransformer("all-MiniLM-L6-v2")
105
  embedder.eval()
@@ -111,9 +95,8 @@ def embed_all():
111
  pass
112
  collection = client.get_or_create_collection(COLLECTION_NAME)
113
 
114
- chunks, ids, metas = [], [], []
115
- idx = 0
116
- print("📄 Scanning Manuals folder...")
117
 
118
  for fname in os.listdir(MANUALS_DIR):
119
  fpath = os.path.join(MANUALS_DIR, fname)
@@ -124,80 +107,77 @@ def embed_all():
124
  else:
125
  continue
126
 
127
- for filepath, page, text in pages:
128
- sentences = split_sentences(text)
129
- subchunks = split_into_chunks(sentences)
130
- for i, subchunk in enumerate(subchunks):
131
- chunks.append(subchunk)
132
- ids.append(f"{fname}::{page}::{i}")
133
  metas.append({"source": fname, "page": page})
134
 
135
- if len(chunks) >= 16:
136
- embs = embedder.encode(chunks).tolist()
137
- collection.add(documents=chunks, ids=ids, metadatas=metas, embeddings=embs)
138
- chunks, ids, metas = [], [], []
139
 
140
- if chunks:
141
- embs = embedder.encode(chunks).tolist()
142
- collection.add(documents=chunks, ids=ids, metadatas=metas, embeddings=embs)
143
 
144
  print(f"✅ Embedded {len(ids)} chunks.")
145
  return collection, embedder
146
 
147
- # ---------------- Model Loader ----------------
148
- def load_model(model_id):
149
- tokenizer = AutoTokenizer.from_pretrained(model_id, token=HF_TOKEN)
150
- model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32, token=HF_TOKEN)
 
 
 
 
 
151
  pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0 if torch.cuda.is_available() else -1)
152
  return pipe, tokenizer
153
 
154
- # ---------------- Query ----------------
155
- def query_llm(context, question, pipe, tokenizer):
156
- prompt = f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
157
- You are a helpful assistant. Use only the following context to answer. If uncertain, say: 'I don't know.'
158
 
 
159
  {context}
160
- <|start_header_id|>user<|end_header_id|>
161
- {question}
162
- <|start_header_id|>assistant<|end_header_id|>
163
- """
164
- out = pipe(prompt, max_new_tokens=512)[0]["generated_text"]
165
- return out.split("<|start_header_id|>assistant<|end_header_id|>")[-1].strip()
166
-
167
- def answer_question(question, model_choice):
 
168
  try:
169
- model_id = MODELS[model_choice]
170
- pipe, tokenizer = load_model(model_id)
171
  query_emb = embedder.encode(question, convert_to_tensor=True)
172
-
173
  results = db.query(query_texts=[question], n_results=MAX_CONTEXT_CHUNKS)
174
- context_chunks = results["documents"][0]
175
- context = "\n\n".join(context_chunks)
176
-
177
- answer = query_llm(context, question, pipe, tokenizer)
178
- return answer
179
  except Exception as e:
180
- traceback.print_exc()
181
- return f"Error: {str(e)}"
182
 
183
- # ---------------- Run App ----------------
184
  with gr.Blocks() as demo:
185
- gr.Markdown("### 📘 Ask Questions About Your Manuals")
186
-
187
- model_choice = gr.Dropdown(label="Select Model", choices=list(MODELS.keys()), value="LLaMA 3 (8B)")
188
- question = gr.Textbox(label="Your Question", placeholder="e.g. How do I reset the treadmill?")
189
- submit = gr.Button("🔍 Get Answer")
190
- answer = gr.Textbox(label="Answer", lines=10)
191
-
192
- submit.click(fn=answer_question, inputs=[question, model_choice], outputs=answer)
193
-
194
- # Run background embed on startup
195
  try:
196
  db, embedder = embed_all()
 
197
  except Exception as e:
198
- print("❌ Failed to embed docs:", e)
199
  db, embedder = None, None
 
200
 
201
- # Only launch if in HF Space
202
  if __name__ == "__main__":
203
  demo.launch()
 
 
1
  import os
2
  import fitz
3
  import json
 
5
  import pytesseract
6
  import chromadb
7
  import torch
 
 
8
  import nltk
9
  import traceback
10
+ import docx2txt
11
  from PIL import Image
12
  from io import BytesIO
13
  from tqdm import tqdm
14
+ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
 
 
 
 
15
  from sentence_transformers import SentenceTransformer, util
16
  from nltk.tokenize import sent_tokenize
17
 
18
+ # Ensure punkt is downloaded
19
  try:
20
  nltk.data.find("tokenizers/punkt")
21
  except LookupError:
22
  nltk.download("punkt")
23
 
24
+ # Configuration
25
+ HF_TOKEN = os.getenv("HF_TOKEN")
26
  MANUALS_DIR = "Manuals"
27
  CHROMA_PATH = "chroma_store"
28
  COLLECTION_NAME = "manual_chunks"
29
  CHUNK_SIZE = 750
30
  CHUNK_OVERLAP = 100
31
  MAX_CONTEXT_CHUNKS = 3
32
+ MODEL_ID = "ibm-granite/granite-vision-3.2-2b"
33
 
 
 
 
 
 
 
 
 
 
34
  device = "cuda" if torch.cuda.is_available() else "cpu"
35
 
36
+ # ---------------- Text Helpers ----------------
37
  def clean(text):
38
  return "\n".join([line.strip() for line in text.splitlines() if line.strip()])
39
 
40
  def split_sentences(text):
41
  try:
42
  return sent_tokenize(text)
43
+ except:
44
+ print("⚠️ Tokenizer fallback: simple split.")
45
  return text.split(". ")
46
 
47
+ def split_chunks(sentences, max_tokens=CHUNK_SIZE, overlap=CHUNK_OVERLAP):
48
  chunks = []
49
+ current_chunk, length = [], 0
50
 
51
+ for sent in sentences:
52
+ words = sent.split()
53
+ if length + len(words) > max_tokens and current_chunk:
54
  chunks.append(" ".join(current_chunk))
55
  current_chunk = current_chunk[-overlap:]
56
+ length = sum(len(s.split()) for s in current_chunk)
57
+ current_chunk.append(sent)
58
+ length += len(words)
 
59
 
60
  if current_chunk:
61
  chunks.append(" ".join(current_chunk))
 
62
  return chunks
63
 
64
+ # ---------------- File Readers ----------------
65
+ def extract_pdf_text(path):
66
+ chunks = []
67
  try:
68
+ doc = fitz.open(path)
69
  for i, page in enumerate(doc):
70
  text = page.get_text().strip()
71
  if not text:
72
+ img = Image.open(BytesIO(page.get_pixmap(dpi=300).tobytes("png")))
 
73
  text = pytesseract.image_to_string(img)
74
+ chunks.append((path, i + 1, clean(text)))
75
  except Exception as e:
76
+ print("❌ PDF read error:", path, e)
77
+ return chunks
78
 
79
+ def extract_docx_text(path):
80
  try:
81
+ return [(path, 1, clean(docx2txt.process(path)))]
 
82
  except Exception as e:
83
+ print("❌ DOCX read error:", path, e)
84
  return []
85
 
86
+ # ---------------- Embedding ----------------
87
  def embed_all():
88
  embedder = SentenceTransformer("all-MiniLM-L6-v2")
89
  embedder.eval()
 
95
  pass
96
  collection = client.get_or_create_collection(COLLECTION_NAME)
97
 
98
+ docs, ids, metas = [], [], []
99
+ print("📄 Processing manuals...")
 
100
 
101
  for fname in os.listdir(MANUALS_DIR):
102
  fpath = os.path.join(MANUALS_DIR, fname)
 
107
  else:
108
  continue
109
 
110
+ for path, page, text in pages:
111
+ for i, chunk in enumerate(split_chunks(split_sentences(text))):
112
+ chunk_id = f"{fname}::{page}::{i}"
113
+ docs.append(chunk)
114
+ ids.append(chunk_id)
 
115
  metas.append({"source": fname, "page": page})
116
 
117
+ if len(docs) >= 16:
118
+ embs = embedder.encode(docs).tolist()
119
+ collection.add(documents=docs, ids=ids, metadatas=metas, embeddings=embs)
120
+ docs, ids, metas = [], [], []
121
 
122
+ if docs:
123
+ embs = embedder.encode(docs).tolist()
124
+ collection.add(documents=docs, ids=ids, metadatas=metas, embeddings=embs)
125
 
126
  print(f"✅ Embedded {len(ids)} chunks.")
127
  return collection, embedder
128
 
129
+ # ---------------- Model Setup ----------------
130
+ def load_model():
131
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, token=HF_TOKEN)
132
+ model = AutoModelForCausalLM.from_pretrained(
133
+ MODEL_ID,
134
+ token=HF_TOKEN,
135
+ device_map="auto" if torch.cuda.is_available() else None,
136
+ torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32
137
+ ).to(device)
138
  pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0 if torch.cuda.is_available() else -1)
139
  return pipe, tokenizer
140
 
141
+ def ask_model(question, context, pipe, tokenizer):
142
+ prompt = f"""Use only the following context to answer. If uncertain, say "I don't know."
 
 
143
 
144
+ <context>
145
  {context}
146
+ </context>
147
+
148
+ Q: {question}
149
+ A:"""
150
+ output = pipe(prompt, max_new_tokens=512)[0]["generated_text"]
151
+ return output.split("A:")[-1].strip()
152
+
153
+ # ---------------- Query ----------------
154
+ def get_answer(question):
155
  try:
 
 
156
  query_emb = embedder.encode(question, convert_to_tensor=True)
 
157
  results = db.query(query_texts=[question], n_results=MAX_CONTEXT_CHUNKS)
158
+ context = "\n\n".join(results["documents"][0])
159
+ return ask_model(question, context, model_pipe, model_tokenizer)
 
 
 
160
  except Exception as e:
161
+ print("❌ Query error:", e)
162
+ return f"Error: {e}"
163
 
164
+ # ---------------- UI ----------------
165
  with gr.Blocks() as demo:
166
+ gr.Markdown("## 🤖 SmartManuals-AI (Granite 3.2-2B)")
167
+ with gr.Row():
168
+ question = gr.Textbox(label="Ask your question")
169
+ ask = gr.Button("Ask")
170
+ answer = gr.Textbox(label="Answer", lines=8)
171
+ ask.click(fn=get_answer, inputs=question, outputs=answer)
172
+
173
+ # Embed + Load Model at Startup
 
 
174
  try:
175
  db, embedder = embed_all()
176
+ model_pipe, model_tokenizer = load_model()
177
  except Exception as e:
178
+ print("❌ Startup failure:", e)
179
  db, embedder = None, None
180
+ model_pipe, model_tokenizer = None, None
181
 
 
182
  if __name__ == "__main__":
183
  demo.launch()