Update app.py
Browse files
app.py
CHANGED
|
@@ -10,18 +10,23 @@ import gradio as gr
|
|
| 10 |
from PIL import Image
|
| 11 |
import fitz # PyMuPDF
|
| 12 |
import pytesseract
|
| 13 |
-
|
|
|
|
| 14 |
|
| 15 |
-
|
|
|
|
| 16 |
|
| 17 |
-
#
|
|
|
|
|
|
|
| 18 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 19 |
if not OPENAI_API_KEY:
|
| 20 |
-
raise RuntimeError("OPENAI_API_KEY not found in environment. Add it to Secrets in
|
| 21 |
-
openai.api_key = OPENAI_API_KEY
|
| 22 |
|
| 23 |
-
#
|
| 24 |
-
|
|
|
|
|
|
|
| 25 |
EMBEDDING_MODEL = os.getenv("OPENAI_EMBEDDING_MODEL", "text-embedding-3-small") # optional
|
| 26 |
|
| 27 |
# ----------------------
|
|
@@ -29,9 +34,13 @@ EMBEDDING_MODEL = os.getenv("OPENAI_EMBEDDING_MODEL", "text-embedding-3-small")
|
|
| 29 |
# ----------------------
|
| 30 |
def extract_text_from_pdf(path: str) -> str:
|
| 31 |
"""
|
| 32 |
-
|
| 33 |
"""
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
texts: List[str] = []
|
| 36 |
for i in range(len(doc)):
|
| 37 |
page = doc.load_page(i)
|
|
@@ -54,7 +63,7 @@ def extract_text_from_image(path: str) -> str:
|
|
| 54 |
|
| 55 |
|
| 56 |
# ----------------------
|
| 57 |
-
#
|
| 58 |
# ----------------------
|
| 59 |
def chunk_text(text: str, max_chars: int = 3000) -> List[str]:
|
| 60 |
paragraphs = [p.strip() for p in re.split(r"\n\s*\n", text) if p.strip()]
|
|
@@ -73,24 +82,26 @@ def chunk_text(text: str, max_chars: int = 3000) -> List[str]:
|
|
| 73 |
|
| 74 |
|
| 75 |
# ----------------------
|
| 76 |
-
# LLM
|
| 77 |
# ----------------------
|
| 78 |
def call_gpt5_for_metadata(title: str, short_text: str, top_chunks: List[str]) -> Dict[str, Any]:
|
| 79 |
"""
|
| 80 |
-
|
| 81 |
-
|
| 82 |
"""
|
| 83 |
-
|
| 84 |
-
prompt = (
|
| 85 |
"You are an automated document taxonomy and tagging assistant for enterprise catalogs.\n\n"
|
| 86 |
f"Document title: {title}\n\n"
|
| 87 |
f"Short document text (first ~1000 chars): {short_text}\n\n"
|
| 88 |
"Top content chunks (short):\n"
|
| 89 |
)
|
|
|
|
|
|
|
| 90 |
for i, c in enumerate(top_chunks[:6]):
|
| 91 |
-
|
|
|
|
| 92 |
|
| 93 |
-
|
| 94 |
"Task: Produce a single JSON object (machine parseable) with EXACT keys:\n"
|
| 95 |
"doc_id, title, summary, doc_type, source, tags (array of strings), tag_confidences (map tag->float), "
|
| 96 |
"taxonomy_path (array of strings), extracted_entities (map), raw_url, ingest_timestamp\n\n"
|
|
@@ -106,44 +117,71 @@ def call_gpt5_for_metadata(title: str, short_text: str, top_chunks: List[str]) -
|
|
| 106 |
"OUTPUT: ONLY THE JSON OBJECT. DO NOT PROVIDE ANY ADDITIONAL TEXT.\n"
|
| 107 |
)
|
| 108 |
|
| 109 |
-
|
| 110 |
-
model=LLM_MODEL,
|
| 111 |
-
messages=[{"role": "user", "content": prompt}],
|
| 112 |
-
temperature=0.0,
|
| 113 |
-
max_tokens=1000,
|
| 114 |
-
)
|
| 115 |
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
m = re.search(r"\{[\s\S]*\}$", text)
|
| 120 |
json_text = m.group(0) if m else text
|
| 121 |
|
| 122 |
try:
|
| 123 |
data = json.loads(json_text)
|
| 124 |
except Exception:
|
| 125 |
-
# If parse fails, return an error structure so UI can show the raw output
|
| 126 |
data = {"_parsing_error": True, "raw_output": text}
|
| 127 |
return data
|
| 128 |
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
def save_uploaded_to_tmp(file_obj):
|
| 131 |
"""
|
| 132 |
-
Accepts:
|
| 133 |
-
-
|
| 134 |
-
-
|
| 135 |
-
-
|
| 136 |
-
-
|
| 137 |
-
|
| 138 |
Returns (tmp_path, original_name)
|
| 139 |
"""
|
| 140 |
-
import io
|
| 141 |
-
|
| 142 |
# Case 1: file-like object with .read()
|
| 143 |
if hasattr(file_obj, "read") and callable(getattr(file_obj, "read")):
|
| 144 |
try:
|
| 145 |
content = file_obj.read()
|
| 146 |
-
#
|
| 147 |
if isinstance(content, str):
|
| 148 |
content = content.encode("utf-8")
|
| 149 |
name = getattr(file_obj, "name", "uploaded_file")
|
|
@@ -152,12 +190,10 @@ def save_uploaded_to_tmp(file_obj):
|
|
| 152 |
tmp.write(content)
|
| 153 |
return tmp.name, os.path.basename(name)
|
| 154 |
except Exception:
|
| 155 |
-
# fallthrough to other handlers
|
| 156 |
pass
|
| 157 |
|
| 158 |
-
# Case 2:
|
| 159 |
if isinstance(file_obj, dict):
|
| 160 |
-
# some versions: {"name": "foo.pdf", "data": b'...'}
|
| 161 |
if "data" in file_obj and "name" in file_obj:
|
| 162 |
data = file_obj["data"]
|
| 163 |
if isinstance(data, str):
|
|
@@ -170,10 +206,8 @@ def save_uploaded_to_tmp(file_obj):
|
|
| 170 |
|
| 171 |
# Case 3: file_obj is a path string
|
| 172 |
if isinstance(file_obj, str):
|
| 173 |
-
# if it's an existing path, just return it
|
| 174 |
if os.path.exists(file_obj):
|
| 175 |
return file_obj, os.path.basename(file_obj)
|
| 176 |
-
# sometimes gradio passes a NamedString that can be opened as a path -- try to open it
|
| 177 |
try:
|
| 178 |
with open(file_obj, "rb") as f:
|
| 179 |
data = f.read()
|
|
@@ -184,7 +218,7 @@ def save_uploaded_to_tmp(file_obj):
|
|
| 184 |
except Exception:
|
| 185 |
pass
|
| 186 |
|
| 187 |
-
# Case 4:
|
| 188 |
name = getattr(file_obj, "name", None)
|
| 189 |
if name and isinstance(name, str):
|
| 190 |
try:
|
|
@@ -197,25 +231,20 @@ def save_uploaded_to_tmp(file_obj):
|
|
| 197 |
except Exception:
|
| 198 |
pass
|
| 199 |
|
| 200 |
-
|
| 201 |
-
raise ValueError(f"Unsupported uploaded file object type: {type(file_obj)}. Value: {str(file_obj)[:200]}")
|
| 202 |
|
| 203 |
|
| 204 |
-
# ----------------------
|
| 205 |
-
# Main processing function
|
| 206 |
-
# ----------------------
|
| 207 |
-
# Updated process_file using the helper above
|
| 208 |
def process_file(file_obj) -> Dict[str, Any]:
|
| 209 |
"""
|
| 210 |
-
|
| 211 |
-
Returns metadata dict
|
| 212 |
"""
|
| 213 |
try:
|
| 214 |
tmp_path, orig_name = save_uploaded_to_tmp(file_obj)
|
| 215 |
except Exception as e:
|
| 216 |
return {"error": f"Failed to save uploaded file: {e}"}
|
| 217 |
|
| 218 |
-
#
|
| 219 |
try:
|
| 220 |
if orig_name.lower().endswith(".pdf"):
|
| 221 |
extracted_text = extract_text_from_pdf(tmp_path)
|
|
@@ -234,14 +263,16 @@ def process_file(file_obj) -> Dict[str, Any]:
|
|
| 234 |
|
| 235 |
short_text = (extracted_text[:1000] + "...") if len(extracted_text) > 1000 else extracted_text
|
| 236 |
|
|
|
|
| 237 |
metadata = call_gpt5_for_metadata(orig_name, short_text, top_chunks)
|
| 238 |
|
|
|
|
|
|
|
|
|
|
| 239 |
if metadata.get("_parsing_error"):
|
| 240 |
-
return {
|
| 241 |
-
"error": "LLM output parsing failed. See raw_output.",
|
| 242 |
-
"raw_output": metadata.get("raw_output")
|
| 243 |
-
}
|
| 244 |
|
|
|
|
| 245 |
now = datetime.datetime.now(datetime.timezone.utc).astimezone().isoformat()
|
| 246 |
metadata.setdefault("doc_id", os.path.splitext(orig_name)[0])
|
| 247 |
metadata.setdefault("title", orig_name)
|
|
@@ -271,23 +302,20 @@ with gr.Blocks(title="DocClassify — Gradio GPT-5 Taxonomy & Tagging") as demo:
|
|
| 271 |
try:
|
| 272 |
result = process_file(file_obj)
|
| 273 |
except Exception as e:
|
| 274 |
-
|
| 275 |
-
return gr.update(value={}), gr.update(value="Failed: " + str(e)), None
|
| 276 |
|
| 277 |
if result.get("error"):
|
| 278 |
-
|
| 279 |
-
# if raw_output provided, show under JSON
|
| 280 |
-
return gr.update(value={"error": result.get("error"), "raw_output": result.get("raw_output", "")}), gr.update(value=status.value), None
|
| 281 |
|
| 282 |
-
status.value = "Done"
|
| 283 |
# create a temp json file for download
|
| 284 |
tmpf = tempfile.NamedTemporaryFile(delete=False, suffix=".json")
|
| 285 |
with open(tmpf.name, "w", encoding="utf8") as f:
|
| 286 |
json.dump(result, f, indent=2, ensure_ascii=False)
|
| 287 |
-
|
| 288 |
return gr.update(value=result), gr.update(value="Done"), tmpf.name
|
| 289 |
|
| 290 |
run_button.click(on_process, inputs=[uploader], outputs=[output_json, status, download_button])
|
| 291 |
|
|
|
|
| 292 |
if __name__ == "__main__":
|
| 293 |
demo.launch()
|
|
|
|
| 10 |
from PIL import Image
|
| 11 |
import fitz # PyMuPDF
|
| 12 |
import pytesseract
|
| 13 |
+
# pdf2image is optional here, we used PyMuPDF for PDF -> image rendering fallback
|
| 14 |
+
# from pdf2image import convert_from_path
|
| 15 |
|
| 16 |
+
# OpenAI new client
|
| 17 |
+
from openai import OpenAI
|
| 18 |
|
| 19 |
+
# -----------------------
|
| 20 |
+
# Configuration / Client
|
| 21 |
+
# -----------------------
|
| 22 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 23 |
if not OPENAI_API_KEY:
|
| 24 |
+
raise RuntimeError("OPENAI_API_KEY not found in environment. Add it to Secrets in HF Space or set env var.")
|
|
|
|
| 25 |
|
| 26 |
+
# Create the new OpenAI client (new API surface for openai>=1.0.0)
|
| 27 |
+
client = OpenAI(api_key=OPENAI_API_KEY)
|
| 28 |
+
|
| 29 |
+
LLM_MODEL = os.getenv("OPENAI_MODEL", "gpt-5") # change to your available model id if needed
|
| 30 |
EMBEDDING_MODEL = os.getenv("OPENAI_EMBEDDING_MODEL", "text-embedding-3-small") # optional
|
| 31 |
|
| 32 |
# ----------------------
|
|
|
|
| 34 |
# ----------------------
|
| 35 |
def extract_text_from_pdf(path: str) -> str:
|
| 36 |
"""
|
| 37 |
+
Extract text using PyMuPDF. If a page has no extractable text, render to image and OCR with pytesseract.
|
| 38 |
"""
|
| 39 |
+
try:
|
| 40 |
+
doc = fitz.open(path)
|
| 41 |
+
except Exception as e:
|
| 42 |
+
raise RuntimeError(f"Failed to open PDF: {e}")
|
| 43 |
+
|
| 44 |
texts: List[str] = []
|
| 45 |
for i in range(len(doc)):
|
| 46 |
page = doc.load_page(i)
|
|
|
|
| 63 |
|
| 64 |
|
| 65 |
# ----------------------
|
| 66 |
+
# Chunker
|
| 67 |
# ----------------------
|
| 68 |
def chunk_text(text: str, max_chars: int = 3000) -> List[str]:
|
| 69 |
paragraphs = [p.strip() for p in re.split(r"\n\s*\n", text) if p.strip()]
|
|
|
|
| 82 |
|
| 83 |
|
| 84 |
# ----------------------
|
| 85 |
+
# OpenAI LLM & embeddings helpers (new client surface)
|
| 86 |
# ----------------------
|
| 87 |
def call_gpt5_for_metadata(title: str, short_text: str, top_chunks: List[str]) -> Dict[str, Any]:
|
| 88 |
"""
|
| 89 |
+
Prompt GPT-5 to return a single JSON object matching the schema the user specified.
|
| 90 |
+
We ask the model to return JSON only. We do a best-effort parse and return structured dict.
|
| 91 |
"""
|
| 92 |
+
prompt_intro = (
|
|
|
|
| 93 |
"You are an automated document taxonomy and tagging assistant for enterprise catalogs.\n\n"
|
| 94 |
f"Document title: {title}\n\n"
|
| 95 |
f"Short document text (first ~1000 chars): {short_text}\n\n"
|
| 96 |
"Top content chunks (short):\n"
|
| 97 |
)
|
| 98 |
+
|
| 99 |
+
prompt_chunks = ""
|
| 100 |
for i, c in enumerate(top_chunks[:6]):
|
| 101 |
+
chunk_text_clean = c[:800].replace("\n", " ")
|
| 102 |
+
prompt_chunks += f"CHUNK_{i+1}: {chunk_text_clean}\n\n"
|
| 103 |
|
| 104 |
+
prompt_end = (
|
| 105 |
"Task: Produce a single JSON object (machine parseable) with EXACT keys:\n"
|
| 106 |
"doc_id, title, summary, doc_type, source, tags (array of strings), tag_confidences (map tag->float), "
|
| 107 |
"taxonomy_path (array of strings), extracted_entities (map), raw_url, ingest_timestamp\n\n"
|
|
|
|
| 117 |
"OUTPUT: ONLY THE JSON OBJECT. DO NOT PROVIDE ANY ADDITIONAL TEXT.\n"
|
| 118 |
)
|
| 119 |
|
| 120 |
+
prompt = prompt_intro + prompt_chunks + prompt_end
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
+
# Call using new client
|
| 123 |
+
try:
|
| 124 |
+
resp = client.chat.completions.create(
|
| 125 |
+
model=LLM_MODEL,
|
| 126 |
+
messages=[{"role": "user", "content": prompt}],
|
| 127 |
+
temperature=0.0,
|
| 128 |
+
max_tokens=1000,
|
| 129 |
+
)
|
| 130 |
+
except Exception as e:
|
| 131 |
+
return {"_api_error": True, "error": f"OpenAI API call failed: {e}"}
|
| 132 |
|
| 133 |
+
# Extract text robustly
|
| 134 |
+
try:
|
| 135 |
+
text = resp.choices[0].message["content"].strip()
|
| 136 |
+
except Exception:
|
| 137 |
+
# fallback attribute access if response uses attribute objects
|
| 138 |
+
try:
|
| 139 |
+
text = resp.choices[0].message.content.strip()
|
| 140 |
+
except Exception:
|
| 141 |
+
text = str(resp)
|
| 142 |
+
|
| 143 |
+
# Try to extract JSON block
|
| 144 |
m = re.search(r"\{[\s\S]*\}$", text)
|
| 145 |
json_text = m.group(0) if m else text
|
| 146 |
|
| 147 |
try:
|
| 148 |
data = json.loads(json_text)
|
| 149 |
except Exception:
|
|
|
|
| 150 |
data = {"_parsing_error": True, "raw_output": text}
|
| 151 |
return data
|
| 152 |
|
| 153 |
+
|
| 154 |
+
def get_embeddings_for_chunks(chunks: List[str], model: str = EMBEDDING_MODEL) -> List[List[float]]:
|
| 155 |
+
try:
|
| 156 |
+
resp = client.embeddings.create(model=model, input=chunks)
|
| 157 |
+
except Exception as e:
|
| 158 |
+
raise RuntimeError(f"Embeddings API call failed: {e}")
|
| 159 |
+
|
| 160 |
+
# resp.data is an array of objects containing .embedding
|
| 161 |
+
try:
|
| 162 |
+
return [item.embedding for item in resp.data]
|
| 163 |
+
except Exception:
|
| 164 |
+
# fallback to dict-like access
|
| 165 |
+
return [item["embedding"] for item in resp.data]
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# ----------------------
|
| 169 |
+
# Robust uploader helper + processing
|
| 170 |
+
# ----------------------
|
| 171 |
def save_uploaded_to_tmp(file_obj):
|
| 172 |
"""
|
| 173 |
+
Accepts multiple upload types commonly returned by gradio:
|
| 174 |
+
- file-like object with .read()
|
| 175 |
+
- dict-like {"name": "...", "data": b'...'}
|
| 176 |
+
- path string (existing file path)
|
| 177 |
+
- objects with a .name attribute pointing to a saved path (NamedString)
|
|
|
|
| 178 |
Returns (tmp_path, original_name)
|
| 179 |
"""
|
|
|
|
|
|
|
| 180 |
# Case 1: file-like object with .read()
|
| 181 |
if hasattr(file_obj, "read") and callable(getattr(file_obj, "read")):
|
| 182 |
try:
|
| 183 |
content = file_obj.read()
|
| 184 |
+
# sometimes content may be str
|
| 185 |
if isinstance(content, str):
|
| 186 |
content = content.encode("utf-8")
|
| 187 |
name = getattr(file_obj, "name", "uploaded_file")
|
|
|
|
| 190 |
tmp.write(content)
|
| 191 |
return tmp.name, os.path.basename(name)
|
| 192 |
except Exception:
|
|
|
|
| 193 |
pass
|
| 194 |
|
| 195 |
+
# Case 2: dict-like returned by some gradio versions
|
| 196 |
if isinstance(file_obj, dict):
|
|
|
|
| 197 |
if "data" in file_obj and "name" in file_obj:
|
| 198 |
data = file_obj["data"]
|
| 199 |
if isinstance(data, str):
|
|
|
|
| 206 |
|
| 207 |
# Case 3: file_obj is a path string
|
| 208 |
if isinstance(file_obj, str):
|
|
|
|
| 209 |
if os.path.exists(file_obj):
|
| 210 |
return file_obj, os.path.basename(file_obj)
|
|
|
|
| 211 |
try:
|
| 212 |
with open(file_obj, "rb") as f:
|
| 213 |
data = f.read()
|
|
|
|
| 218 |
except Exception:
|
| 219 |
pass
|
| 220 |
|
| 221 |
+
# Case 4: object has .name attribute referencing a real path (NamedString)
|
| 222 |
name = getattr(file_obj, "name", None)
|
| 223 |
if name and isinstance(name, str):
|
| 224 |
try:
|
|
|
|
| 231 |
except Exception:
|
| 232 |
pass
|
| 233 |
|
| 234 |
+
raise ValueError(f"Unsupported uploaded file object type: {type(file_obj)}. Value repr: {repr(file_obj)[:400]}")
|
|
|
|
| 235 |
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
def process_file(file_obj) -> Dict[str, Any]:
|
| 238 |
"""
|
| 239 |
+
Orchestrates saving uploaded file, extracting text, chunking, calling LLM and post-processing.
|
| 240 |
+
Returns: metadata dict or {"error": "..."} on failure.
|
| 241 |
"""
|
| 242 |
try:
|
| 243 |
tmp_path, orig_name = save_uploaded_to_tmp(file_obj)
|
| 244 |
except Exception as e:
|
| 245 |
return {"error": f"Failed to save uploaded file: {e}"}
|
| 246 |
|
| 247 |
+
# Extract text
|
| 248 |
try:
|
| 249 |
if orig_name.lower().endswith(".pdf"):
|
| 250 |
extracted_text = extract_text_from_pdf(tmp_path)
|
|
|
|
| 263 |
|
| 264 |
short_text = (extracted_text[:1000] + "...") if len(extracted_text) > 1000 else extracted_text
|
| 265 |
|
| 266 |
+
# Call LLM to get JSON metadata
|
| 267 |
metadata = call_gpt5_for_metadata(orig_name, short_text, top_chunks)
|
| 268 |
|
| 269 |
+
if metadata.get("_api_error"):
|
| 270 |
+
return {"error": metadata.get("error")}
|
| 271 |
+
|
| 272 |
if metadata.get("_parsing_error"):
|
| 273 |
+
return {"error": "LLM output parsing failed. See raw_output.", "raw_output": metadata.get("raw_output")}
|
|
|
|
|
|
|
|
|
|
| 274 |
|
| 275 |
+
# Ensure required keys and add ingestion timestamp if missing
|
| 276 |
now = datetime.datetime.now(datetime.timezone.utc).astimezone().isoformat()
|
| 277 |
metadata.setdefault("doc_id", os.path.splitext(orig_name)[0])
|
| 278 |
metadata.setdefault("title", orig_name)
|
|
|
|
| 302 |
try:
|
| 303 |
result = process_file(file_obj)
|
| 304 |
except Exception as e:
|
| 305 |
+
return gr.update(value={}), gr.update(value=f"Failed: {e}"), None
|
|
|
|
| 306 |
|
| 307 |
if result.get("error"):
|
| 308 |
+
return gr.update(value={"error": result.get("error"), "raw_output": result.get("raw_output", "")}), gr.update(value=f"Error: {result.get('error')}"), None
|
|
|
|
|
|
|
| 309 |
|
|
|
|
| 310 |
# create a temp json file for download
|
| 311 |
tmpf = tempfile.NamedTemporaryFile(delete=False, suffix=".json")
|
| 312 |
with open(tmpf.name, "w", encoding="utf8") as f:
|
| 313 |
json.dump(result, f, indent=2, ensure_ascii=False)
|
| 314 |
+
|
| 315 |
return gr.update(value=result), gr.update(value="Done"), tmpf.name
|
| 316 |
|
| 317 |
run_button.click(on_process, inputs=[uploader], outputs=[output_json, status, download_button])
|
| 318 |
|
| 319 |
+
# Launch
|
| 320 |
if __name__ == "__main__":
|
| 321 |
demo.launch()
|