Spaces:
Sleeping

File size: 4,994 Bytes
ebf20cf
 
 
f73c3e2
ebf20cf
 
 
 
 
f73c3e2
ebf20cf
 
 
 
f73c3e2
 
 
ebf20cf
f73c3e2
 
ebf20cf
f73c3e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebf20cf
 
 
f73c3e2
 
 
 
ebf20cf
f73c3e2
ebf20cf
 
f73c3e2
 
ebf20cf
 
f73c3e2
ebf20cf
f73c3e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
"""
Regelexperte – Multimodale Bildanalyse
=======================================
Analysiert Fotos von Spielzuständen, Karten oder Effekten
und beantwortet Regelfragen via Claude multimodal + RAG.

Verwendung:
    from src.expert.vision import answer_from_image
    result = answer_from_image(
        image_data=base64_bytes,
        question="Darf ich jetzt diese Aktion ausführen?",
        game="stalker"
    )
"""
import base64
import os
import re

import anthropic
from dotenv import load_dotenv

from src.rag.vectorstore import retrieve

load_dotenv()

PROMPT_PATH = os.path.join(os.path.dirname(__file__), "..", "..", "prompts", "expert", "vision.md")
MODEL = "claude-sonnet-4-20250514"

GAME_DISPLAY_NAMES = {
    "stalker": "S.T.A.L.K.E.R. The Board Game",
}

_client = None


def _get_client() -> anthropic.Anthropic:
    global _client
    if _client is None:
        _client = anthropic.Anthropic()
    return _client


def _load_prompt() -> str:
    with open(PROMPT_PATH, "r") as f:
        return f.read()


def _format_chunks(chunks: list[dict]) -> str:
    parts = []
    for i, chunk in enumerate(chunks, 1):
        source_label = chunk["source"].replace("_", " ")
        parts.append(
            f"### Quelle {i}: {source_label}, Seite {chunk['page']} "
            f"({chunk['section']})\n\n{chunk['text']}"
        )
    return "\n\n---\n\n".join(parts)


def _extract_sources(chunks: list[dict]) -> list[str]:
    seen = set()
    sources = []
    for c in chunks:
        label = f"{c['source'].replace('_', ' ')} S.{c['page']}"
        if label not in seen:
            seen.add(label)
            sources.append(label)
    return sources


def answer_from_image(
    image_data: bytes,
    question: str,
    game: str,
    media_type: str = "image/jpeg",
    k: int = 6,
) -> dict:
    """
    Analysiert ein Spielzustand-Foto und beantwortet die Regelfrage.

    Zweistufig:
    1. Claude beschreibt den Spielzustand auf dem Bild
    2. Beschreibung + Frage werden als RAG-Query genutzt, dann kombinierte Antwort

    Args:
        image_data: Bilddaten als bytes (raw, nicht base64)
        question: Die Regelfrage des Spielers
        game: Spielname
        media_type: MIME-Type des Bildes
        k: Anzahl RAG-Chunks

    Returns:
        Dict mit situation, answer, sources, chunks
    """
    client = _get_client()
    display_name = GAME_DISPLAY_NAMES.get(game, game)
    image_b64 = base64.standard_b64encode(image_data).decode("utf-8")

    # Schritt 1: Spielzustand beschreiben
    describe_response = client.messages.create(
        model=MODEL,
        max_tokens=512,
        system=(
            f"Du bist ein Experte für {display_name}. "
            "Beschreibe präzise was du auf dem Bild siehst: "
            "Spielkomponenten, Karten, Token, Spielzustand. "
            "Antworte in der Sprache der Frage."
        ),
        messages=[{
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": media_type,
                        "data": image_b64,
                    },
                },
                {
                    "type": "text",
                    "text": f"Beschreibe den Spielzustand auf dem Bild. Frage des Spielers: {question}",
                },
            ],
        }],
    )
    situation = describe_response.content[0].text

    # Schritt 2: RAG-Retrieval mit Bildbeschreibung + Frage
    rag_query = f"{situation}\n\n{question}"
    chunks = retrieve(rag_query, game, k=k)
    context = _format_chunks(chunks)

    # Schritt 3: Kombinierte Antwort mit Bild + Kontext
    prompt_template = _load_prompt()
    system_prompt = prompt_template.split("## Aufgabe")[0]
    system_prompt = re.sub(r"^#.*?\n+", "", system_prompt).strip()
    system_prompt = system_prompt.replace("{{spielname}}", display_name)

    answer_response = client.messages.create(
        model=MODEL,
        max_tokens=1024,
        system=system_prompt,
        messages=[{
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": media_type,
                        "data": image_b64,
                    },
                },
                {
                    "type": "text",
                    "text": (
                        f"## Erkannter Spielzustand\n\n{situation}\n\n"
                        f"## Regeltext-Kontext\n\n{context}\n\n"
                        f"## Frage des Spielers\n\n{question}"
                    ),
                },
            ],
        }],
    )

    answer = answer_response.content[0].text
    sources = _extract_sources(chunks)

    return {
        "situation": situation,
        "answer": answer,
        "sources": sources,
        "chunks": chunks,
    }