Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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
|
| 25 |
try:
|
| 26 |
nltk.data.find("tokenizers/punkt")
|
| 27 |
except LookupError:
|
| 28 |
nltk.download("punkt")
|
| 29 |
|
| 30 |
-
#
|
|
|
|
| 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 |
-
# ----------------
|
| 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
|
| 57 |
-
print("
|
| 58 |
return text.split(". ")
|
| 59 |
|
| 60 |
-
def
|
| 61 |
chunks = []
|
| 62 |
-
current_chunk,
|
| 63 |
|
| 64 |
-
for
|
| 65 |
-
words =
|
| 66 |
-
if
|
| 67 |
chunks.append(" ".join(current_chunk))
|
| 68 |
current_chunk = current_chunk[-overlap:]
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
current_len += len(words)
|
| 73 |
|
| 74 |
if current_chunk:
|
| 75 |
chunks.append(" ".join(current_chunk))
|
| 76 |
-
|
| 77 |
return chunks
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
|
|
|
| 81 |
try:
|
| 82 |
-
doc = fitz.open(
|
| 83 |
for i, page in enumerate(doc):
|
| 84 |
text = page.get_text().strip()
|
| 85 |
if not text:
|
| 86 |
-
|
| 87 |
-
img = Image.open(BytesIO(pix.tobytes("png")))
|
| 88 |
text = pytesseract.image_to_string(img)
|
| 89 |
-
|
| 90 |
except Exception as e:
|
| 91 |
-
print("❌
|
| 92 |
-
return
|
| 93 |
|
| 94 |
-
def extract_docx_text(
|
| 95 |
try:
|
| 96 |
-
|
| 97 |
-
return [(docx_path, 1, text)]
|
| 98 |
except Exception as e:
|
| 99 |
-
print("❌
|
| 100 |
return []
|
| 101 |
|
| 102 |
-
# ----------------
|
| 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 |
-
|
| 115 |
-
|
| 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
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
ids.append(f"{fname}::{page}::{i}")
|
| 133 |
metas.append({"source": fname, "page": page})
|
| 134 |
|
| 135 |
-
if len(
|
| 136 |
-
embs = embedder.encode(
|
| 137 |
-
collection.add(documents=
|
| 138 |
-
|
| 139 |
|
| 140 |
-
if
|
| 141 |
-
embs = embedder.encode(
|
| 142 |
-
collection.add(documents=
|
| 143 |
|
| 144 |
print(f"✅ Embedded {len(ids)} chunks.")
|
| 145 |
return collection, embedder
|
| 146 |
|
| 147 |
-
# ---------------- Model
|
| 148 |
-
def load_model(
|
| 149 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
| 150 |
-
model = AutoModelForCausalLM.from_pretrained(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0 if torch.cuda.is_available() else -1)
|
| 152 |
return pipe, tokenizer
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
| 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 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
"""
|
| 164 |
-
|
| 165 |
-
return
|
| 166 |
-
|
| 167 |
-
|
|
|
|
| 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 |
-
|
| 175 |
-
context
|
| 176 |
-
|
| 177 |
-
answer = query_llm(context, question, pipe, tokenizer)
|
| 178 |
-
return answer
|
| 179 |
except Exception as e:
|
| 180 |
-
|
| 181 |
-
return f"
|
| 182 |
|
| 183 |
-
# ----------------
|
| 184 |
with gr.Blocks() as demo:
|
| 185 |
-
gr.Markdown("
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
# Run background embed on startup
|
| 195 |
try:
|
| 196 |
db, embedder = embed_all()
|
|
|
|
| 197 |
except Exception as e:
|
| 198 |
-
print("❌
|
| 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()
|