Spaces:
Paused

File size: 3,541 Bytes
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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
            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