Spaces:
Sleeping
Sleeping
Commit ·
aae6d78
1
Parent(s): e80e041
knowledge recognition from attached picture filess
Browse files- core_logic.py +17 -6
- perception_agent.py +109 -0
core_logic.py
CHANGED
|
@@ -79,12 +79,23 @@ def chat_function(message, history):
|
|
| 79 |
user_text = message.get("text", "")
|
| 80 |
files = message.get("files", [])
|
| 81 |
|
| 82 |
-
#
|
| 83 |
context_from_files = ""
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
# TRUNCATE FILE CONTEXT: Max ~3000 tokens (approx 12,000 chars)
|
| 90 |
if len(context_from_files) > 12000:
|
|
@@ -112,7 +123,7 @@ def chat_function(message, history):
|
|
| 112 |
model=model,
|
| 113 |
messages=messages,
|
| 114 |
stream=True,
|
| 115 |
-
temperature=0.
|
| 116 |
#max_tokens=1024 # Limit response size to prevent mid-stream cuts
|
| 117 |
)
|
| 118 |
|
|
|
|
| 79 |
user_text = message.get("text", "")
|
| 80 |
files = message.get("files", [])
|
| 81 |
|
| 82 |
+
# Context Aggregator Buffer for all multi-format assets
|
| 83 |
context_from_files = ""
|
| 84 |
+
|
| 85 |
+
# 1. Process Multimodal and Extended Multi-format Files via Perception Agent
|
| 86 |
+
if files:
|
| 87 |
+
from perception_agent import read_document_file
|
| 88 |
+
yield "◌ _Perception Agent initialized: Ingesting uploaded file assets..._"
|
| 89 |
+
|
| 90 |
+
for f in files:
|
| 91 |
+
# Gradio 6 handles file entries either as dictionaries with a 'path' key or flat strings
|
| 92 |
+
path = f["path"] if isinstance(f, dict) else f
|
| 93 |
+
if path and os.path.exists(path):
|
| 94 |
+
file_content = read_document_file(path)
|
| 95 |
+
context_from_files += file_content
|
| 96 |
+
|
| 97 |
+
yield "◌ _Perception processing complete. Transmitting compiled structures to the Brain..._"
|
| 98 |
+
|
| 99 |
|
| 100 |
# TRUNCATE FILE CONTEXT: Max ~3000 tokens (approx 12,000 chars)
|
| 101 |
if len(context_from_files) > 12000:
|
|
|
|
| 123 |
model=model,
|
| 124 |
messages=messages,
|
| 125 |
stream=True,
|
| 126 |
+
temperature=0.2,
|
| 127 |
#max_tokens=1024 # Limit response size to prevent mid-stream cuts
|
| 128 |
)
|
| 129 |
|
perception_agent.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# ./perception_agent.py
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from docx import Document
|
| 7 |
+
from pypdf import PdfReader # Cleanly leverages your requirements.txt package
|
| 8 |
+
from groq import Groq
|
| 9 |
+
from agent_logging import log_agent_action
|
| 10 |
+
|
| 11 |
+
client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
| 12 |
+
|
| 13 |
+
def read_image_file(file_path):
|
| 14 |
+
"""Uses Groq Vision capability to interpret images (.png, .jpg, .bmp)"""
|
| 15 |
+
import base64
|
| 16 |
+
try:
|
| 17 |
+
log_agent_action("PERCEPTION", f"Encoding image for Vision API: {file_path}")
|
| 18 |
+
with open(file_path, "rb") as image_file:
|
| 19 |
+
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
|
| 20 |
+
|
| 21 |
+
ext = os.path.splitext(file_path)[1].lower().replace(".", "")
|
| 22 |
+
mime_type = f"image/{ext}" if ext != "jpg" else "image/jpeg"
|
| 23 |
+
|
| 24 |
+
response = client.chat.completions.create(
|
| 25 |
+
model="llama-3.2-11b-vision-preview",
|
| 26 |
+
messages=[
|
| 27 |
+
{
|
| 28 |
+
"role": "user",
|
| 29 |
+
"content": [
|
| 30 |
+
{"type": "text", "text": "Analyze this technical image. Extract all code, data tables, structural diagrams, or text precisely."},
|
| 31 |
+
{
|
| 32 |
+
"type": "image_url",
|
| 33 |
+
"image_url": {
|
| 34 |
+
"url": f"data:{mime_type};base64,{encoded_string}"
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
]
|
| 38 |
+
}
|
| 39 |
+
],
|
| 40 |
+
temperature=0.0
|
| 41 |
+
)
|
| 42 |
+
log_agent_action("PERCEPTION_SUCCESS", f"Vision extraction complete for {file_path}")
|
| 43 |
+
return f"\n--- Visual Content Extraction from {os.path.basename(file_path)} ---\n{response.choices[0].message.content}\n"
|
| 44 |
+
except Exception as e:
|
| 45 |
+
log_agent_action("PERCEPTION_ERROR", f"Vision interpretation failed: {str(e)}")
|
| 46 |
+
return f"\n[Vision Error processing image {os.path.basename(file_path)}: {str(e)}]\n"
|
| 47 |
+
|
| 48 |
+
def read_document_file(file_path):
|
| 49 |
+
"""Universal router parsing text, code, spreadsheets, PDFs, and document assets"""
|
| 50 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 51 |
+
filename = os.path.basename(file_path)
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
# 1. Plain Text and Markdown Layouts
|
| 55 |
+
if ext in ['.txt', '.md', '.py', '.json', '.yaml', '.toml', '.css', '.html']:
|
| 56 |
+
log_agent_action("PERCEPTION", f"Reading plaintext structure: {filename}")
|
| 57 |
+
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
|
| 58 |
+
return f"\n--- Content of File: {filename} ---\n{f.read()}\n"
|
| 59 |
+
|
| 60 |
+
# 2. Excel Data Configurations
|
| 61 |
+
elif ext in ['.xlsx', '.xls']:
|
| 62 |
+
log_agent_action("PERCEPTION", f"Parsing Data Spreadsheet: {filename}")
|
| 63 |
+
excel_data = pd.read_excel(file_path, sheet_name=None)
|
| 64 |
+
combined_text = f"\n--- Spreadsheet Matrix Extraction: {filename} ---\n"
|
| 65 |
+
for sheet_name, df in excel_data.items():
|
| 66 |
+
combined_text += f"\nSheet: {sheet_name}\n"
|
| 67 |
+
combined_text += df.to_markdown(index=False) + "\n"
|
| 68 |
+
return combined_text
|
| 69 |
+
|
| 70 |
+
# 3. Microsoft Word Processing
|
| 71 |
+
elif ext == '.docx':
|
| 72 |
+
log_agent_action("PERCEPTION", f"Extracting structural Word paragraphs: {filename}")
|
| 73 |
+
doc = Document(file_path)
|
| 74 |
+
paragraphs = [p.text for p in doc.paragraphs]
|
| 75 |
+
return f"\n--- Document Text Extraction: {filename} ---\n" + "\n".join(paragraphs) + "\n"
|
| 76 |
+
|
| 77 |
+
# 4. NEW ADDITION: Portable Document Format (.pdf) Ingestion
|
| 78 |
+
elif ext == '.pdf':
|
| 79 |
+
log_agent_action("PERCEPTION", f"Initializing pypdf reader pipeline: {filename}")
|
| 80 |
+
reader = PdfReader(file_path)
|
| 81 |
+
pdf_text_buffer = []
|
| 82 |
+
|
| 83 |
+
for index, page in enumerate(reader.pages):
|
| 84 |
+
extracted_page_text = page.extract_text()
|
| 85 |
+
if extracted_page_text:
|
| 86 |
+
pdf_text_buffer.append(f"--- Page {index + 1} ---\n{extracted_page_text}")
|
| 87 |
+
|
| 88 |
+
if not pdf_text_buffer:
|
| 89 |
+
log_agent_action("PERCEPTION_WARN", f"PDF contained no raw text layers (possible raw scan): {filename}")
|
| 90 |
+
return f"\n[System Warning: '{filename}' appears to be an un-OCRed scanned image PDF. Please extract its pages as raw images for CoderG's Vision layer.]\n"
|
| 91 |
+
|
| 92 |
+
log_agent_action("PERCEPTION_SUCCESS", f"Successfully parsed {len(pdf_text_buffer)} pages from {filename}")
|
| 93 |
+
return f"\n--- PDF Document Content Ingestion: {filename} ---\n" + "\n".join(pdf_text_buffer) + "\n"
|
| 94 |
+
|
| 95 |
+
# 5. Image Vector/Raster Formats
|
| 96 |
+
elif ext in ['.png', '.jpg', '.jpeg', '.bmp']:
|
| 97 |
+
return read_image_file(file_path)
|
| 98 |
+
|
| 99 |
+
elif ext == '.doc':
|
| 100 |
+
log_agent_action("PERCEPTION_WARN", f"Legacy format encountered: {filename}")
|
| 101 |
+
return f"\n[System Error: Legacy format '{ext}' detected. Please convert '{filename}' to '.docx' for automated ingestion.]\n"
|
| 102 |
+
|
| 103 |
+
else:
|
| 104 |
+
log_agent_action("PERCEPTION_WARN", f"Unknown asset extension skipped: {filename}")
|
| 105 |
+
return f"\n[System Warning: Unsupported file format '{ext}' for file '{filename}'. Skipping content ingestion.]\n"
|
| 106 |
+
|
| 107 |
+
except Exception as e:
|
| 108 |
+
log_agent_action("PERCEPTION_ERROR", f"Failed parsing {filename}: {str(e)}")
|
| 109 |
+
return f"\n[Error processing document asset {filename}: {str(e)}]\n"
|