Spaces:
Paused

miracle / core /vision.py
dushyantsingh0
intial commits
eefcb41
Raw History Blame Contribute Delete
4.39 kB
import re
import asyncio
import base64
import os
from uuid import UUID
from typing import List, Dict, Any, Optional
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from models.attachment import Attachment
from core.logging import get_logger
logger = get_logger(__name__)
# Pattern for Markdown images: ![alt](url_or_id)
IMAGE_PATTERN = re.compile(r'!\[.*?\]\((.*?)\)')
async def resolve_image(db: AsyncSession, workspace_id: UUID, identifier: str) -> Optional[Dict[str, Any]]:
"""Resolves a Markdown identifier (URL or UUID) to a Base64 data URI or public URL."""
# 1. Direct Web URLs
if identifier.startswith(("http://", "https://")):
return {
"type": "image_url",
"image_url": {"url": identifier, "detail": "low"}
}
# 2. Potential Attachment Reference (UUID)
try:
# Check if the identifier is a UUID or contains a UUID in a known path structure
# (e.g., /api/v1/tickets/attachments/UUID/download)
potential_uuid = identifier
if "/" in identifier:
parts = identifier.strip("/").split("/")
if "download" in parts:
potential_uuid = parts[parts.index("download") - 1]
else:
potential_uuid = parts[-1]
attachment_id = UUID(potential_uuid)
stmt = select(Attachment).where(
Attachment.id == attachment_id,
Attachment.workspace_id == workspace_id,
Attachment.deleted_at.is_(None)
)
res = await db.execute(stmt)
attachment = res.scalar_one_or_none()
if attachment:
from core.storage import get_storage_provider
storage = get_storage_provider()
if attachment.storage_backend == "s3":
url = await storage.get_url(attachment.storage_path)
return {
"type": "image_url",
"image_url": {"url": url, "detail": "auto"}
}
# Local fallback: Only process if it's an actual image and under memory safety limit
if not attachment.content_type or not attachment.content_type.startswith("image/"):
logger.warning(f"Vision: Skipping non-image attachment {attachment.id} (Type: {attachment.content_type})")
return None
# MEMORY SAFETY GATE: Skip base64 conversion for images > 2MB
MAX_VISION_SIZE = 2 * 1024 * 1024
if attachment.file_size and attachment.file_size > MAX_VISION_SIZE:
logger.warning(f"Vision: Skipping large image {attachment.id} ({attachment.file_size} bytes) to prevent OOM.")
return None
local_path = storage.get_local_path(attachment.storage_path)
if os.path.exists(local_path):
def _read_and_encode():
with open(local_path, "rb") as f:
return base64.b64encode(f.read()).decode("utf-8")
img_data = await asyncio.to_thread(_read_and_encode)
return {
"type": "image_url",
"image_url": {
"url": f"data:{attachment.content_type};base64,{img_data}",
"detail": "auto"
}
}
except (ValueError, IndexError):
# Not a valid UUID or recognizable attachment link
pass
return None
async def extract_visual_context(db: AsyncSession, workspace_id: UUID, text: str, limit: int = 5) -> List[Dict[str, Any]]:
"""
Parses markdown text for images and resolves them into a format compatible with
OpenAI-style multimodal message payloads.
"""
if not text:
return []
matches = IMAGE_PATTERN.findall(text)
if not matches:
return []
# CONCURRENCY OPTIMIZATION: Resolve all images in parallel
tasks = [resolve_image(db, workspace_id, identifier.strip()) for identifier in matches[:limit]]
results = await asyncio.gather(*tasks)
images = [r for r in results if r]
if images:
logger.info(f"Vision: Resolved {len(images)} images for multimodal context from workspace {workspace_id}")
return images