-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslip_vision.py
More file actions
134 lines (117 loc) · 4.45 KB
/
Copy pathslip_vision.py
File metadata and controls
134 lines (117 loc) · 4.45 KB
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
"""
Gemini vision/OCR helper for brother's 2-odds bet slips.
Given raw image bytes (Telegram photo) and optional caption text, returns
an extracted slip dict compatible with the /slip handler:
{
"description": "...",
"stake": float | None,
"total_odds": float | None,
"legs": [
{
"fixture_hint": str,
"league_hint": str | None,
"market": str | None,
"line": float | None,
"odds": float | None,
},
...
],
}
"""
from __future__ import annotations
import json
import os
from typing import Any
from dotenv import load_dotenv
_script_dir = os.path.dirname(os.path.abspath(__file__))
load_dotenv(os.path.join(_script_dir, ".env"))
GEMINI_API_KEY = (os.getenv("GEMINI_API_KEY") or "").strip()
def _safe_float(val: Any) -> float | None:
try:
if val is None:
return None
return float(val)
except (TypeError, ValueError):
return None
def parse_slip_from_image(image_bytes: bytes, caption: str | None = None) -> dict:
"""Use Gemini multimodal model to parse a bet slip image into a structured slip dict."""
if not GEMINI_API_KEY or not image_bytes:
return {}
try:
import google.generativeai as genai
genai.configure(api_key=GEMINI_API_KEY)
model = genai.GenerativeModel("gemini-2.5-flash")
img_part = {
"mime_type": "image/jpeg",
"data": image_bytes,
}
caption_text = (caption or "").strip()
prompt = (
"You are reading a sports bet slip image. Extract only structured data.\n\n"
"Return STRICT JSON ONLY (no prose, no markdown, no code fences) with this schema:\n"
"{\n"
' \"stake\": float or null,\n'
' \"total_odds\": float or null,\n'
' \"legs\": [\n'
" {\n"
' \"fixture_hint\": string, // e.g. \"Liverpool vs Chelsea\"\n'
' \"league_hint\": string or null, // e.g. \"Premier League\"\n'
' \"market\": string or null, // e.g. \"OVER_2_5\", \"HOME_WIN\"\n'
' \"line\": float or null, // e.g. 2.5 for totals\n'
' \"odds\": float or null // per-leg odds if visible\n'
" },\n"
" ...\n"
" ]\n"
"}\n\n"
"If something is not visible, set it to null. Do NOT include comments.\n"
)
contents: list[Any] = [img_part, {"text": prompt}]
if caption_text:
contents.append({"text": f"Caption: {caption_text}"})
resp = model.generate_content(contents)
raw = (resp.text or "").strip() if resp else ""
if not raw:
return {}
# Some models may wrap JSON in fences or prose; try to locate the first JSON object.
raw_str = raw
if "```" in raw_str:
# take content between first pair of fences if present
parts = raw_str.split("```")
if len(parts) >= 3:
raw_str = parts[1]
raw_str = raw_str.strip()
data = json.loads(raw_str)
slip: dict = {}
slip["stake"] = _safe_float(data.get("stake"))
slip["total_odds"] = _safe_float(data.get("total_odds"))
legs_out: list[dict] = []
for leg in data.get("legs") or []:
if not isinstance(leg, dict):
continue
fixture_hint = (leg.get("fixture_hint") or "").strip()
league_hint = (leg.get("league_hint") or "") or None
market = (leg.get("market") or "") or None
line_val = _safe_float(leg.get("line"))
odds_val = _safe_float(leg.get("odds"))
if not fixture_hint and not league_hint and not market:
continue
legs_out.append(
{
"fixture_hint": fixture_hint,
"league_hint": league_hint,
"market": market,
"line": line_val,
"odds": odds_val,
}
)
slip["legs"] = legs_out
# Description is for human reading; prefer caption if present, else join legs.
if caption_text:
slip["description"] = caption_text
elif legs_out:
slip["description"] = "; ".join(l.get("fixture_hint") or "" for l in legs_out if l.get("fixture_hint"))
else:
slip["description"] = ""
return slip
except Exception:
return {}