Repository navigation
Expand file tree
/
Copy pathweb_interface.py
More file actions
1918 lines (1752 loc) · 102 KB
/
Copy pathweb_interface.py
File metadata and controls
1918 lines (1752 loc) · 102 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
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
FastAPI Web Interface
- Web UI that consumes the MCP server
- Handles web-specific concerns and user interface
- Communicates with MCP server via HTTP
"""
import json
import asyncio
from pathlib import Path
from typing import List, Dict, Any, Optional
from fastapi import FastAPI, Request, Form, HTTPException, Query
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from starlette.middleware.base import BaseHTTPMiddleware
import uvicorn
import httpx
import os
# Import configuration
from config import WEB_CONFIG, BASE_DIR, IMAGES_DIR, IMAGES_TRY_SPECIES_FIRST
class WebInterface:
"""Web interface that consumes the MCP server"""
def __init__(self):
self.app = FastAPI(title="AIFARMS Web Interface", version="2.0.0")
self.mcp_server_url = WEB_CONFIG["mcp_server_url"]
# Serve static files (e.g. logo)
_static_dir = Path(__file__).resolve().parent / "static"
if _static_dir.exists():
self.app.mount("/static", StaticFiles(directory=str(_static_dir)), name="static")
# Setup middleware and routes
self._setup_middleware()
self._setup_routes()
self._setup_templates()
print(f"🌐 Initialized Web Interface")
print(f"🔗 MCP Server URL: {self.mcp_server_url}")
def _setup_middleware(self):
"""Setup CORS and other middleware"""
# Return 404 for common scanner/probe paths (reduces log noise from bots)
_PROBE_PATHS = frozenset({
"/s3.yml", "/s3.yaml", "/s3.properties", "/s3.key", "/s3.secret",
"/aws_s3_config.json", "/.env.aws", "/.env.bak", "/s3/.env.bak",
})
class BlockProbePathsMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
path = request.url.path.rstrip("/") or "/"
if path in _PROBE_PATHS or path.startswith("/s3/"):
return JSONResponse(status_code=404, content={"detail": "Not Found"})
return await call_next(request)
self.app.add_middleware(BlockProbePathsMiddleware)
self.app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def _setup_routes(self):
"""Setup web interface routes"""
@self.app.get("/health")
async def health():
"""Quick check that the web server is up (no MCP dependency)."""
return {"status": "ok", "service": "web_interface"}
@self.app.get("/", response_class=HTMLResponse)
async def home(request: Request):
"""Home page with search interface"""
try:
# Get available filters from MCP server (timeout so page still loads if MCP is down)
async with httpx.AsyncClient(timeout=5.0) as client:
response = await client.get(f"{self.mcp_server_url}/api/datasets")
datasets_data = response.json()
raw_list = datasets_data.get("datasets") if isinstance(datasets_data, dict) else []
datasets_list = self._normalize_datasets_for_template(raw_list)
all_filters = self._extract_filters_from_datasets(raw_list if isinstance(raw_list, list) else [])
# Count by type for UI (so user can see if wildlife/plants etc. loaded)
by_type = {}
for d in datasets_list:
t = (d.get("type") or "unknown").strip().lower() or "unknown"
by_type[t] = by_type.get(t, 0) + 1
datasets_by_type = dict(sorted(by_type.items()))
return self.templates.TemplateResponse(request, "search_interface.html", {
"request": request,
"filters": all_filters,
"datasets": datasets_list,
"datasets_by_type": datasets_by_type,
"mcp_server_url": self.mcp_server_url
})
except Exception as e:
print(f"Error loading home page: {e}")
# Return basic interface if MCP server is unavailable
return self.templates.TemplateResponse(request, "search_interface.html", {
"request": request,
"filters": {},
"datasets": [],
"datasets_by_type": {},
"mcp_server_url": self.mcp_server_url,
"error": "MCP server unavailable"
})
@self.app.get("/search", response_class=HTMLResponse)
async def search_page(request: Request):
"""Search results page"""
return self.templates.TemplateResponse(request, "search_results.html", {
"request": request,
"results": {},
"query": "",
"filters": {}
})
@self.app.post("/search", response_class=HTMLResponse)
async def search_images(
request: Request,
query: str = Form(""),
dataset: str = Form(""),
category: List[str] = Form([]),
species: List[str] = Form([]),
time: List[str] = Form([]),
season: List[str] = Form([]),
action: List[str] = Form([]),
plant_state: List[str] = Form([]),
limit: int = Form(50),
page: int = Form(1)
):
"""Handle search form submission"""
try:
print(f"🔍 Web interface search request: query='{query}', dataset='{dataset}'")
# Prepare search request
search_data = {
"query": query,
"dataset": dataset if dataset else None,
"filters": {
"category": category if category else [],
"species": species if species else [],
"time": time if time else [],
"season": season if season else [],
"action": action if action else [],
"plant_state": plant_state if plant_state else []
},
"limit": limit,
"offset": (page - 1) * limit
}
print(f"🔍 Calling MCP server with: {search_data}")
# Call MCP server search tool
async with httpx.AsyncClient() as client:
response = await client.post(
f"{self.mcp_server_url}/mcp/tools/search_images",
json=search_data
)
mcp_response = response.json()
print(f"🔍 MCP server response: {mcp_response}")
# Extract the actual results from the MCP response structure
search_results = {}
if "content" in mcp_response:
for content_item in mcp_response["content"]:
if content_item.get("type") == "result" and "data" in content_item:
search_results = content_item["data"]
break
if not search_results:
search_results = {"error": "No results found in MCP response", "mcp_response": mcp_response}
# Add image URLs to the results
if "results" in search_results and search_results["results"]:
for result in search_results["results"]:
result["image_url"] = self._construct_image_url(result)
print(f"🔍 Extracted search results: {search_results}")
# Get filters for the results page
async with httpx.AsyncClient() as client:
response = await client.get(f"{self.mcp_server_url}/api/datasets")
datasets_data = response.json()
all_filters = self._extract_filters_from_datasets(datasets_data["datasets"])
return self.templates.TemplateResponse(request, "search_results.html", {
"request": request,
"results": search_results,
"query": query,
"filters": all_filters,
"datasets": datasets_data["datasets"],
"current_page": page,
"limit": limit
})
except Exception as e:
print(f"❌ Search error: {e}")
import traceback
traceback.print_exc()
return self.templates.TemplateResponse(request, "search_results.html", {
"request": request,
"results": {"error": str(e)},
"query": query,
"filters": {},
"datasets": {},
"current_page": page,
"limit": limit
})
@self.app.post("/llm_search", response_class=HTMLResponse)
async def llm_search_images(
request: Request,
query: str = Form(""),
dataset: str = Form(""),
category: str = Form(""),
limit: int = Form(50),
page: int = Form(1),
dataset_offset: int = Form(0)
):
"""Handle LLM-powered search with intelligent query understanding"""
try:
print(f"🧠 LLM search request: query='{query}', dataset='{dataset}', category='{category}', dataset_offset={dataset_offset}")
# Prepare LLM search request (category restricts by data type: wildlife, domestic_animal, livestock, plants, pests)
search_data = {
"query": query,
"dataset": dataset if dataset else None,
"limit": limit,
"offset": (page - 1) * limit,
"dataset_offset": dataset_offset
}
if category and category.strip():
search_data["category"] = [category.strip()]
print(f"🧠 Calling MCP server LLM search with: {search_data}")
# Call MCP server LLM search tool (long timeout: LLM + dataset search; server caps datasets for broad queries)
llm_search_timeout = httpx.Timeout(30.0, read=300.0) # 5 min read for slow LLM + many datasets
async with httpx.AsyncClient(timeout=llm_search_timeout) as client:
response = await client.post(
f"{self.mcp_server_url}/mcp/tools/llm_search",
json=search_data
)
mcp_response = response.json()
print(f"🧠 MCP server LLM response: {mcp_response}")
# Extract the actual results from the MCP response structure
search_results = {}
if "content" in mcp_response:
for content_item in mcp_response["content"]:
if content_item.get("type") == "result" and "data" in content_item:
search_results = content_item["data"]
break
if not search_results:
search_results = {"error": "No results found in MCP LLM response", "mcp_response": mcp_response}
# Add image URLs to the results and sort by confidence
if "results" in search_results and search_results["results"]:
for result in search_results["results"]:
result["image_url"] = self._construct_image_url(result)
# Sort results by confidence (highest first) if available
if any('llm_confidence' in result for result in search_results["results"]):
search_results["results"].sort(key=lambda x: x.get('llm_confidence', 0), reverse=True)
print(f"🧠 Results sorted by confidence (highest first)")
print(f"🧠 Extracted LLM search results: {search_results}")
# Get filters for the results page
async with httpx.AsyncClient() as client:
response = await client.get(f"{self.mcp_server_url}/api/datasets")
datasets_data = response.json()
raw_list = datasets_data.get("datasets") if isinstance(datasets_data, dict) else []
all_filters = self._extract_filters_from_datasets(raw_list if isinstance(raw_list, list) else [])
datasets_list = self._normalize_datasets_for_template(raw_list)
return self.templates.TemplateResponse(request, "llm_search_results.html", {
"request": request,
"results": search_results,
"query": query,
"dataset": dataset,
"category": category,
"filters": all_filters,
"datasets": datasets_list,
"current_page": page,
"limit": limit,
"dataset_offset": search_results.get("dataset_offset", 0),
"next_dataset_offset": search_results.get("next_dataset_offset", 0),
"total_datasets_matching": search_results.get("total_datasets_matching", 0),
"has_more_datasets": search_results.get("has_more_datasets", False),
})
except Exception as e:
print(f"❌ LLM search error: {e}")
import traceback
traceback.print_exc()
return self.templates.TemplateResponse(request, "llm_search_results.html", {
"request": request,
"results": {"error": str(e)},
"query": query,
"dataset": dataset,
"category": category,
"filters": {},
"datasets": [],
"current_page": page,
"limit": limit,
"dataset_offset": 0,
"next_dataset_offset": 0,
"total_datasets_matching": 0,
"has_more_datasets": False,
})
@self.app.get("/api/search")
async def api_search(
query: str = "",
dataset: str = "",
category: List[str] = Query([]),
species: List[str] = Query([]),
time: List[str] = Query([]),
season: List[str] = Query([]),
action: List[str] = Query([]),
plant_state: List[str] = Query([]),
limit: int = Query(50),
offset: int = Query(0)
):
"""API endpoint for search"""
try:
search_data = {
"query": query,
"dataset": dataset if dataset else None,
"filters": {
"category": category if category else [],
"species": species if species else [],
"time": time if time else [],
"season": season if season else [],
"action": action if action else [],
"plant_state": plant_state if plant_state else []
},
"limit": limit,
"offset": offset
}
async with httpx.AsyncClient() as client:
response = await client.post(
f"{self.mcp_server_url}/mcp/tools/search_images",
json=search_data
)
return response.json()
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@self.app.get("/api/datasets")
async def api_datasets():
"""Get available datasets"""
try:
async with httpx.AsyncClient() as client:
response = await client.get(f"{self.mcp_server_url}/api/datasets")
return response.json()
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@self.app.get("/api/models")
async def api_models():
"""Get available models"""
try:
async with httpx.AsyncClient() as client:
response = await client.get(f"{self.mcp_server_url}/api/models")
return response.json()
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@self.app.post("/api/inference")
async def api_inference(request: Request):
"""Run model inference"""
try:
body = await request.json()
async with httpx.AsyncClient() as client:
response = await client.post(
f"{self.mcp_server_url}/api/inference",
json=body
)
return response.json()
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@self.app.get("/image/{filename:path}")
async def serve_image(filename: str):
"""Serve images from the MCP server"""
try:
# Redirect to MCP server for images
image_url = f"{self.mcp_server_url}/image/{filename}"
return JSONResponse({"image_url": image_url})
except Exception as e:
raise HTTPException(status_code=404, detail="Image not found")
@self.app.get("/croissant_datasets", response_class=HTMLResponse)
async def croissant_datasets(request: Request):
"""Browse discovered Croissant datasets"""
try:
# Call MCP server to get Croissant datasets
async with httpx.AsyncClient(timeout=300.0) as client: # 5 minute timeout for crawling
response = await client.post(
f"{self.mcp_server_url}/mcp/tools/crawl_croissant_datasets",
json={}
)
# Check response status
if response.status_code != 200:
error_detail = response.text
try:
error_json = response.json()
error_detail = error_json.get("detail", error_detail)
except:
pass
print(f"❌ MCP server returned error {response.status_code}: {error_detail}")
return self.templates.TemplateResponse(request, "croissant_datasets.html", {
"request": request,
"datasets": [],
"total_count": 0,
"error": f"MCP server error ({response.status_code}): {error_detail}"
})
mcp_response = response.json()
# Extract datasets from MCP response
datasets = []
# Handle MCP format response (wrapped by tool registry)
if "content" in mcp_response:
for content_item in mcp_response["content"]:
if content_item.get("type") == "result" and "data" in content_item:
data = content_item["data"]
# Check for datasets in the data
if "datasets" in data:
datasets = data["datasets"]
break
# Also check if data itself is a dict with datasets at root
elif isinstance(data, dict) and "datasets" in data:
datasets = data["datasets"]
break
# Also check if datasets are in the response root (direct format)
if not datasets and "datasets" in mcp_response:
datasets = mcp_response["datasets"]
# Debug: log what we got
if not datasets:
print(f"⚠️ No datasets found in response. Response keys: {list(mcp_response.keys())}")
if "detail" in mcp_response:
print(f"⚠️ Error detail: {mcp_response['detail']}")
if "content" in mcp_response:
for i, item in enumerate(mcp_response["content"]):
print(f" Content item {i}: type={item.get('type')}, keys={list(item.keys())}")
if "data" in item:
print(f" Data keys: {list(item['data'].keys())}")
print(f" Data: {item['data']}")
error_msg = None
if "detail" in mcp_response:
error_msg = mcp_response["detail"]
return self.templates.TemplateResponse(request, "croissant_datasets.html", {
"request": request,
"datasets": datasets,
"total_count": len(datasets),
"error": error_msg
})
except httpx.TimeoutException:
error_msg = "Request timed out - the crawler may be taking too long. Try again later."
print(f"❌ Timeout loading Croissant datasets: {error_msg}")
return self.templates.TemplateResponse(request, "croissant_datasets.html", {
"request": request,
"datasets": [],
"total_count": 0,
"error": error_msg
})
except Exception as e:
print(f"❌ Error loading Croissant datasets: {e}")
import traceback
traceback.print_exc()
return self.templates.TemplateResponse(request, "croissant_datasets.html", {
"request": request,
"datasets": [],
"total_count": 0,
"error": str(e)
})
@self.app.get("/debug/search")
async def debug_search():
"""Debug endpoint to test search functionality"""
try:
# Test search with a simple query
search_data = {
"query": "bobcat",
"limit": 5
}
print(f"🔍 Debug search request: {search_data}")
async with httpx.AsyncClient() as client:
response = await client.post(
f"{self.mcp_server_url}/mcp/tools/search_images",
json=search_data
)
mcp_response = response.json()
print(f"🔍 Debug search response: {mcp_response}")
# Extract the actual results from the MCP response structure
search_results = {}
if "content" in mcp_response:
for content_item in mcp_response["content"]:
if content_item.get("type") == "result" and "data" in content_item:
search_results = content_item["data"]
break
if not search_results:
search_results = {"error": "No results found in MCP response", "mcp_response": mcp_response}
# Add image URLs to the results
if "results" in search_results and search_results["results"]:
for result in search_results["results"]:
result["image_url"] = self._construct_image_url(result)
print(f"🔍 Debug extracted results: {search_results}")
return {
"debug_info": "Search test completed",
"request": search_data,
"response": mcp_response,
"extracted_results": search_results,
"mcp_server_url": self.mcp_server_url
}
except Exception as e:
print(f"❌ Debug search error: {e}")
import traceback
traceback.print_exc()
return {
"error": str(e),
"traceback": traceback.format_exc()
}
@self.app.get("/debug/files")
async def debug_files():
"""Debug endpoint to show file structure"""
try:
import os
from pathlib import Path
base_dir = Path("/opt/mcp-data-server")
file_info = {
"base_directory": str(base_dir),
"base_exists": base_dir.exists(),
"base_contents": [],
"image_files": [],
"mcp_files": []
}
if base_dir.exists():
# List base directory contents
for item in base_dir.iterdir():
if item.is_dir():
file_info["base_contents"].append(f"📁 {item.name}/")
# Look for images in subdirectories
for subitem in item.iterdir():
if subitem.suffix.lower() in ['.jpg', '.jpeg', '.png', '.gif']:
file_info["image_files"].append(f"{item.name}/{subitem.name}")
elif item.suffix == '.json':
file_info["mcp_files"].append(item.name)
elif item.suffix.lower() in ['.jpg', '.jpeg', '.png', '.gif']:
file_info["image_files"].append(item.name)
return file_info
except Exception as e:
return {
"error": str(e),
"traceback": traceback.format_exc()
}
@self.app.get("/test/images")
async def test_images():
"""Test endpoint to check if image files exist"""
try:
import os
from pathlib import Path
images_dir = Path(IMAGES_DIR)
test_files = []
if images_dir.exists():
# List first 10 image files
for item in images_dir.iterdir():
if item.suffix.lower() in ['.jpg', '.jpeg', '.png', '.gif']:
test_files.append(item.name)
if len(test_files) >= 10:
break
return {
"images_directory": str(images_dir),
"directory_exists": images_dir.exists(),
"sample_files": test_files,
"total_files": len(list(images_dir.glob("*.jpg"))) if images_dir.exists() else 0
}
except Exception as e:
return {
"error": str(e),
"traceback": traceback.format_exc()
}
@self.app.get("/debug/coyote-images")
async def debug_coyote_images():
"""Debug endpoint to check coyote image file matching"""
try:
import json
from pathlib import Path
# Load coyote dataset
coyote_file = BASE_DIR / "coyote_mcp_data.json"
if not coyote_file.exists():
return {"error": f"Coyote dataset file not found: {coyote_file}"}
with open(coyote_file, 'r') as f:
coyote_data = json.load(f)
images_dir = Path(IMAGES_DIR)
if not images_dir.exists():
return {"error": f"Images directory not found: {images_dir}"}
# Get all image files in directory (case-insensitive)
existing_files = {}
for item in images_dir.iterdir():
if item.suffix.lower() in ['.jpg', '.jpeg', '.png', '.gif']:
# Store both original and lowercase versions for matching
existing_files[item.name.lower()] = item.name
existing_files[item.name] = item.name
# Check first 20 coyote images
coyote_images = coyote_data.get("images", [])[:20]
results = []
missing = []
found = []
for img_entry in coyote_images:
metadata = img_entry.get("metadata", {})
original_filename = metadata.get("original_filename", "")
img_id = img_entry.get("id", "")
# Check if file exists (case-insensitive)
found_file = None
if original_filename:
# Try exact match
if original_filename in existing_files:
found_file = existing_files[original_filename]
# Try case-insensitive match
elif original_filename.lower() in existing_files:
found_file = existing_files[original_filename.lower()]
# Try with different case
else:
# Try all variations
for existing_lower, existing_orig in existing_files.items():
if existing_lower == original_filename.lower():
found_file = existing_orig
break
result = {
"id": img_id,
"original_filename": original_filename,
"expected_path": f"{IMAGES_DIR}/{original_filename}",
"file_exists": found_file is not None,
"actual_filename": found_file
}
if found_file:
found.append(result)
else:
missing.append(result)
results.append(result)
# Get sample of actual files that might be coyote images
sample_files = []
for item in list(images_dir.iterdir())[:50]:
if item.suffix.lower() in ['.jpg', '.jpeg', '.png', '.gif']:
sample_files.append(item.name)
return {
"coyote_dataset_file": str(coyote_file),
"images_directory": str(images_dir),
"total_coyote_entries_checked": len(coyote_images),
"files_found": len(found),
"files_missing": len(missing),
"results": results,
"missing_files": missing,
"found_files": found,
"sample_existing_files": sample_files[:20],
"total_images_in_directory": len([f for f in images_dir.iterdir() if f.suffix.lower() in ['.jpg', '.jpeg', '.png', '.gif']])
}
except Exception as e:
import traceback
return {
"error": str(e),
"traceback": traceback.format_exc()
}
@self.app.get("/images/{filename:path}")
async def serve_image(filename: str):
"""Serve images: order depends on IMAGES_TRY_SPECIES_FIRST (Taiga = subdirs only → try species subdir first)."""
try:
from pathlib import Path
from fastapi.responses import FileResponse
images_dir = Path(IMAGES_DIR)
filename_no_ext = Path(filename).stem
image_path_flat = images_dir / filename
try:
images_dir_resolved = images_dir.resolve()
image_path_flat_resolved = (images_dir_resolved / filename).resolve()
except OSError:
images_dir_resolved = images_dir
image_path_flat_resolved = image_path_flat
flat_to_try = image_path_flat_resolved if image_path_flat_resolved != image_path_flat else image_path_flat
# Use resolved base for species subdirs so we look in the same place as the flat path
images_base = images_dir_resolved
requested_suffix = Path(filename).suffix
def unique_values(values):
seen = set()
unique = []
for value in values:
if value and value not in seen:
seen.add(value)
unique.append(value)
return unique
filename_no_ext_variants = unique_values([
filename_no_ext,
filename_no_ext.replace("-", "_"),
filename_no_ext.replace("ref_leaf", "red_leaf"),
filename_no_ext.replace("ref_leaf", "red_leaf").replace("-", "_"),
])
filename_variants = unique_values(
[filename] +
[f"{stem}{requested_suffix}" for stem in filename_no_ext_variants if requested_suffix]
)
def try_species_subdir():
if "_" not in filename_no_ext:
return None
# Try dataset-name subdir first (e.g. domestic_cat for domestic_cat_001), then first segment
import re
subdir_candidates = []
for stem in filename_no_ext_variants:
if re.search(r"_\d+$", stem):
subdir_candidates.append(re.sub(r"_\d+$", "", stem)) # wild_turkey_001 -> wild_turkey
elif "_" in stem:
subdir_candidates.append(stem) # wild_turkey (no number) -> wild_turkey
subdir_candidates.append(stem.split("_")[0])
subdir_candidates = unique_values(subdir_candidates)
# Case-insensitive subdir match first (e.g. dir is Daktulosphaira_vitifoliae, we have daktulosphaira_vitifoliae)
try:
for candidate in subdir_candidates:
if not candidate:
continue
target_lower = candidate.lower().replace(" ", "_").replace("-", "_")
for child in images_base.iterdir():
if not child.is_dir():
continue
if child.name.lower().replace(" ", "_").replace("-", "_") == target_lower:
for name in filename_variants:
sub_path = child / name
if sub_path.exists() and sub_path.is_file():
return FileResponse(str(sub_path))
for ext in ['.jpg', '.jpeg', '.png', '.gif', '.JPG', '.JPEG', '.PNG', '.GIF']:
for stem in filename_no_ext_variants:
sub_path = child / f"{stem}{ext}"
if sub_path.exists() and sub_path.is_file():
return FileResponse(str(sub_path))
# Fallback: subdir exists but files may be named by number only (e.g. 252.jpg)
num_suffix = re.search(r"(\d+)$", filename_no_ext)
if num_suffix:
for ext in ['.jpg', '.jpeg', '.png', '.gif', '.JPG', '.JPEG', '.PNG', '.GIF']:
sub_path = child / f"{num_suffix.group(1)}{ext}"
if sub_path.exists() and sub_path.is_file():
return FileResponse(str(sub_path))
break # only need first candidate for case-insensitive; then try literal
except OSError:
pass
for subdir in subdir_candidates:
if not subdir:
continue
species_dir = images_base / subdir
for name in filename_variants:
sub_path = species_dir / name
if sub_path.exists() and sub_path.is_file():
return FileResponse(str(sub_path))
for ext in ['.jpg', '.jpeg', '.png', '.gif', '.JPG', '.JPEG', '.PNG', '.GIF']:
for stem in filename_no_ext_variants:
sub_path = species_dir / f"{stem}{ext}"
if sub_path.exists() and sub_path.is_file():
return FileResponse(str(sub_path))
# Fallback: try numeric suffix only in this subdir (e.g. wild_turkey/252.jpg)
num_suffix = re.search(r"(\d+)$", filename_no_ext)
if num_suffix:
for ext in ['.jpg', '.jpeg', '.png', '.gif', '.JPG', '.JPEG', '.PNG', '.GIF']:
sub_path = species_dir / f"{num_suffix.group(1)}{ext}"
if sub_path.exists() and sub_path.is_file():
return FileResponse(str(sub_path))
return None
def try_flat():
if flat_to_try.exists() and flat_to_try.is_file():
return FileResponse(str(flat_to_try))
for name in filename_variants:
flat_variant = images_base / name
if flat_variant.exists() and flat_variant.is_file():
return FileResponse(str(flat_variant))
return None
# Order: species subdir first when Taiga layout (subdirs only), else flat first
if IMAGES_TRY_SPECIES_FIRST:
r = try_species_subdir()
if r is not None:
return r
r = try_flat()
if r is not None:
return r
else:
r = try_flat()
if r is not None:
return r
r = try_species_subdir()
if r is not None:
return r
# Case-insensitive in flat dir
filename_lower = filename.lower()
try:
for item in images_base.iterdir():
if item.is_file() and item.name.lower() in {name.lower() for name in filename_variants}:
return FileResponse(str(item))
except OSError:
pass
# 4) Different extensions in flat dir
for ext in ['.jpg', '.jpeg', '.png', '.gif', '.JPG', '.JPEG', '.PNG', '.GIF']:
for stem in filename_no_ext_variants:
potential_file = images_base / f"{stem}{ext}"
if potential_file.exists() and potential_file.is_file():
return FileResponse(str(potential_file))
# Not found – log why (directory missing vs wrong filenames)
# Use same subdir list as try_species_subdir (e.g. wild_turkey then wild, same as domestic_cat then domestic)
if "_" in filename_no_ext:
import re
subdir_candidates_log = []
if re.search(r"_\d+$", filename_no_ext):
subdir_candidates_log.append(re.sub(r"_\d+$", "", filename_no_ext))
elif "_" in filename_no_ext:
subdir_candidates_log.append(filename_no_ext)
subdir_candidates_log.append(filename_no_ext.split("_")[0])
species_dirs_tried = [images_base / d for d in subdir_candidates_log]
else:
species_dirs_tried = [images_base / filename_no_ext] if filename_no_ext else []
print(f"❌ Image not found: {filename}")
print(f" Flat path resolved: {image_path_flat_resolved} (exists={image_path_flat_resolved.exists()})")
print(f" Tried species subdirs: {species_dirs_tried}")
# Report first candidate we tried (e.g. wild_turkey, domestic_cat) not just first segment
if species_dirs_tried:
first_tried = species_dirs_tried[0]
exists = first_tried.exists() and first_tried.is_dir()
print(f" Species dir exists ({first_tried.name}): {exists}")
if exists:
try:
sample = list(first_tried.iterdir())[:5]
names = [p.name for p in sample if p.is_file()]
print(f" Sample files in {first_tried.name}/: {names}")
except OSError as e:
print(f" (cannot list {first_tried.name}/: {e})")
else:
try:
print(f" Resolved path: {first_tried.resolve()}")
except OSError as e:
print(f" Resolve failed (permissions?): {e}")
print(f" Tried flat: {image_path_flat}")
print(f" Tried case-insensitive and other extensions for: {filename}")
# List files with same prefix (e.g. grapes_*) to see if any exist
prefix = filename_no_ext.split("_")[0] if "_" in filename_no_ext else filename_no_ext
try:
same_prefix = [p.name for p in images_base.iterdir() if p.is_file() and p.name.lower().startswith(prefix.lower() + "_")]
if same_prefix:
print(f" Files with prefix '{prefix}_' in images dir: {same_prefix[:10]}{'...' if len(same_prefix) > 10 else ''}")
else:
print(f" No files with prefix '{prefix}_' in images dir.")
except OSError as e:
print(f" (could not list images dir: {e})")
# List some similar files for debugging
similar_files = []
filename_lower_short = filename_lower[:10]
try:
for item in images_base.iterdir():
if item.is_file() and item.suffix.lower() in ['.jpg', '.jpeg', '.png', '.gif']:
if filename_lower_short in item.name.lower() or item.name.lower().startswith(filename_lower_short):
similar_files.append(item.name)
if len(similar_files) >= 5:
break
except OSError:
pass
error_detail = f"Image not found: {filename}"
if similar_files:
error_detail += f". Similar files found: {', '.join(similar_files[:3])}"
# Fallback: redirect to MCP server /images/ so images on the server (e.g. wild_turkey) still load
if getattr(self, "mcp_server_url", None):
mcp_images_url = f"{self.mcp_server_url.rstrip('/')}/images/{filename}"
print(f"🖼️ Redirecting to MCP server for image: {mcp_images_url}")
return RedirectResponse(url=mcp_images_url, status_code=302)
raise HTTPException(status_code=404, detail=error_detail)
except HTTPException:
raise
except Exception as e:
print(f"❌ Error serving image {filename}: {e}")
import traceback
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@self.app.get("/download/{filename:path}")
async def download_image(filename: str):
"""Download images from the web interface with proper download headers"""
try:
from pathlib import Path
from fastapi.responses import FileResponse
images_dir = Path(IMAGES_DIR)
filename_no_ext = Path(filename).stem
image_path_flat = images_dir / filename
try:
images_dir_resolved = images_dir.resolve()
image_path_flat_resolved = (images_dir_resolved / filename).resolve()
except OSError:
images_dir_resolved = images_dir
image_path_flat_resolved = image_path_flat
disp = lambda n: f'attachment; filename="{n}"'
print(f"📥 Download request for image: {filename}")
flat_to_try = image_path_flat_resolved if image_path_flat_resolved != image_path_flat else image_path_flat
images_base = images_dir_resolved
def _dl_species():
if "_" not in filename_no_ext:
return None
import re
subdir_candidates = []
if re.search(r"_\d+$", filename_no_ext):
subdir_candidates.append(re.sub(r"_\d+$", "", filename_no_ext))
elif "_" in filename_no_ext:
subdir_candidates.append(filename_no_ext)
subdir_candidates.append(filename_no_ext.split("_")[0])
for subdir in subdir_candidates:
if not subdir:
continue
species_dir = images_base / subdir
for p in [species_dir / filename, *(species_dir / f"{filename_no_ext}{e}" for e in ['.jpg', '.jpeg', '.png', '.gif', '.JPG', '.JPEG', '.PNG', '.GIF'])]:
if p.exists() and p.is_file():
return FileResponse(str(p), media_type="application/octet-stream", filename=p.name, headers={"Content-Disposition": disp(p.name)})
# Fallback: numeric suffix only (e.g. wild_turkey/252.jpg)
num_suffix = re.search(r"(\d+)$", filename_no_ext)
if num_suffix:
for e in ['.jpg', '.jpeg', '.png', '.gif', '.JPG', '.JPEG', '.PNG', '.GIF']:
p = species_dir / f"{num_suffix.group(1)}{e}"
if p.exists() and p.is_file():
return FileResponse(str(p), media_type="application/octet-stream", filename=p.name, headers={"Content-Disposition": disp(p.name)})
return None
if IMAGES_TRY_SPECIES_FIRST:
r = _dl_species()
if r is not None:
return r
if flat_to_try.exists() and flat_to_try.is_file():
return FileResponse(str(flat_to_try), media_type="application/octet-stream", filename=filename, headers={"Content-Disposition": disp(filename)})
if not IMAGES_TRY_SPECIES_FIRST:
r = _dl_species()
if r is not None:
return r
# Case-insensitive, then other extensions in flat dir
filename_lower = filename.lower()
try: