Upload 4 files
Browse files- .gitattributes +1 -0
- app.py +425 -0
- hunting_dates.csv +3 -0
- letzhunt.py +1004 -0
- requirements.txt +6 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
hunting_dates.csv filter=lfs diff=lfs merge=lfs -text
|
app.py
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
| 7 |
+
import gpxpy
|
| 8 |
+
import gpxpy.gpx
|
| 9 |
+
import gradio as gr
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import folium
|
| 12 |
+
from shapely.geometry import LineString, Polygon, MultiLineString
|
| 13 |
+
from shapely.ops import unary_union
|
| 14 |
+
|
| 15 |
+
# =======================
|
| 16 |
+
# Data loading & parsing
|
| 17 |
+
# =======================
|
| 18 |
+
|
| 19 |
+
CSV_PATH = "hunting_dates.csv"
|
| 20 |
+
df_raw = pd.read_csv(CSV_PATH)
|
| 21 |
+
|
| 22 |
+
# --- Robust polygon parsing ---
|
| 23 |
+
|
| 24 |
+
def _normalize_polygon_nested(obj: Any) -> List[List[Tuple[float, float]]]:
|
| 25 |
+
"""
|
| 26 |
+
Normalize structure into list of rings (each ring = list[(lon, lat)]).
|
| 27 |
+
"""
|
| 28 |
+
def is_point(p):
|
| 29 |
+
return (
|
| 30 |
+
isinstance(p, (list, tuple))
|
| 31 |
+
and len(p) >= 2
|
| 32 |
+
and isinstance(p[0], (int, float))
|
| 33 |
+
and isinstance(p[1], (int, float))
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
if isinstance(obj, (list, tuple)) and obj and all(is_point(pt) for pt in obj):
|
| 37 |
+
ring = [(float(pt[0]), float(pt[1])) for pt in obj]
|
| 38 |
+
return [ring]
|
| 39 |
+
|
| 40 |
+
if isinstance(obj, (list, tuple)):
|
| 41 |
+
rings: List[List[Tuple[float, float]]] = []
|
| 42 |
+
if obj and all(isinstance(item, (list, tuple)) for item in obj):
|
| 43 |
+
if any(isinstance(item, (list, tuple)) and item and all(is_point(pt) for pt in item) for item in obj):
|
| 44 |
+
for item in obj:
|
| 45 |
+
if not item:
|
| 46 |
+
continue
|
| 47 |
+
if all(is_point(pt) for pt in item):
|
| 48 |
+
ring = [(float(pt[0]), float(pt[1])) for pt in item]
|
| 49 |
+
rings.append(ring)
|
| 50 |
+
else:
|
| 51 |
+
sub_rings = _normalize_polygon_nested(item)
|
| 52 |
+
rings.extend(sub_rings)
|
| 53 |
+
return rings
|
| 54 |
+
|
| 55 |
+
for child in obj:
|
| 56 |
+
if child is None:
|
| 57 |
+
continue
|
| 58 |
+
sub_rings = _normalize_polygon_nested(child)
|
| 59 |
+
if sub_rings:
|
| 60 |
+
return sub_rings
|
| 61 |
+
|
| 62 |
+
raise ValueError(f"Cannot interpret polygon structure: {obj!r}")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def parse_polygon_str(poly_str: str) -> Polygon:
|
| 66 |
+
if not isinstance(poly_str, str):
|
| 67 |
+
raise ValueError(f"Polygon value is not a string: {poly_str!r}")
|
| 68 |
+
|
| 69 |
+
s = poly_str.strip()
|
| 70 |
+
|
| 71 |
+
parsed = None
|
| 72 |
+
try:
|
| 73 |
+
parsed = json.loads(s)
|
| 74 |
+
except Exception:
|
| 75 |
+
try:
|
| 76 |
+
parsed = eval(s, {"__builtins__": None}, {})
|
| 77 |
+
except Exception as e:
|
| 78 |
+
raise ValueError(f"Failed to parse polygon string: {poly_str!r}") from e
|
| 79 |
+
|
| 80 |
+
rings = _normalize_polygon_nested(parsed)
|
| 81 |
+
if not rings:
|
| 82 |
+
raise ValueError(f"No valid ring found in polygon: {poly_str!r}")
|
| 83 |
+
|
| 84 |
+
shell = rings[0]
|
| 85 |
+
holes = rings[1:] if len(rings) > 1 else None
|
| 86 |
+
return Polygon(shell, holes)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# --- Parse dates column into list of datetime.date ---
|
| 90 |
+
|
| 91 |
+
DATE_RE = re.compile(r"(\d{2}/\d{2}/\d{4}|\d{4}-\d{2}-\d{2})")
|
| 92 |
+
|
| 93 |
+
def parse_dates_field(dates_field: str) -> List[dt.date]:
|
| 94 |
+
if not isinstance(dates_field, str):
|
| 95 |
+
return []
|
| 96 |
+
matches = DATE_RE.findall(dates_field)
|
| 97 |
+
parsed: List[dt.date] = []
|
| 98 |
+
for m in matches:
|
| 99 |
+
if "/" in m:
|
| 100 |
+
d = dt.datetime.strptime(m, "%d/%m/%Y").date()
|
| 101 |
+
else:
|
| 102 |
+
d = dt.datetime.strptime(m, "%Y-%m-%d").date()
|
| 103 |
+
parsed.append(d)
|
| 104 |
+
return sorted(set(parsed))
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
records: List[Dict] = []
|
| 108 |
+
for _, row in df_raw.iterrows():
|
| 109 |
+
lot = int(row["lot"])
|
| 110 |
+
poly = parse_polygon_str(str(row["polygon"]))
|
| 111 |
+
dates = parse_dates_field(str(row.get("dates", "")))
|
| 112 |
+
records.append(
|
| 113 |
+
{
|
| 114 |
+
"lot": lot,
|
| 115 |
+
"polygon": poly,
|
| 116 |
+
"dates": dates,
|
| 117 |
+
}
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
df = pd.DataFrame(records)
|
| 121 |
+
|
| 122 |
+
all_dates = sorted({d for dates in df["dates"] for d in dates})
|
| 123 |
+
if not all_dates:
|
| 124 |
+
MIN_DATE = MAX_DATE = dt.date.today()
|
| 125 |
+
else:
|
| 126 |
+
MIN_DATE = all_dates[0]
|
| 127 |
+
MAX_DATE = all_dates[-1]
|
| 128 |
+
|
| 129 |
+
lot_dates_map: Dict[int, List[dt.date]] = {
|
| 130 |
+
lot: sorted({d for dates in group["dates"] for d in dates})
|
| 131 |
+
for lot, group in df.groupby("lot")
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
def date_to_str(d: dt.date) -> str:
|
| 135 |
+
return d.strftime("%d/%m/%Y")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
# =======================
|
| 139 |
+
# GPX parsing / overlap
|
| 140 |
+
# =======================
|
| 141 |
+
|
| 142 |
+
def parse_gpx_file(file_obj) -> List[LineString]:
|
| 143 |
+
"""
|
| 144 |
+
Handles both filepath string and file object.
|
| 145 |
+
"""
|
| 146 |
+
path = None
|
| 147 |
+
if isinstance(file_obj, str):
|
| 148 |
+
path = file_obj
|
| 149 |
+
elif hasattr(file_obj, "name"):
|
| 150 |
+
path = file_obj.name
|
| 151 |
+
|
| 152 |
+
if not path or not os.path.exists(path):
|
| 153 |
+
return []
|
| 154 |
+
|
| 155 |
+
with open(path, "r", encoding="utf-8", errors="ignore") as f:
|
| 156 |
+
gpx = gpxpy.parse(f)
|
| 157 |
+
|
| 158 |
+
lines: List[LineString] = []
|
| 159 |
+
|
| 160 |
+
for track in gpx.tracks:
|
| 161 |
+
for segment in track.segments:
|
| 162 |
+
pts = [(p.longitude, p.latitude) for p in segment.points]
|
| 163 |
+
if len(pts) >= 2:
|
| 164 |
+
lines.append(LineString(pts))
|
| 165 |
+
|
| 166 |
+
for route in gpx.routes:
|
| 167 |
+
pts = [(p.longitude, p.latitude) for p in route.points]
|
| 168 |
+
if len(pts) >= 2:
|
| 169 |
+
lines.append(LineString(pts))
|
| 170 |
+
|
| 171 |
+
return lines
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def split_line_by_polygons(line: LineString, polys: List[Polygon]) -> Tuple[List[LineString], List[LineString]]:
|
| 175 |
+
if not polys:
|
| 176 |
+
return [], [line]
|
| 177 |
+
|
| 178 |
+
union_poly = unary_union(polys)
|
| 179 |
+
inter = line.intersection(union_poly)
|
| 180 |
+
|
| 181 |
+
intersecting: List[LineString] = []
|
| 182 |
+
non_intersecting: List[LineString] = []
|
| 183 |
+
|
| 184 |
+
def flatten_geom(g, target: List[LineString]):
|
| 185 |
+
if g.is_empty:
|
| 186 |
+
return
|
| 187 |
+
if isinstance(g, LineString):
|
| 188 |
+
target.append(g)
|
| 189 |
+
elif isinstance(g, MultiLineString):
|
| 190 |
+
for part in g.geoms:
|
| 191 |
+
target.append(part)
|
| 192 |
+
else:
|
| 193 |
+
# Handle GeometryCollection or other mixed types if necessary
|
| 194 |
+
try:
|
| 195 |
+
for part in g.geoms:
|
| 196 |
+
flatten_geom(part, target)
|
| 197 |
+
except AttributeError:
|
| 198 |
+
pass
|
| 199 |
+
|
| 200 |
+
flatten_geom(inter, intersecting)
|
| 201 |
+
|
| 202 |
+
diff = line.difference(union_poly)
|
| 203 |
+
flatten_geom(diff, non_intersecting)
|
| 204 |
+
|
| 205 |
+
return intersecting, non_intersecting
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
# =======================
|
| 209 |
+
# Date helpers
|
| 210 |
+
# =======================
|
| 211 |
+
|
| 212 |
+
def clamp_date(d: dt.date) -> dt.date:
|
| 213 |
+
if d < MIN_DATE:
|
| 214 |
+
return MIN_DATE
|
| 215 |
+
if d > MAX_DATE:
|
| 216 |
+
return MAX_DATE
|
| 217 |
+
return d
|
| 218 |
+
|
| 219 |
+
def default_date() -> dt.date:
|
| 220 |
+
today = dt.date.today()
|
| 221 |
+
return clamp_date(today)
|
| 222 |
+
|
| 223 |
+
def date_to_timestamp(d: dt.date) -> float:
|
| 224 |
+
return dt.datetime(d.year, d.month, d.day, tzinfo=dt.timezone.utc).timestamp()
|
| 225 |
+
|
| 226 |
+
def normalize_selected_ts(ts: Any) -> dt.date:
|
| 227 |
+
if ts is None:
|
| 228 |
+
return default_date()
|
| 229 |
+
try:
|
| 230 |
+
t = float(ts)
|
| 231 |
+
d = dt.datetime.fromtimestamp(t, tz=dt.timezone.utc).date()
|
| 232 |
+
except Exception:
|
| 233 |
+
return default_date()
|
| 234 |
+
return clamp_date(d)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
# =======================
|
| 238 |
+
# Map rendering (Folium)
|
| 239 |
+
# =======================
|
| 240 |
+
|
| 241 |
+
LUX_CENTER = [49.8153, 6.13]
|
| 242 |
+
LUX_ZOOM = 10
|
| 243 |
+
|
| 244 |
+
def build_map_html(selected_ts: Any,
|
| 245 |
+
gpx_lines: Optional[List[LineString]]) -> str:
|
| 246 |
+
d = normalize_selected_ts(selected_ts)
|
| 247 |
+
|
| 248 |
+
# Responsive map configuration
|
| 249 |
+
m = folium.Map(
|
| 250 |
+
location=LUX_CENTER,
|
| 251 |
+
zoom_start=LUX_ZOOM,
|
| 252 |
+
width="100%",
|
| 253 |
+
height="100vh",
|
| 254 |
+
tiles="OpenStreetMap",
|
| 255 |
+
attr=" ",
|
| 256 |
+
)
|
| 257 |
+
m.options['attributionControl'] = False
|
| 258 |
+
|
| 259 |
+
# 1. Add Hunting Lots (Polygons)
|
| 260 |
+
active_rows = df[df["dates"].apply(lambda ds: d in ds)]
|
| 261 |
+
active_polys: List[Polygon] = []
|
| 262 |
+
|
| 263 |
+
for _, row in active_rows.iterrows():
|
| 264 |
+
lot = row["lot"]
|
| 265 |
+
poly: Polygon = row["polygon"]
|
| 266 |
+
if poly.is_empty:
|
| 267 |
+
continue
|
| 268 |
+
active_polys.append(poly)
|
| 269 |
+
|
| 270 |
+
lot_str = f"{lot:03d}"
|
| 271 |
+
dates_for_lot = lot_dates_map.get(lot, [])
|
| 272 |
+
date_lines = [f"<b>{date_to_str(x)}</b>" for x in dates_for_lot]
|
| 273 |
+
html_popup = f"<b>{lot_str}</b><br><br>" + "<br>".join(date_lines)
|
| 274 |
+
|
| 275 |
+
gj = folium.GeoJson(
|
| 276 |
+
data=poly.__geo_interface__,
|
| 277 |
+
style_function=lambda feat, col="crimson": {
|
| 278 |
+
"fillColor": col,
|
| 279 |
+
"color": col,
|
| 280 |
+
"weight": 2,
|
| 281 |
+
"fillOpacity": 0.45,
|
| 282 |
+
},
|
| 283 |
+
)
|
| 284 |
+
folium.Popup(html_popup, max_width=300).add_to(gj)
|
| 285 |
+
gj.add_to(m)
|
| 286 |
+
|
| 287 |
+
# 2. Add GPX Lines (GeoJSON)
|
| 288 |
+
all_line_geoms = [] # For calculating bounds
|
| 289 |
+
|
| 290 |
+
if gpx_lines:
|
| 291 |
+
if active_polys:
|
| 292 |
+
# Split lines into overlapping (red) and non-overlapping (blue)
|
| 293 |
+
inter_lines = []
|
| 294 |
+
non_inter_lines = []
|
| 295 |
+
|
| 296 |
+
for line in gpx_lines:
|
| 297 |
+
inter, non_inter = split_line_by_polygons(line, active_polys)
|
| 298 |
+
inter_lines.extend(inter)
|
| 299 |
+
non_inter_lines.extend(non_inter)
|
| 300 |
+
|
| 301 |
+
if inter_lines:
|
| 302 |
+
folium.GeoJson(
|
| 303 |
+
data=MultiLineString(inter_lines).__geo_interface__,
|
| 304 |
+
style_function=lambda x: {"color": "red", "weight": 4, "opacity": 0.9}
|
| 305 |
+
).add_to(m)
|
| 306 |
+
all_line_geoms.extend(inter_lines)
|
| 307 |
+
|
| 308 |
+
if non_inter_lines:
|
| 309 |
+
folium.GeoJson(
|
| 310 |
+
data=MultiLineString(non_inter_lines).__geo_interface__,
|
| 311 |
+
style_function=lambda x: {"color": "blue", "weight": 3, "opacity": 0.7}
|
| 312 |
+
).add_to(m)
|
| 313 |
+
all_line_geoms.extend(non_inter_lines)
|
| 314 |
+
else:
|
| 315 |
+
# No hunting lots active, draw all lines in blue
|
| 316 |
+
if gpx_lines:
|
| 317 |
+
folium.GeoJson(
|
| 318 |
+
data=MultiLineString(gpx_lines).__geo_interface__,
|
| 319 |
+
style_function=lambda x: {"color": "blue", "weight": 3, "opacity": 0.7}
|
| 320 |
+
).add_to(m)
|
| 321 |
+
all_line_geoms.extend(gpx_lines)
|
| 322 |
+
|
| 323 |
+
# 3. Auto-zoom to GPX track
|
| 324 |
+
if all_line_geoms:
|
| 325 |
+
# Calculate bounds: (minx, miny, maxx, maxy) -> (min_lon, min_lat, max_lon, max_lat)
|
| 326 |
+
min_x, min_y, max_x, max_y = MultiLineString(all_line_geoms).bounds
|
| 327 |
+
# Folium fit_bounds takes [[min_lat, min_lon], [max_lat, max_lon]]
|
| 328 |
+
m.fit_bounds([[min_y, min_x], [max_y, max_x]])
|
| 329 |
+
|
| 330 |
+
return m._repr_html_()
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
# =======================
|
| 334 |
+
# Gradio interface logic
|
| 335 |
+
# =======================
|
| 336 |
+
|
| 337 |
+
def app_fn(selected_ts: Any, gpx_file):
|
| 338 |
+
new_lines: List[LineString] = []
|
| 339 |
+
if gpx_file is not None:
|
| 340 |
+
new_lines = parse_gpx_file(gpx_file)
|
| 341 |
+
map_html = build_map_html(selected_ts, new_lines)
|
| 342 |
+
return map_html
|
| 343 |
+
|
| 344 |
+
def clear_gpx_fn(selected_ts: Any):
|
| 345 |
+
map_html = build_map_html(selected_ts, gpx_lines=None)
|
| 346 |
+
return map_html, None
|
| 347 |
+
|
| 348 |
+
# =======================
|
| 349 |
+
# Build Gradio UI
|
| 350 |
+
# =======================
|
| 351 |
+
|
| 352 |
+
# Removed css argument to fix crash. Added gr.HTML for styles below.
|
| 353 |
+
with gr.Blocks(title="Luxembourg Hunting Lots") as demo:
|
| 354 |
+
|
| 355 |
+
# Inject CSS for hiding footer
|
| 356 |
+
gr.HTML("""
|
| 357 |
+
<style>
|
| 358 |
+
footer {visibility: hidden}
|
| 359 |
+
.gradio-container {min-height: 0px !important;}
|
| 360 |
+
</style>
|
| 361 |
+
""")
|
| 362 |
+
|
| 363 |
+
gr.Markdown(
|
| 364 |
+
"## Hunting Dates in Luxembourg\n"
|
| 365 |
+
"Choose a date and optionally upload a GPX track to see overlaps "
|
| 366 |
+
"with active hunting lots.\n\n"
|
| 367 |
+
f"Data available from **{MIN_DATE}** to **{MAX_DATE}**."
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
with gr.Row():
|
| 371 |
+
date_input = gr.DateTime(
|
| 372 |
+
label="Select date",
|
| 373 |
+
value=date_to_timestamp(default_date()),
|
| 374 |
+
include_time=False,
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
gpx_input = gr.File(
|
| 378 |
+
label="Upload GPX track (optional)",
|
| 379 |
+
file_types=[".gpx"],
|
| 380 |
+
interactive=True
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
clear_btn = gr.Button("Clear GPX")
|
| 384 |
+
|
| 385 |
+
map_output = gr.HTML()
|
| 386 |
+
|
| 387 |
+
# Initial map
|
| 388 |
+
init_map_html = build_map_html(date_to_timestamp(default_date()), gpx_lines=None)
|
| 389 |
+
map_output.value = init_map_html
|
| 390 |
+
|
| 391 |
+
# Events
|
| 392 |
+
date_input.change(
|
| 393 |
+
fn=app_fn,
|
| 394 |
+
inputs=[date_input, gpx_input],
|
| 395 |
+
outputs=[map_output],
|
| 396 |
+
show_progress=False,
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
gpx_input.change(
|
| 400 |
+
fn=app_fn,
|
| 401 |
+
inputs=[date_input, gpx_input],
|
| 402 |
+
outputs=[map_output],
|
| 403 |
+
show_progress=True,
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
clear_btn.click(
|
| 407 |
+
fn=clear_gpx_fn,
|
| 408 |
+
inputs=[date_input],
|
| 409 |
+
outputs=[map_output, gpx_input],
|
| 410 |
+
show_progress=False,
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
gr.Markdown(
|
| 414 |
+
"""
|
| 415 |
+
---
|
| 416 |
+
|
| 417 |
+
[Freedom Luxembourg](https://www.freeletz.lu/freeletz/)
|
| 418 |
+
|
| 419 |
+
The information provided is offered “as is”, without any guarantees.
|
| 420 |
+
The only authoritative source of information is the official [GeoPortail](https://map.geoportail.lu/communes/Luxembourg/anf_dates_battues/?lang=en)
|
| 421 |
+
"""
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
if __name__ == "__main__":
|
| 425 |
+
demo.launch()
|
hunting_dates.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b6869b40e39f87153f85033dc22d1d635c52dfb5e3e2f089adbb6099599a9baa
|
| 3 |
+
size 12337939
|
letzhunt.py
ADDED
|
@@ -0,0 +1,1004 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
import json
|
| 4 |
+
import datetime
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import requests
|
| 7 |
+
import re
|
| 8 |
+
import cv2
|
| 9 |
+
import numpy as np
|
| 10 |
+
from urllib.request import urlopen
|
| 11 |
+
from shapely.geometry import Polygon, MultiPolygon
|
| 12 |
+
from pyproj import Transformer
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
from typing import List, Dict, Any, Tuple, Optional
|
| 15 |
+
import dateparser
|
| 16 |
+
import tempfile # << kept (no-op, left as requested)
|
| 17 |
+
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from datetime import datetime as _dt, date as _date
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
from PIL import Image
|
| 23 |
+
from transformers import AutoProcessor
|
| 24 |
+
from transformers import HunYuanVLForConditionalGeneration
|
| 25 |
+
|
| 26 |
+
# super-image for upscaling
|
| 27 |
+
from super_image import DrlnModel, ImageLoader
|
| 28 |
+
|
| 29 |
+
# ================================
|
| 30 |
+
# --- Global Constants ---
|
| 31 |
+
# ================================
|
| 32 |
+
|
| 33 |
+
BASE_LOTS_FILE = 'hunting_lots.csv'
|
| 34 |
+
DATES_FILE = 'hunting_dates.csv'
|
| 35 |
+
TILES_DIR = 'tiles'
|
| 36 |
+
|
| 37 |
+
API_URL = "https://wms.inspire.geoportail.lu/geoserver/am/ogc/features/v1/collections/AM.HuntingLots/items?f=json&limit=1000&startIndex=0"
|
| 38 |
+
WMS_BASE_URL = "https://wmsproxy.geoportail.lu/ogcproxywms"
|
| 39 |
+
|
| 40 |
+
# --- Hunyuan OCR Configuration ---
|
| 41 |
+
HUNYUAN_MODEL_NAME = "tencent/HunyuanOCR"
|
| 42 |
+
|
| 43 |
+
# --- Super-resolution Configuration ---
|
| 44 |
+
SUPERRES_MODEL_NAME = "eugenesiow/drln-bam" # DRLN model family
|
| 45 |
+
SUPERRES_SCALE = 2 # must match model
|
| 46 |
+
|
| 47 |
+
# Max tolerated OCR day shift when repairing dates
|
| 48 |
+
MAX_OCR_DAY_SHIFT = 180
|
| 49 |
+
|
| 50 |
+
# ================================
|
| 51 |
+
# --- Utility Functions ---
|
| 52 |
+
# ================================
|
| 53 |
+
|
| 54 |
+
def safe_literal_eval(val):
|
| 55 |
+
"""Safely evaluate string representations of lists/tuples."""
|
| 56 |
+
try:
|
| 57 |
+
if isinstance(val, str) and (val.startswith('[') or val.startswith('(')):
|
| 58 |
+
return json.loads(val.replace("'", '"').replace("(", "[").replace(")", "]"))
|
| 59 |
+
return val
|
| 60 |
+
except Exception:
|
| 61 |
+
return []
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def ensure_directory(directory: str):
|
| 65 |
+
"""Create directory if it doesn't exist."""
|
| 66 |
+
if not os.path.exists(directory):
|
| 67 |
+
os.makedirs(directory)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def file_uptodate(file_path: str, days: int, required_columns: List[str] = None) -> bool:
|
| 71 |
+
"""Check if file exists, is recent, and has required columns."""
|
| 72 |
+
if not os.path.exists(file_path):
|
| 73 |
+
return False
|
| 74 |
+
mod_time = datetime.datetime.fromtimestamp(os.path.getmtime(file_path))
|
| 75 |
+
if (datetime.datetime.now() - mod_time).days > days:
|
| 76 |
+
return False
|
| 77 |
+
if required_columns:
|
| 78 |
+
try:
|
| 79 |
+
df = pd.read_csv(file_path, converters={'dates': safe_literal_eval})
|
| 80 |
+
return all(col in df.columns for col in required_columns)
|
| 81 |
+
except Exception:
|
| 82 |
+
return False
|
| 83 |
+
return True
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def load_image_safe(image_path: str) -> Optional[np.ndarray]:
|
| 87 |
+
"""Safely load an image with OpenCV, returning None if failed."""
|
| 88 |
+
try:
|
| 89 |
+
image = cv2.imread(image_path)
|
| 90 |
+
if image is None:
|
| 91 |
+
print(f"Warning: Could not load image {image_path}")
|
| 92 |
+
return None
|
| 93 |
+
return image
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f"Error loading image {image_path}: {e}")
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
+
# ================================
|
| 99 |
+
# --- Part 1: Hunting Lot Data ---
|
| 100 |
+
# ================================
|
| 101 |
+
|
| 102 |
+
def update_lots(url: str) -> pd.DataFrame:
|
| 103 |
+
"""Fetches and processes hunting lot geo data."""
|
| 104 |
+
print("Fetching latest hunting lot data from server...")
|
| 105 |
+
try:
|
| 106 |
+
with urlopen(url) as response:
|
| 107 |
+
data = json.loads(response.read().decode())
|
| 108 |
+
except Exception as e:
|
| 109 |
+
print(f"Error fetching lot data: {e}")
|
| 110 |
+
return pd.DataFrame()
|
| 111 |
+
|
| 112 |
+
features = data.get('features', [])
|
| 113 |
+
transformer = Transformer.from_crs("EPSG:4326", "EPSG:3857", always_xy=True)
|
| 114 |
+
|
| 115 |
+
processed_lots: List[Dict[str, Any]] = []
|
| 116 |
+
for item in tqdm(features, desc="Processing Lot Geometry"):
|
| 117 |
+
properties = item.get('properties', {})
|
| 118 |
+
lot_num = properties.get('gml_description', 'Unknown')
|
| 119 |
+
geometry = item.get('geometry')
|
| 120 |
+
|
| 121 |
+
lot_data = {
|
| 122 |
+
'lot': lot_num,
|
| 123 |
+
'polygon': None,
|
| 124 |
+
'centroid': None,
|
| 125 |
+
'bbox': None
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
if geometry:
|
| 129 |
+
geom_type = geometry.get('type')
|
| 130 |
+
coords = geometry.get('coordinates')
|
| 131 |
+
lot_data['polygon'] = coords
|
| 132 |
+
try:
|
| 133 |
+
poly_obj = None
|
| 134 |
+
if geom_type == 'Polygon' and coords:
|
| 135 |
+
poly_obj = Polygon(coords[0])
|
| 136 |
+
elif geom_type == 'MultiPolygon' and coords:
|
| 137 |
+
poly_obj = MultiPolygon([Polygon(p[0]) for p in coords if len(p) > 0])
|
| 138 |
+
|
| 139 |
+
if poly_obj:
|
| 140 |
+
centroid = poly_obj.centroid
|
| 141 |
+
lot_data['centroid'] = (centroid.x, centroid.y)
|
| 142 |
+
x, y = transformer.transform(centroid.x, centroid.y)
|
| 143 |
+
lot_data['bbox'] = (x - 1000, y - 1000, x + 1000, y + 1000)
|
| 144 |
+
except Exception as e:
|
| 145 |
+
print(f"Geometry error for lot {lot_num}: {e}")
|
| 146 |
+
|
| 147 |
+
processed_lots.append(lot_data)
|
| 148 |
+
|
| 149 |
+
df = pd.DataFrame(processed_lots)
|
| 150 |
+
df = df[df['lot'] != 'Unknown'].copy()
|
| 151 |
+
df['lot'] = pd.to_numeric(df['lot'], errors='coerce')
|
| 152 |
+
df = df.dropna(subset=['lot']).astype({'lot': int}).sort_values('lot').reset_index(drop=True)
|
| 153 |
+
|
| 154 |
+
df.to_csv(BASE_LOTS_FILE, index=False)
|
| 155 |
+
print(f"Saved full lot geometry data → {BASE_LOTS_FILE}")
|
| 156 |
+
return df
|
| 157 |
+
|
| 158 |
+
# ================================
|
| 159 |
+
# --- Part 2: Tile Download ---
|
| 160 |
+
# ================================
|
| 161 |
+
|
| 162 |
+
def get_tile_path(lot_number: int) -> str:
|
| 163 |
+
"""Get path to original tile."""
|
| 164 |
+
return os.path.join(TILES_DIR, f"{lot_number:03d}.png")
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def tile_uptodate(lot_number: int, days: int = 7) -> bool:
|
| 168 |
+
"""Check if tile is recent."""
|
| 169 |
+
path = get_tile_path(lot_number)
|
| 170 |
+
if not os.path.exists(path):
|
| 171 |
+
return False
|
| 172 |
+
mod_time = datetime.datetime.fromtimestamp(os.path.getmtime(path))
|
| 173 |
+
return (datetime.datetime.now() - mod_time).days <= days
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def download_tile(lot_number: int, bounds: Tuple[float, float, float, float]) -> bool:
|
| 177 |
+
"""Download WMS tile for a lot."""
|
| 178 |
+
try:
|
| 179 |
+
bbox_str = ",".join([f"{coord:.2f}" for coord in bounds])
|
| 180 |
+
params = {
|
| 181 |
+
'SERVICE': 'WMS', 'VERSION': '1.3.0', 'REQUEST': 'GetMap',
|
| 182 |
+
'FORMAT': 'image/png', 'TRANSPARENT': 'true',
|
| 183 |
+
'LAYERS': 'anf_dates_battues', 'CRS': 'EPSG:3857',
|
| 184 |
+
'STYLES': '', 'WIDTH': '512', 'HEIGHT': '512', 'BBOX': bbox_str
|
| 185 |
+
}
|
| 186 |
+
response = requests.get(WMS_BASE_URL, params=params, timeout=30)
|
| 187 |
+
response.raise_for_status()
|
| 188 |
+
|
| 189 |
+
ensure_directory(TILES_DIR)
|
| 190 |
+
|
| 191 |
+
with open(get_tile_path(lot_number), 'wb') as f:
|
| 192 |
+
f.write(response.content)
|
| 193 |
+
|
| 194 |
+
if os.path.exists(get_tile_path(lot_number)) and os.path.getsize(get_tile_path(lot_number)) > 0:
|
| 195 |
+
return True
|
| 196 |
+
else:
|
| 197 |
+
print(f"Downloaded file is empty or missing for lot {lot_number}")
|
| 198 |
+
return False
|
| 199 |
+
|
| 200 |
+
except requests.exceptions.RequestException as e:
|
| 201 |
+
print(f"Tile download failed for lot {lot_number}: {e}")
|
| 202 |
+
return False
|
| 203 |
+
except Exception as e:
|
| 204 |
+
print(f"Unexpected error downloading tile for lot {lot_number}: {e}")
|
| 205 |
+
return False
|
| 206 |
+
|
| 207 |
+
# ================================
|
| 208 |
+
# --- Super-resolution (DRLN x4) ---
|
| 209 |
+
# ================================
|
| 210 |
+
|
| 211 |
+
class SuperResolutionWrapper:
|
| 212 |
+
"""
|
| 213 |
+
Thin wrapper around super-image DRLN x4 model.
|
| 214 |
+
Loaded once and reused for all tiles.
|
| 215 |
+
Runs on GPU if available, otherwise on CPU.
|
| 216 |
+
"""
|
| 217 |
+
def __init__(self, model_name: str = SUPERRES_MODEL_NAME, scale: int = SUPERRES_SCALE):
|
| 218 |
+
print(f"Loading super-resolution model '{model_name}' (scale x{scale})...")
|
| 219 |
+
import torch
|
| 220 |
+
|
| 221 |
+
# Pick device: prefer CUDA if available
|
| 222 |
+
if torch.cuda.is_available():
|
| 223 |
+
self.device = torch.device("cuda")
|
| 224 |
+
else:
|
| 225 |
+
self.device = torch.device("cpu")
|
| 226 |
+
|
| 227 |
+
# Load model and move to device
|
| 228 |
+
self.model = DrlnModel.from_pretrained(model_name, scale=scale)
|
| 229 |
+
self.model = self.model.to(self.device)
|
| 230 |
+
self.model.eval() # inference mode
|
| 231 |
+
|
| 232 |
+
# Debug info
|
| 233 |
+
devices = {str(p.device) for p in self.model.parameters()}
|
| 234 |
+
print(f"Super-resolution model loaded on device(s): {devices}")
|
| 235 |
+
self.scale = scale
|
| 236 |
+
|
| 237 |
+
def _open_with_background(self, input_path: str, bg_color=(255, 255, 255)) -> Image.Image:
|
| 238 |
+
"""
|
| 239 |
+
Open a possibly-transparent PNG and composite onto a solid background.
|
| 240 |
+
Default background is white (255,255,255).
|
| 241 |
+
"""
|
| 242 |
+
img = Image.open(input_path)
|
| 243 |
+
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
|
| 244 |
+
# Ensure RGBA
|
| 245 |
+
img = img.convert("RGBA")
|
| 246 |
+
bg = Image.new("RGB", img.size, bg_color)
|
| 247 |
+
bg.paste(img, mask=img.split()[-1]) # use alpha channel as mask
|
| 248 |
+
return bg
|
| 249 |
+
else:
|
| 250 |
+
# No alpha channel, just convert to RGB
|
| 251 |
+
return img.convert("RGB")
|
| 252 |
+
|
| 253 |
+
def upscale_image(self, input_path: str) -> Optional[Image.Image]:
|
| 254 |
+
"""
|
| 255 |
+
Upscale an image and return the upscaled PIL image directly without saving to disk.
|
| 256 |
+
"""
|
| 257 |
+
try:
|
| 258 |
+
img = self._open_with_background(input_path, bg_color=(255, 255, 255))
|
| 259 |
+
|
| 260 |
+
lr = ImageLoader.load_image(img)
|
| 261 |
+
if isinstance(lr, torch.Tensor):
|
| 262 |
+
lr = lr.to(self.device)
|
| 263 |
+
else:
|
| 264 |
+
lr = lr.to(self.device)
|
| 265 |
+
|
| 266 |
+
with torch.no_grad():
|
| 267 |
+
sr = self.model(lr)
|
| 268 |
+
|
| 269 |
+
if isinstance(sr, torch.Tensor):
|
| 270 |
+
sr_cpu = sr.detach().cpu()
|
| 271 |
+
else:
|
| 272 |
+
sr_cpu = sr
|
| 273 |
+
|
| 274 |
+
# Convert tensor back to PIL.Image using super-image utilities
|
| 275 |
+
# sr_cpu is expected to be in CHW, [0,1]
|
| 276 |
+
np_img = sr_cpu.squeeze(0).clamp(0, 1).mul(255).byte().permute(1, 2, 0).numpy()
|
| 277 |
+
return Image.fromarray(np_img)
|
| 278 |
+
except Exception as e:
|
| 279 |
+
print(f"Super-resolution (in-memory) failed for '{input_path}': {e}")
|
| 280 |
+
return None
|
| 281 |
+
|
| 282 |
+
# ================================
|
| 283 |
+
# --- Hunyuan OCR utilities ---
|
| 284 |
+
# ================================
|
| 285 |
+
|
| 286 |
+
def clean_repeated_substrings(text: str) -> str:
|
| 287 |
+
"""Clean repeated substrings in text (your original logic)."""
|
| 288 |
+
n = len(text)
|
| 289 |
+
if n < 8000:
|
| 290 |
+
return text
|
| 291 |
+
for length in range(2, n // 10 + 1):
|
| 292 |
+
candidate = text[-length:]
|
| 293 |
+
count = 0
|
| 294 |
+
i = n - length
|
| 295 |
+
|
| 296 |
+
while i >= 0 and text[i:i + length] == candidate:
|
| 297 |
+
count += 1
|
| 298 |
+
i -= length
|
| 299 |
+
|
| 300 |
+
if count >= 10:
|
| 301 |
+
return text[:n - length * (count - 1)]
|
| 302 |
+
|
| 303 |
+
return text
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
@dataclass
|
| 307 |
+
class Line:
|
| 308 |
+
text: str
|
| 309 |
+
x1: int
|
| 310 |
+
y1: int
|
| 311 |
+
x2: int
|
| 312 |
+
y2: int
|
| 313 |
+
|
| 314 |
+
@property
|
| 315 |
+
def cx(self) -> float:
|
| 316 |
+
return (self.x1 + self.x2) / 2
|
| 317 |
+
|
| 318 |
+
@property
|
| 319 |
+
def cy(self) -> float:
|
| 320 |
+
return (self.y1 + self.y2) / 2
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
PATTERN = re.compile(r"""
|
| 324 |
+
(?P<text>.+?)
|
| 325 |
+
\(
|
| 326 |
+
(?P<x1>\d+)
|
| 327 |
+
,
|
| 328 |
+
(?P<y1>\d+)
|
| 329 |
+
\),
|
| 330 |
+
\(
|
| 331 |
+
(?P<x2>\d+)
|
| 332 |
+
,
|
| 333 |
+
(?P<y2>\d+)
|
| 334 |
+
\)
|
| 335 |
+
""", re.VERBOSE)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def parse_compact_ocr_string(s: str, img_w: int, img_h: int) -> list[Line]:
|
| 339 |
+
"""
|
| 340 |
+
Parse HunyuanOCR's compact output string and
|
| 341 |
+
denormalize coordinates from [0,1000] to image pixels.
|
| 342 |
+
"""
|
| 343 |
+
lines: list[Line] = []
|
| 344 |
+
for m in PATTERN.finditer(s):
|
| 345 |
+
text = m.group("text").strip()
|
| 346 |
+
x1_n = float(m.group("x1"))
|
| 347 |
+
y1_n = float(m.group("y1"))
|
| 348 |
+
x2_n = float(m.group("x2"))
|
| 349 |
+
y2_n = float(m.group("y2"))
|
| 350 |
+
|
| 351 |
+
x1 = int(x1_n * img_w / 1000.0)
|
| 352 |
+
y1 = int(y1_n * img_h / 1000.0)
|
| 353 |
+
x2 = int(x2_n * img_w / 1000.0)
|
| 354 |
+
y2 = int(y2_n * img_h / 1000.0)
|
| 355 |
+
|
| 356 |
+
lines.append(Line(text, x1, y1, x2, y2))
|
| 357 |
+
return lines
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def lines_are_close(a: Line, b: Line, max_dx: float, max_dy: float) -> bool:
|
| 361 |
+
dx = abs(a.cx - b.cx)
|
| 362 |
+
dy = abs(a.cy - b.cy)
|
| 363 |
+
return dx <= max_dx and dy <= max_dy
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def cluster_lines_into_labels(lines: list[Line], img_w: int, img_h: int) -> list[list[Line]]:
|
| 367 |
+
"""
|
| 368 |
+
Cluster lines into labels based on spatial proximity in pixel space.
|
| 369 |
+
Each cluster should correspond to one hunting-lot label.
|
| 370 |
+
"""
|
| 371 |
+
if not lines:
|
| 372 |
+
return []
|
| 373 |
+
|
| 374 |
+
max_dx = img_w * 0.2
|
| 375 |
+
max_dy = img_h * 0.2
|
| 376 |
+
|
| 377 |
+
labels: list[list[Line]] = []
|
| 378 |
+
visited: set[int] = set()
|
| 379 |
+
|
| 380 |
+
for i, line in enumerate(lines):
|
| 381 |
+
if i in visited:
|
| 382 |
+
continue
|
| 383 |
+
|
| 384 |
+
cluster_idx = len(labels)
|
| 385 |
+
labels.append([])
|
| 386 |
+
stack = [i]
|
| 387 |
+
visited.add(i)
|
| 388 |
+
|
| 389 |
+
while stack:
|
| 390 |
+
idx = stack.pop()
|
| 391 |
+
l = lines[idx]
|
| 392 |
+
labels[cluster_idx].append(l)
|
| 393 |
+
|
| 394 |
+
for j, other in enumerate(lines):
|
| 395 |
+
if j in visited:
|
| 396 |
+
continue
|
| 397 |
+
if lines_are_close(l, other, max_dx, max_dy):
|
| 398 |
+
visited.add(j)
|
| 399 |
+
stack.append(j)
|
| 400 |
+
|
| 401 |
+
for label in labels:
|
| 402 |
+
label.sort(key=lambda l: (l.cy, l.cx))
|
| 403 |
+
|
| 404 |
+
return labels
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
LOT_NUMBER_RE = re.compile(r"^\d{1,4}$")
|
| 408 |
+
DATE_RE = re.compile(r"^\s*\d{1,2}/\d{1,2}/\d{4}\s*$")
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def is_lot_number(text: str) -> bool:
|
| 412 |
+
return bool(LOT_NUMBER_RE.fullmatch(text.strip()))
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def is_battue_label(text: str) -> bool:
|
| 416 |
+
t = text.lower()
|
| 417 |
+
return "battue" in t and "treibjagd" in t
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def is_date_line(text: str) -> bool:
|
| 421 |
+
return bool(DATE_RE.fullmatch(text))
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def build_blocks_from_labels(labels: list[list[Line]]):
|
| 425 |
+
"""
|
| 426 |
+
From clusters of lines, build structured blocks:
|
| 427 |
+
lot number + Battue/Treibjagd + list of dates.
|
| 428 |
+
"""
|
| 429 |
+
blocks = []
|
| 430 |
+
for li, label_lines in enumerate(labels):
|
| 431 |
+
lot_line: Line | None = None
|
| 432 |
+
label_line: Line | None = None
|
| 433 |
+
date_lines: list[Line] = []
|
| 434 |
+
|
| 435 |
+
for l in label_lines:
|
| 436 |
+
txt = l.text.strip()
|
| 437 |
+
if is_lot_number(txt) and lot_line is None:
|
| 438 |
+
lot_line = l
|
| 439 |
+
elif is_battue_label(txt) and label_line is None:
|
| 440 |
+
label_line = l
|
| 441 |
+
elif is_date_line(txt):
|
| 442 |
+
date_lines.append(l)
|
| 443 |
+
|
| 444 |
+
if lot_line and label_line and date_lines:
|
| 445 |
+
date_lines.sort(key=lambda l: l.cy)
|
| 446 |
+
blocks.append({
|
| 447 |
+
"lot_line": lot_line,
|
| 448 |
+
"label_line": label_line,
|
| 449 |
+
"date_lines": date_lines,
|
| 450 |
+
})
|
| 451 |
+
return blocks
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def edit_distance(a: str, b: str) -> int:
|
| 455 |
+
dp = [[i + j if i * j == 0 else 0 for j in range(len(b) + 1)]
|
| 456 |
+
for i in range(len(a) + 1)]
|
| 457 |
+
for i in range(1, len(a) + 1):
|
| 458 |
+
for j in range(1, len(b) + 1):
|
| 459 |
+
dp[i][j] = min(
|
| 460 |
+
dp[i - 1][j] + 1,
|
| 461 |
+
dp[i][j - 1] + 1,
|
| 462 |
+
dp[i - 1][j - 1] + (a[i - 1] != b[j - 1]),
|
| 463 |
+
)
|
| 464 |
+
return dp[-1][-1]
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def lot_similarity(ocr_lot: str, target_lot: str) -> float:
|
| 468 |
+
a = ocr_lot.strip()
|
| 469 |
+
b = target_lot.strip()
|
| 470 |
+
if not a or not b:
|
| 471 |
+
return 0.0
|
| 472 |
+
dist = edit_distance(a, b)
|
| 473 |
+
return 1 - dist / max(len(a), len(b))
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def is_centered(line: Line, img_w: int, img_h: int, tolerance_ratio: float = 0.15) -> bool:
|
| 477 |
+
"""
|
| 478 |
+
A line is considered centered if it is centered both horizontally and vertically
|
| 479 |
+
within the given tolerance.
|
| 480 |
+
"""
|
| 481 |
+
img_cx = img_w / 2
|
| 482 |
+
img_cy = img_h / 2
|
| 483 |
+
dx = abs(line.cx - img_cx)
|
| 484 |
+
dy = abs(line.cy - img_cy)
|
| 485 |
+
return dx <= tolerance_ratio * img_w and dy <= tolerance_ratio * img_h
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def choose_block_for_lot(blocks, target_lot: str, img_w: int, img_h: int):
|
| 489 |
+
"""
|
| 490 |
+
Apply heuristics with zero-padding logic:
|
| 491 |
+
1. Check for exact match using 0-padded lot numbers (e.g. "001" == "001").
|
| 492 |
+
2. If no exact match, prefer a block that is centered both horizontally and vertically.
|
| 493 |
+
"""
|
| 494 |
+
exact_matches = []
|
| 495 |
+
centered_blocks = []
|
| 496 |
+
|
| 497 |
+
# Target lot is expected to be passed in as a 3-digit zero-padded string already
|
| 498 |
+
# but we ensure consistency here just in case.
|
| 499 |
+
if target_lot.isdigit():
|
| 500 |
+
target_lot_compare = f"{int(target_lot):03d}"
|
| 501 |
+
else:
|
| 502 |
+
target_lot_compare = target_lot
|
| 503 |
+
|
| 504 |
+
for idx, b in enumerate(blocks):
|
| 505 |
+
ocr_lot = b["lot_line"].text.strip()
|
| 506 |
+
|
| 507 |
+
# Normalize OCR output to 3-digit zero-padded for comparison
|
| 508 |
+
if ocr_lot.isdigit():
|
| 509 |
+
ocr_lot_compare = f"{int(ocr_lot):03d}"
|
| 510 |
+
else:
|
| 511 |
+
ocr_lot_compare = ocr_lot
|
| 512 |
+
|
| 513 |
+
sim = lot_similarity(ocr_lot_compare, target_lot_compare)
|
| 514 |
+
centered = is_centered(b["lot_line"], img_w, img_h)
|
| 515 |
+
|
| 516 |
+
# 1) Exact lot number match (padded) → always keep, regardless of position
|
| 517 |
+
if ocr_lot_compare == target_lot_compare:
|
| 518 |
+
exact_matches.append(b)
|
| 519 |
+
continue
|
| 520 |
+
|
| 521 |
+
# 2) Non-exact, but potentially useful candidate
|
| 522 |
+
if centered:
|
| 523 |
+
centered_blocks.append((sim, b))
|
| 524 |
+
|
| 525 |
+
# 1) If we have exact matches, choose the one closest to center as a tie-breaker
|
| 526 |
+
if exact_matches:
|
| 527 |
+
exact_matches.sort(
|
| 528 |
+
key=lambda blk: (
|
| 529 |
+
abs(blk["lot_line"].cx - img_w / 2),
|
| 530 |
+
abs(blk["lot_line"].cy - img_h / 2),
|
| 531 |
+
)
|
| 532 |
+
)
|
| 533 |
+
chosen = exact_matches[0]
|
| 534 |
+
return chosen
|
| 535 |
+
|
| 536 |
+
# 2) No exact match → pick the most centered (Fallback logic)
|
| 537 |
+
if centered_blocks:
|
| 538 |
+
img_center_x = img_w / 2
|
| 539 |
+
img_center_y = img_h / 2
|
| 540 |
+
centered_blocks.sort(
|
| 541 |
+
key=lambda sb: (
|
| 542 |
+
abs(sb[1]["lot_line"].cx - img_center_x)
|
| 543 |
+
+ abs(sb[1]["lot_line"].cy - img_center_y),
|
| 544 |
+
-sb[0],
|
| 545 |
+
)
|
| 546 |
+
)
|
| 547 |
+
chosen_sim, chosen = centered_blocks[0]
|
| 548 |
+
return chosen
|
| 549 |
+
|
| 550 |
+
return None
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def parse_date_str(s: str) -> _date | None:
|
| 554 |
+
try:
|
| 555 |
+
return _dt.strptime(s.strip(), "%d/%m/%Y").date()
|
| 556 |
+
except ValueError:
|
| 557 |
+
return None
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def _current_season_bounds(today: Optional[_date] = None) -> tuple[_date, _date]:
|
| 561 |
+
"""
|
| 562 |
+
Compute the [min_date, max_date] for the current Autumn/Winter season.
|
| 563 |
+
"""
|
| 564 |
+
if today is None:
|
| 565 |
+
today = _dt.now().date()
|
| 566 |
+
|
| 567 |
+
y = today.year
|
| 568 |
+
m = today.month
|
| 569 |
+
|
| 570 |
+
if m in (1, 2):
|
| 571 |
+
# Season started last year (Sep) and ends this Feb (with leap handling)
|
| 572 |
+
season_start_year = y - 1
|
| 573 |
+
season_end_year = y
|
| 574 |
+
elif 3 <= m <= 8:
|
| 575 |
+
# Use upcoming season: Sep this year → Feb next year
|
| 576 |
+
season_start_year = y
|
| 577 |
+
season_end_year = y + 1
|
| 578 |
+
else: # 9–12
|
| 579 |
+
# Season started this Sep and ends next Feb
|
| 580 |
+
season_start_year = y
|
| 581 |
+
season_end_year = y + 1
|
| 582 |
+
|
| 583 |
+
season_min = _date(season_start_year, 9, 1)
|
| 584 |
+
|
| 585 |
+
# End-of-Feb with leap year handling
|
| 586 |
+
if (season_end_year % 4 == 0 and season_end_year % 100 != 0) or (season_end_year % 400 == 0):
|
| 587 |
+
feb_last_day = 29
|
| 588 |
+
else:
|
| 589 |
+
feb_last_day = 28
|
| 590 |
+
season_max = _date(season_end_year, 2, feb_last_day)
|
| 591 |
+
|
| 592 |
+
return season_min, season_max
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def _clamp_and_fix_consecutive_dates(
|
| 596 |
+
dates: list[_date],
|
| 597 |
+
max_shift_days: int = MAX_OCR_DAY_SHIFT,
|
| 598 |
+
) -> list[_date]:
|
| 599 |
+
"""
|
| 600 |
+
Attempt to correct OCR date errors given season bounds and consecutiveness.
|
| 601 |
+
"""
|
| 602 |
+
if not dates:
|
| 603 |
+
return []
|
| 604 |
+
|
| 605 |
+
season_min, season_max = _current_season_bounds()
|
| 606 |
+
|
| 607 |
+
# Sort dates as recognized
|
| 608 |
+
dates_sorted = sorted(dates)
|
| 609 |
+
|
| 610 |
+
# Clamp to season range with small shifts only
|
| 611 |
+
fixed = []
|
| 612 |
+
for d in dates_sorted:
|
| 613 |
+
if d < season_min:
|
| 614 |
+
delta = (season_min - d).days
|
| 615 |
+
if delta <= max_shift_days:
|
| 616 |
+
d = season_min
|
| 617 |
+
else:
|
| 618 |
+
continue
|
| 619 |
+
elif d > season_max:
|
| 620 |
+
delta = (d - season_max).days
|
| 621 |
+
if delta <= max_shift_days:
|
| 622 |
+
d = season_max
|
| 623 |
+
else:
|
| 624 |
+
continue
|
| 625 |
+
fixed.append(d)
|
| 626 |
+
|
| 627 |
+
if not fixed:
|
| 628 |
+
return []
|
| 629 |
+
|
| 630 |
+
fixed.sort()
|
| 631 |
+
|
| 632 |
+
# Enforce consecutiveness: treat first date as anchor, then +1 day increments
|
| 633 |
+
anchor = fixed[0]
|
| 634 |
+
consecutive = [anchor]
|
| 635 |
+
for i in range(1, len(fixed)):
|
| 636 |
+
expected = consecutive[-1] + datetime.timedelta(days=1)
|
| 637 |
+
diff = abs((fixed[i] - expected).days)
|
| 638 |
+
if diff <= max_shift_days:
|
| 639 |
+
consecutive.append(expected)
|
| 640 |
+
else:
|
| 641 |
+
break
|
| 642 |
+
|
| 643 |
+
# Final sanity: ensure all inside [season_min, season_max]
|
| 644 |
+
consecutive = [d for d in consecutive if season_min <= d <= season_max]
|
| 645 |
+
return consecutive
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
def extract_dates_from_block(block):
|
| 649 |
+
dates: list[_date] = []
|
| 650 |
+
for dline in block["date_lines"]:
|
| 651 |
+
dt = parse_date_str(dline.text)
|
| 652 |
+
if not dt:
|
| 653 |
+
continue
|
| 654 |
+
dates.append(dt)
|
| 655 |
+
|
| 656 |
+
dates_fixed = _clamp_and_fix_consecutive_dates(dates)
|
| 657 |
+
return dates_fixed
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
def extract_lot_dates_from_output(
|
| 661 |
+
output_texts,
|
| 662 |
+
target_lot: str,
|
| 663 |
+
image: Image.Image,
|
| 664 |
+
):
|
| 665 |
+
if isinstance(output_texts, list):
|
| 666 |
+
text = output_texts[0]
|
| 667 |
+
else:
|
| 668 |
+
text = output_texts
|
| 669 |
+
|
| 670 |
+
img_w, img_h = image.size
|
| 671 |
+
lines = parse_compact_ocr_string(text, img_w, img_h)
|
| 672 |
+
|
| 673 |
+
if not lines:
|
| 674 |
+
return None
|
| 675 |
+
|
| 676 |
+
labels = cluster_lines_into_labels(lines, img_w, img_h)
|
| 677 |
+
blocks = build_blocks_from_labels(labels)
|
| 678 |
+
|
| 679 |
+
if not blocks:
|
| 680 |
+
return None
|
| 681 |
+
|
| 682 |
+
# Pass the already padded target_lot to the block chooser
|
| 683 |
+
chosen = choose_block_for_lot(blocks, target_lot, img_w, img_h)
|
| 684 |
+
if chosen is None:
|
| 685 |
+
return None
|
| 686 |
+
|
| 687 |
+
dates = extract_dates_from_block(chosen)
|
| 688 |
+
if not dates:
|
| 689 |
+
return None
|
| 690 |
+
|
| 691 |
+
return {
|
| 692 |
+
"lot_ocr": chosen["lot_line"].text.strip(),
|
| 693 |
+
"lot_centered": is_centered(chosen["lot_line"], img_w, img_h),
|
| 694 |
+
"dates": dates,
|
| 695 |
+
"bbox_lot": (
|
| 696 |
+
chosen["lot_line"].x1,
|
| 697 |
+
chosen["lot_line"].y1,
|
| 698 |
+
chosen["lot_line"].x2,
|
| 699 |
+
chosen["lot_line"].y2,
|
| 700 |
+
),
|
| 701 |
+
}
|
| 702 |
+
|
| 703 |
+
# ================================
|
| 704 |
+
# --- HunyuanOCR wrapper (reused) ---
|
| 705 |
+
# ================================
|
| 706 |
+
|
| 707 |
+
class HunyuanOCR:
|
| 708 |
+
"""
|
| 709 |
+
Lightweight wrapper to load the model/processor once
|
| 710 |
+
and run inference for many tiles.
|
| 711 |
+
"""
|
| 712 |
+
def __init__(self, model_name_or_path: str = HUNYUAN_MODEL_NAME):
|
| 713 |
+
print(f"Loading HunyuanOCR model '{model_name_or_path}'...")
|
| 714 |
+
self.processor = AutoProcessor.from_pretrained(model_name_or_path, use_fast=False)
|
| 715 |
+
self.model = HunYuanVLForConditionalGeneration.from_pretrained(
|
| 716 |
+
model_name_or_path,
|
| 717 |
+
attn_implementation="eager",
|
| 718 |
+
torch_dtype=torch.bfloat16, # explicit
|
| 719 |
+
).to("cuda")
|
| 720 |
+
print("HunyuanOCR model loaded.")
|
| 721 |
+
|
| 722 |
+
def run(self, image_path: str = None, image: Image.Image = None):
|
| 723 |
+
"""
|
| 724 |
+
You can either pass an image_path (on-disk PNG) or a PIL.Image via `image`.
|
| 725 |
+
"""
|
| 726 |
+
if image is None and image_path is None:
|
| 727 |
+
raise ValueError("Either image_path or image must be provided.")
|
| 728 |
+
|
| 729 |
+
processor = self.processor
|
| 730 |
+
model = self.model
|
| 731 |
+
|
| 732 |
+
if image is None:
|
| 733 |
+
image_inputs = Image.open(image_path)
|
| 734 |
+
else:
|
| 735 |
+
image_inputs = image
|
| 736 |
+
|
| 737 |
+
# For the chat template, we still need an identifier for the image.
|
| 738 |
+
image_identifier = image_path if image_path is not None else "in-memory.png"
|
| 739 |
+
|
| 740 |
+
messages1 = [
|
| 741 |
+
{
|
| 742 |
+
"role": "user",
|
| 743 |
+
"content": [
|
| 744 |
+
{"type": "image", "image": image_identifier},
|
| 745 |
+
{
|
| 746 |
+
"type": "text",
|
| 747 |
+
"text": (
|
| 748 |
+
"Detect and recognize text in the image, "
|
| 749 |
+
"and output the text coordinates in a formatted manner."
|
| 750 |
+
),
|
| 751 |
+
},
|
| 752 |
+
],
|
| 753 |
+
}
|
| 754 |
+
]
|
| 755 |
+
messages = [messages1]
|
| 756 |
+
texts = [
|
| 757 |
+
processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True)
|
| 758 |
+
for msg in messages
|
| 759 |
+
]
|
| 760 |
+
|
| 761 |
+
inputs = processor(
|
| 762 |
+
text=texts,
|
| 763 |
+
images=image_inputs,
|
| 764 |
+
padding=True,
|
| 765 |
+
return_tensors="pt",
|
| 766 |
+
)
|
| 767 |
+
|
| 768 |
+
with torch.no_grad():
|
| 769 |
+
device = next(model.parameters()).device
|
| 770 |
+
inputs = inputs.to(device)
|
| 771 |
+
generated_ids = model.generate(
|
| 772 |
+
**inputs,
|
| 773 |
+
max_new_tokens=256,
|
| 774 |
+
do_sample=False,
|
| 775 |
+
)
|
| 776 |
+
|
| 777 |
+
if "input_ids" in inputs:
|
| 778 |
+
input_ids = inputs.input_ids
|
| 779 |
+
else:
|
| 780 |
+
input_ids = inputs.inputs
|
| 781 |
+
|
| 782 |
+
generated_ids_trimmed = [
|
| 783 |
+
out_ids[len(in_ids):] for in_ids, out_ids in zip(input_ids, generated_ids)
|
| 784 |
+
]
|
| 785 |
+
output_texts = clean_repeated_substrings(
|
| 786 |
+
processor.batch_decode(
|
| 787 |
+
generated_ids_trimmed,
|
| 788 |
+
skip_special_tokens=True,
|
| 789 |
+
clean_up_tokenization_spaces=False,
|
| 790 |
+
)
|
| 791 |
+
)
|
| 792 |
+
return image_inputs, output_texts
|
| 793 |
+
|
| 794 |
+
# ================================
|
| 795 |
+
# --- Main Processing Logic (Hunyuan + Super-res) ---
|
| 796 |
+
# ================================
|
| 797 |
+
|
| 798 |
+
def get_hunt_dates_with_ocr(df: pd.DataFrame) -> pd.DataFrame:
|
| 799 |
+
"""
|
| 800 |
+
Main function to extract hunting dates using:
|
| 801 |
+
- WMS tiles (512x512)
|
| 802 |
+
- 4x super-resolution via DRLN (in-memory)
|
| 803 |
+
- HunyuanOCR for OCR
|
| 804 |
+
"""
|
| 805 |
+
ensure_directory(TILES_DIR)
|
| 806 |
+
|
| 807 |
+
print("\nStep 1: Downloading and preparing tiles...")
|
| 808 |
+
for _, row in tqdm(df.iterrows(), total=df.shape[0], desc="Preparing Tiles"):
|
| 809 |
+
lot_num = int(row['lot'])
|
| 810 |
+
|
| 811 |
+
if row['bbox'] and not tile_uptodate(lot_num):
|
| 812 |
+
success = download_tile(lot_num, row['bbox'])
|
| 813 |
+
if not success:
|
| 814 |
+
print(f"Warning: Failed to download tile for lot {lot_num}")
|
| 815 |
+
|
| 816 |
+
# Initialize models once
|
| 817 |
+
try:
|
| 818 |
+
sr_model = SuperResolutionWrapper(SUPERRES_MODEL_NAME, SUPERRES_SCALE)
|
| 819 |
+
except Exception as e:
|
| 820 |
+
print(f"\nFATAL ERROR during super-resolution initialization: {e}")
|
| 821 |
+
exit(1)
|
| 822 |
+
|
| 823 |
+
try:
|
| 824 |
+
ocr = HunyuanOCR(HUNYUAN_MODEL_NAME)
|
| 825 |
+
except Exception as e:
|
| 826 |
+
print(f"\nFATAL ERROR during HunyuanOCR initialization: {e}")
|
| 827 |
+
exit(1)
|
| 828 |
+
|
| 829 |
+
all_dates: List[List[str]] = []
|
| 830 |
+
stats = {
|
| 831 |
+
'total_lots': len(df),
|
| 832 |
+
'lots_with_dates': 0,
|
| 833 |
+
'failed_lots': 0,
|
| 834 |
+
'no_tile': 0,
|
| 835 |
+
'tile_load_failed': 0,
|
| 836 |
+
'sr_failed': 0,
|
| 837 |
+
}
|
| 838 |
+
|
| 839 |
+
print("\nStep 2: Running super-resolution + HunyuanOCR...")
|
| 840 |
+
|
| 841 |
+
for _, row in tqdm(df.iterrows(), total=df.shape[0], desc="Extracting Dates"):
|
| 842 |
+
lot_number = int(row['lot'])
|
| 843 |
+
|
| 844 |
+
# 1. Format target lot as 3-digit zero-padded string for consistent comparison
|
| 845 |
+
# e.g. lot 1 becomes "001"
|
| 846 |
+
lot_str = f"{lot_number:03d}"
|
| 847 |
+
tile_path = get_tile_path(lot_number)
|
| 848 |
+
|
| 849 |
+
print(f"\n--- Processing Lot {lot_str} ---")
|
| 850 |
+
|
| 851 |
+
if not os.path.exists(tile_path):
|
| 852 |
+
print(" > Status: Tile not found.")
|
| 853 |
+
all_dates.append([])
|
| 854 |
+
stats['failed_lots'] += 1
|
| 855 |
+
stats['no_tile'] += 1
|
| 856 |
+
continue
|
| 857 |
+
|
| 858 |
+
# Light check the original tile with cv2
|
| 859 |
+
test_image = load_image_safe(tile_path)
|
| 860 |
+
if test_image is None:
|
| 861 |
+
print(" > Status: Tile exists but cannot be loaded (cv2 test failed).")
|
| 862 |
+
all_dates.append([])
|
| 863 |
+
stats['failed_lots'] += 1
|
| 864 |
+
stats['tile_load_failed'] += 1
|
| 865 |
+
continue
|
| 866 |
+
|
| 867 |
+
# Super-res: in-memory upscaling only
|
| 868 |
+
ocr_image_pil: Optional[Image.Image] = sr_model.upscale_image(tile_path)
|
| 869 |
+
|
| 870 |
+
if ocr_image_pil is None:
|
| 871 |
+
print(" > Status: Super-resolution failed; falling back to original tile.")
|
| 872 |
+
stats['sr_failed'] += 1
|
| 873 |
+
ocr_input_path = tile_path
|
| 874 |
+
else:
|
| 875 |
+
ocr_input_path = None
|
| 876 |
+
|
| 877 |
+
try:
|
| 878 |
+
if ocr_image_pil is not None:
|
| 879 |
+
# OCR from in-memory PIL image
|
| 880 |
+
image_pil, output_texts = ocr.run(image=ocr_image_pil)
|
| 881 |
+
else:
|
| 882 |
+
# OCR from file path (original)
|
| 883 |
+
image_pil, output_texts = ocr.run(image_path=ocr_input_path)
|
| 884 |
+
except Exception as e:
|
| 885 |
+
print(f" > HunyuanOCR inference error: {e}")
|
| 886 |
+
all_dates.append([])
|
| 887 |
+
stats['failed_lots'] += 1
|
| 888 |
+
# Cleanup
|
| 889 |
+
if ocr_image_pil: del ocr_image_pil
|
| 890 |
+
continue
|
| 891 |
+
|
| 892 |
+
# Pass the zero-padded lot_str and both dimensions to the extraction function
|
| 893 |
+
result = extract_lot_dates_from_output(output_texts, lot_str, image_pil)
|
| 894 |
+
|
| 895 |
+
if result is None:
|
| 896 |
+
print(" > Status: No valid dates found for this lot.")
|
| 897 |
+
all_dates.append([])
|
| 898 |
+
stats['failed_lots'] += 1
|
| 899 |
+
else:
|
| 900 |
+
print(" > Status: Dates found.")
|
| 901 |
+
|
| 902 |
+
chosen_lot = result['lot_ocr']
|
| 903 |
+
dates_objs: List[_date] = result['dates']
|
| 904 |
+
dates_strs = [d.strftime("%d/%m/%Y") for d in dates_objs]
|
| 905 |
+
|
| 906 |
+
# --- Console Output for Verification ---
|
| 907 |
+
print(f" > Real Lot: {lot_str}")
|
| 908 |
+
print(f" > OCR Lot : {chosen_lot}")
|
| 909 |
+
print(f" > Dates : {dates_strs}")
|
| 910 |
+
|
| 911 |
+
# Normalize detected lot for warning check
|
| 912 |
+
chosen_lot_padded = chosen_lot
|
| 913 |
+
if chosen_lot.isdigit():
|
| 914 |
+
chosen_lot_padded = f"{int(chosen_lot):03d}"
|
| 915 |
+
|
| 916 |
+
if lot_str != chosen_lot_padded:
|
| 917 |
+
print(f" > Warning : OCR lot ({chosen_lot}) != Real lot ({lot_str}) [Used centered block]")
|
| 918 |
+
|
| 919 |
+
all_dates.append(dates_strs)
|
| 920 |
+
stats['lots_with_dates'] += 1
|
| 921 |
+
|
| 922 |
+
# Explicit memory cleanup
|
| 923 |
+
if 'ocr_image_pil' in locals() and ocr_image_pil:
|
| 924 |
+
del ocr_image_pil
|
| 925 |
+
if 'image_pil' in locals() and image_pil:
|
| 926 |
+
del image_pil
|
| 927 |
+
|
| 928 |
+
print("\n=== HunyuanOCR + Super-resolution Summary ===")
|
| 929 |
+
print(f"Total lots processed: {stats['total_lots']}")
|
| 930 |
+
print(f"Lots with dates found: {stats['lots_with_dates']}")
|
| 931 |
+
print(f"Failed (no tile): {stats['no_tile']}")
|
| 932 |
+
print(f"Failed (tile load error): {stats['tile_load_failed']}")
|
| 933 |
+
print(f"Failed (super-resolution errors): {stats['sr_failed']}")
|
| 934 |
+
print(f"Failed (other): {stats['failed_lots'] - stats['no_tile'] - stats['tile_load_failed']}")
|
| 935 |
+
success_rate = (stats['lots_with_dates'] / stats['total_lots']) * 100 if stats['total_lots'] > 0 else 0
|
| 936 |
+
print(f"Success Rate: {success_rate:.1f}%")
|
| 937 |
+
|
| 938 |
+
df['dates'] = all_dates
|
| 939 |
+
return df
|
| 940 |
+
|
| 941 |
+
# ================================
|
| 942 |
+
# --- Main Execution ---
|
| 943 |
+
# ================================
|
| 944 |
+
|
| 945 |
+
if __name__ == "__main__":
|
| 946 |
+
REQUIRED_COLUMNS = ['lot', 'polygon', 'centroid', 'bbox', 'dates']
|
| 947 |
+
|
| 948 |
+
# --- Part 1: Get Lot Data ---
|
| 949 |
+
if file_uptodate(BASE_LOTS_FILE, days=30, required_columns=['lot', 'polygon', 'centroid', 'bbox']):
|
| 950 |
+
print(f"Using recent lot data from '{BASE_LOTS_FILE}'")
|
| 951 |
+
df_lots = pd.read_csv(
|
| 952 |
+
BASE_LOTS_FILE,
|
| 953 |
+
converters={
|
| 954 |
+
'polygon': safe_literal_eval,
|
| 955 |
+
'centroid': safe_literal_eval,
|
| 956 |
+
'bbox': safe_literal_eval
|
| 957 |
+
}
|
| 958 |
+
)
|
| 959 |
+
else:
|
| 960 |
+
print("Lot data is outdated or missing. Fetching new data...")
|
| 961 |
+
df_lots = update_lots(API_URL)
|
| 962 |
+
if df_lots.empty:
|
| 963 |
+
print("Failed to get lot data. Exiting.")
|
| 964 |
+
exit(1)
|
| 965 |
+
|
| 966 |
+
# --- Part 2: Get Hunt Dates ---
|
| 967 |
+
if file_uptodate(DATES_FILE, days=1, required_columns=REQUIRED_COLUMNS):
|
| 968 |
+
print(f"\nUsing recent hunting dates from '{DATES_FILE}'")
|
| 969 |
+
df_dates = pd.read_csv(
|
| 970 |
+
DATES_FILE,
|
| 971 |
+
converters={
|
| 972 |
+
'dates': safe_literal_eval,
|
| 973 |
+
'polygon': safe_literal_eval,
|
| 974 |
+
'centroid': safe_literal_eval,
|
| 975 |
+
'bbox': safe_literal_eval
|
| 976 |
+
}
|
| 977 |
+
)
|
| 978 |
+
else:
|
| 979 |
+
print("\nHunting dates file is outdated or missing. Running HunyuanOCR + super-resolution process...")
|
| 980 |
+
df_dates = get_hunt_dates_with_ocr(df_lots.copy())
|
| 981 |
+
|
| 982 |
+
df_save = df_dates.copy()
|
| 983 |
+
df_save['dates'] = df_save['dates'].apply(lambda d: tuple(d) if isinstance(d, list) else ())
|
| 984 |
+
df_save[REQUIRED_COLUMNS].to_csv(DATES_FILE, index=False)
|
| 985 |
+
print(f"\nSaved latest hunting dates to '{DATES_FILE}'")
|
| 986 |
+
|
| 987 |
+
# --- Part 3: Display Results ---
|
| 988 |
+
print("\n--- Final Results ---")
|
| 989 |
+
|
| 990 |
+
df_dates['has_dates'] = df_dates['dates'].apply(lambda d: isinstance(d, (list, tuple)) and len(d) > 0)
|
| 991 |
+
lots_with_dates = df_dates[df_dates['has_dates']].copy()
|
| 992 |
+
|
| 993 |
+
print(f"Found dates for {len(lots_with_dates)} / {len(df_dates)} lots.")
|
| 994 |
+
|
| 995 |
+
if not lots_with_dates.empty:
|
| 996 |
+
print("\nFirst 15 lots with dates found:")
|
| 997 |
+
for _, row in lots_with_dates.head(15).iterrows():
|
| 998 |
+
dates = row['dates'] if isinstance(row['dates'], list) else list(row['dates'])
|
| 999 |
+
print(f"Lot {row['lot']:03d}: {dates}")
|
| 1000 |
+
else:
|
| 1001 |
+
print("\nNo hunting dates were found for any lots.")
|
| 1002 |
+
print("\nTroubleshooting:")
|
| 1003 |
+
print("1. Check that tiles are downloaded in tiles/")
|
| 1004 |
+
print("2. Check GPU memory usage for DRLN and HunyuanOCR")
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
folium
|
| 2 |
+
gpxpy
|
| 3 |
+
gradio
|
| 4 |
+
lxml
|
| 5 |
+
pandas
|
| 6 |
+
shapely
|