Spaces:
Sleeping
Sleeping
Commit
·
830acbf
1
Parent(s):
331c413
Upd summariser
Browse files- memory/memory.py +1 -1
- models/__pycache__/__init__.cpython-311.pyc +0 -0
- models/__pycache__/llama.cpython-311.pyc +0 -0
- models/__pycache__/summarizer.cpython-311.pyc +0 -0
- models/summarizer.py +16 -16
- utils/symbipredict_2022.csv +0 -0
- utils/vlm.py +0 -54
memory/memory.py
CHANGED
|
@@ -7,7 +7,7 @@ import faiss
|
|
| 7 |
from sentence_transformers import SentenceTransformer
|
| 8 |
from google import genai # must be configured in app.py and imported globally
|
| 9 |
import logging
|
| 10 |
-
from models.summarizer import
|
| 11 |
|
| 12 |
_LLM_SMALL = "gemini-2.5-flash-lite-preview-06-17"
|
| 13 |
# Load embedding model
|
|
|
|
| 7 |
from sentence_transformers import SentenceTransformer
|
| 8 |
from google import genai # must be configured in app.py and imported globally
|
| 9 |
import logging
|
| 10 |
+
from models.summarizer import summarizer
|
| 11 |
|
| 12 |
_LLM_SMALL = "gemini-2.5-flash-lite-preview-06-17"
|
| 13 |
# Load embedding model
|
models/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (351 Bytes). View file
|
|
|
models/__pycache__/llama.cpython-311.pyc
ADDED
|
Binary file (6.73 kB). View file
|
|
|
models/__pycache__/summarizer.cpython-311.pyc
ADDED
|
Binary file (10.5 kB). View file
|
|
|
models/summarizer.py
CHANGED
|
@@ -39,21 +39,21 @@ class TextSummarizer:
|
|
| 39 |
return text.strip()
|
| 40 |
|
| 41 |
def extract_key_phrases(self, text: str) -> List[str]:
|
| 42 |
-
"""Extract key
|
| 43 |
if not text:
|
| 44 |
return []
|
| 45 |
|
| 46 |
-
#
|
| 47 |
-
|
| 48 |
-
r'\b(?:
|
| 49 |
-
r'\b(?:
|
| 50 |
-
r'\b(?:
|
| 51 |
-
r'\b(?:
|
| 52 |
-
r'\b(?:
|
| 53 |
]
|
| 54 |
|
| 55 |
key_phrases = []
|
| 56 |
-
for pattern in
|
| 57 |
matches = re.findall(pattern, text, re.IGNORECASE)
|
| 58 |
key_phrases.extend(matches)
|
| 59 |
|
|
@@ -70,10 +70,10 @@ class TextSummarizer:
|
|
| 70 |
|
| 71 |
# Extract key phrases for context
|
| 72 |
key_phrases = self.extract_key_phrases(cleaned_text)
|
| 73 |
-
key_phrases_str = ", ".join(key_phrases[:5]) if key_phrases else "
|
| 74 |
|
| 75 |
# Create optimized prompt
|
| 76 |
-
prompt = f"""Summarize this
|
| 77 |
|
| 78 |
Key terms: {key_phrases_str}
|
| 79 |
|
|
@@ -110,7 +110,7 @@ Summary:"""
|
|
| 110 |
|
| 111 |
# Short, strict prompt to avoid verbosity; instruct to output NOTHING if irrelevant
|
| 112 |
prompt = (
|
| 113 |
-
f"You extract only
|
| 114 |
f"Respond with a concise bullet list (<= {max_length} chars total). "
|
| 115 |
"If the content is irrelevant, respond with EXACTLY: NONE.\n\n"
|
| 116 |
f"Content: {cleaned_text[:1600]}\n\nRelevant facts:"
|
|
@@ -138,12 +138,12 @@ Summary:"""
|
|
| 138 |
url_mapping[doc_id] = doc['url']
|
| 139 |
|
| 140 |
# Create focused summary for each document
|
| 141 |
-
summary_prompt = f"""Summarize this
|
| 142 |
|
| 143 |
Document: {doc['title']}
|
| 144 |
Content: {doc['content'][:800]}
|
| 145 |
|
| 146 |
-
Key
|
| 147 |
|
| 148 |
summary = self.llama_client._call_llama(summary_prompt)
|
| 149 |
summary = self.clean_text(summary)
|
|
@@ -165,11 +165,11 @@ Key medical information:"""
|
|
| 165 |
|
| 166 |
cleaned_chunk = self.clean_text(chunk)
|
| 167 |
|
| 168 |
-
prompt = f"""Summarize this
|
| 169 |
|
| 170 |
Conversation: {cleaned_chunk[:1000]}
|
| 171 |
|
| 172 |
-
|
| 173 |
|
| 174 |
summary = self.llama_client._call_llama(prompt)
|
| 175 |
return self.clean_text(summary)
|
|
|
|
| 39 |
return text.strip()
|
| 40 |
|
| 41 |
def extract_key_phrases(self, text: str) -> List[str]:
|
| 42 |
+
"""Extract key cooking phrases and terms"""
|
| 43 |
if not text:
|
| 44 |
return []
|
| 45 |
|
| 46 |
+
# Cooking term patterns
|
| 47 |
+
cooking_patterns = [
|
| 48 |
+
r'\b(?:recipe|ingredients?|cooking|baking|roasting|grilling|frying|boiling|steaming)\b',
|
| 49 |
+
r'\b(?:chef|cook|kitchen|cuisine|meal|dish|food|taste|flavor)\b',
|
| 50 |
+
r'\b(?:temperature|timing|preparation|technique|method|seasoning|spices?|herbs?)\b',
|
| 51 |
+
r'\b(?:oven|stovetop|grill|pan|pot|skillet|knife|cutting|chopping)\b',
|
| 52 |
+
r'\b(?:sauce|marinade|dressing|garnish|presentation|serving)\b'
|
| 53 |
]
|
| 54 |
|
| 55 |
key_phrases = []
|
| 56 |
+
for pattern in cooking_patterns:
|
| 57 |
matches = re.findall(pattern, text, re.IGNORECASE)
|
| 58 |
key_phrases.extend(matches)
|
| 59 |
|
|
|
|
| 70 |
|
| 71 |
# Extract key phrases for context
|
| 72 |
key_phrases = self.extract_key_phrases(cleaned_text)
|
| 73 |
+
key_phrases_str = ", ".join(key_phrases[:5]) if key_phrases else "cooking information"
|
| 74 |
|
| 75 |
# Create optimized prompt
|
| 76 |
+
prompt = f"""Summarize this cooking text in {max_length} characters or less. Focus only on key cooking facts, recipes, techniques, and ingredients. Do not include greetings, confirmations, or conversational elements.
|
| 77 |
|
| 78 |
Key terms: {key_phrases_str}
|
| 79 |
|
|
|
|
| 110 |
|
| 111 |
# Short, strict prompt to avoid verbosity; instruct to output NOTHING if irrelevant
|
| 112 |
prompt = (
|
| 113 |
+
f"You extract only cooking relevant facts that help answer: '{query}'. "
|
| 114 |
f"Respond with a concise bullet list (<= {max_length} chars total). "
|
| 115 |
"If the content is irrelevant, respond with EXACTLY: NONE.\n\n"
|
| 116 |
f"Content: {cleaned_text[:1600]}\n\nRelevant facts:"
|
|
|
|
| 138 |
url_mapping[doc_id] = doc['url']
|
| 139 |
|
| 140 |
# Create focused summary for each document
|
| 141 |
+
summary_prompt = f"""Summarize this cooking document in 2-3 sentences, focusing on information relevant to: "{user_query}"
|
| 142 |
|
| 143 |
Document: {doc['title']}
|
| 144 |
Content: {doc['content'][:800]}
|
| 145 |
|
| 146 |
+
Key cooking information:"""
|
| 147 |
|
| 148 |
summary = self.llama_client._call_llama(summary_prompt)
|
| 149 |
summary = self.clean_text(summary)
|
|
|
|
| 165 |
|
| 166 |
cleaned_chunk = self.clean_text(chunk)
|
| 167 |
|
| 168 |
+
prompt = f"""Summarize this cooking conversation in 1-2 sentences. Focus only on cooking facts, recipes, techniques, or ingredients discussed. Remove greetings and conversational elements.
|
| 169 |
|
| 170 |
Conversation: {cleaned_chunk[:1000]}
|
| 171 |
|
| 172 |
+
Cooking summary:"""
|
| 173 |
|
| 174 |
summary = self.llama_client._call_llama(prompt)
|
| 175 |
return self.clean_text(summary)
|
utils/symbipredict_2022.csv
DELETED
|
The diff for this file is too large to render.
See raw diff
|
|
|
utils/vlm.py
DELETED
|
@@ -1,54 +0,0 @@
|
|
| 1 |
-
import os, logging, traceback, json, base64
|
| 2 |
-
from io import BytesIO
|
| 3 |
-
from PIL import Image
|
| 4 |
-
from .translation import translate_query
|
| 5 |
-
from gradio_client import Client, handle_file
|
| 6 |
-
import tempfile
|
| 7 |
-
|
| 8 |
-
logger = logging.getLogger("vlm-agent")
|
| 9 |
-
logging.basicConfig(level=logging.INFO, format="%(asctime)s — %(name)s — %(levelname)s — %(message)s", force=True)
|
| 10 |
-
|
| 11 |
-
# ✅ Load Gradio client once
|
| 12 |
-
gr_client = None
|
| 13 |
-
def load_gradio_client():
|
| 14 |
-
global gr_client
|
| 15 |
-
if gr_client is None:
|
| 16 |
-
logger.info("[VLM] ⏳ Connecting to MedGEMMA Gradio Space...")
|
| 17 |
-
gr_client = Client("warshanks/medgemma-4b-it")
|
| 18 |
-
logger.info("[VLM] Gradio MedGEMMA client ready.")
|
| 19 |
-
return gr_client
|
| 20 |
-
|
| 21 |
-
def process_medical_image(base64_image: str, prompt: str = None, lang: str = "EN") -> str:
|
| 22 |
-
if not prompt:
|
| 23 |
-
prompt = "Describe and investigate any clinical findings from this medical image."
|
| 24 |
-
elif lang.upper() in {"VI", "ZH"}:
|
| 25 |
-
prompt = translate_query(prompt, lang.lower())
|
| 26 |
-
|
| 27 |
-
try:
|
| 28 |
-
# 1️⃣ Decode base64 image to temp file
|
| 29 |
-
image_data = base64.b64decode(base64_image)
|
| 30 |
-
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
| 31 |
-
tmp.write(image_data)
|
| 32 |
-
tmp.flush()
|
| 33 |
-
image_path = tmp.name
|
| 34 |
-
|
| 35 |
-
# 2️⃣ Send to Gradio MedGEMMA
|
| 36 |
-
client = load_gradio_client()
|
| 37 |
-
logger.info(f"[VLM] Sending prompt: {prompt}")
|
| 38 |
-
result = client.predict(
|
| 39 |
-
message={"text": prompt, "files": [handle_file(image_path)]},
|
| 40 |
-
param_2 = "You analyze medical images and report abnormalities, diseases with clear diagnostic insight.",
|
| 41 |
-
param_3=2048,
|
| 42 |
-
api_name="/chat"
|
| 43 |
-
)
|
| 44 |
-
if isinstance(result, str):
|
| 45 |
-
logger.info(f"[VLM] ✅ Response: {result}")
|
| 46 |
-
return result.strip()
|
| 47 |
-
else:
|
| 48 |
-
logger.warning(f"[VLM] ⚠️ Unexpected result type: {type(result)} — {result}")
|
| 49 |
-
return str(result)
|
| 50 |
-
|
| 51 |
-
except Exception as e:
|
| 52 |
-
logger.error(f"[VLM] ❌ Exception: {e}")
|
| 53 |
-
logger.error(f"[VLM] 🔍 Traceback:\n{traceback.format_exc()}")
|
| 54 |
-
return f"[VLM] ⚠️ Failed to process image: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|