import re 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 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 local_path = storage.get_local_path(attachment.storage_path) if os.path.exists(local_path): with open(local_path, "rb") as f: img_data = base64.b64encode(f.read()).decode("utf-8") 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) images = [] for identifier in matches: if len(images) >= limit: break resolved = await resolve_image(db, workspace_id, identifier.strip()) if resolved: images.append(resolved) if images: logger.info(f"Vision: Resolved {len(images)} images for multimodal context from workspace {workspace_id}") return images