Spaces:
Runtime error
Runtime error
Download app.py from KassimYassin/palate: direct link, hf CLI and curl.
- Browser
- Download file 16.6 kB
-
https://huggingface.co/spaces/KassimYassin/palate/resolve/main/app.py
- Command line
-
hf download hf://spaces/KassimYassin/palate/app.py
-
curl -L -o app.py https://huggingface.co/spaces/KassimYassin/palate/resolve/main/app.py
16.6 kB
| """ | |
| Palate / TasteOS Global Multi-City Culinary Engine | |
| Hugging Face Spaces Entry Point (FastAPI + Gradio) | |
| Serves 82,000+ Ground-Truth Kitchens across 8 Global Capitals. | |
| Zero paid Google APIs. | |
| """ | |
| import os | |
| import sys | |
| import json | |
| import urllib.parse | |
| from typing import Optional, List | |
| # Explicitly disable Gradio Server-Side Rendering (SSR) mode to prevent Node.js from binding port 7860 | |
| os.environ["GRADIO_SSR_MODE"] = "false" | |
| from fastapi import FastAPI, Request, Query, HTTPException, Response | |
| from fastapi.responses import FileResponse, JSONResponse, HTMLResponse | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.staticfiles import StaticFiles | |
| from engine import MultiCityEngineManager | |
| from spatial_copilot_service import copilot_service | |
| # Ensure UTF-8 output | |
| if sys.platform == "win32" and hasattr(sys.stdout, "reconfigure"): | |
| sys.stdout.reconfigure(encoding="utf-8") | |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| PUBLIC_DIR = os.path.join(BASE_DIR, "public") | |
| INDEX_PATH = os.path.join(PUBLIC_DIR, "index.html") | |
| manager = MultiCityEngineManager() | |
| app = FastAPI( | |
| title="Palate — Unfiltered Global Culinary Craft", | |
| description="Zero Paid Placements · Zero Fake Reviews · 82,000+ Kitchens Across 8 Global Capitals", | |
| version="2.0.0" | |
| ) | |
| # Enable CORS for external embeds and Cloudflare proxying | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| expose_headers=["X-Total-Count", "X-Offset", "X-Limit"] | |
| ) | |
| # 0. API: List Available Global Cities | |
| def get_cities(): | |
| return manager.list_cities() | |
| # 1. API: Search with Rich Dietary & Amenity Filters | |
| def search_places( | |
| city: str = "amsterdam", | |
| q: str = "", | |
| lat: Optional[float] = None, | |
| lon: Optional[float] = None, | |
| offset: int = 0, | |
| limit: int = 40, | |
| cuisine: Optional[str] = None, | |
| diet: Optional[str] = None, | |
| outdoor: bool = False, | |
| canal: bool = False, | |
| wheelchair: bool = False, | |
| accredited: bool = False, | |
| monument: bool = False, | |
| independent: bool = False, | |
| celiac: bool = False, | |
| scratch: bool = False, | |
| water: bool = False, | |
| clean: bool = False, | |
| late_night: bool = False, | |
| roastery: bool = False, | |
| historic: bool = False, | |
| price: Optional[str] = None, | |
| min_score: int = 0, | |
| sort: str = "quality", | |
| bbox: Optional[str] = None, | |
| max_dist: Optional[int] = None, | |
| facets: bool = False, | |
| response: Response = None | |
| ): | |
| city_id = city.lower().strip() | |
| engine = manager.get_engine(city_id) | |
| default_center = engine.city_config.get("center", {"lat": 52.3680, "lon": 4.8900}) | |
| has_user_coords = lat is not None and lon is not None | |
| user_lat = lat if lat is not None else default_center["lat"] | |
| user_lon = lon if lon is not None else default_center["lon"] | |
| # Normalize celiac diet alias | |
| if diet and diet.lower().strip() in ("celiac", "celiac_safe"): | |
| celiac = True | |
| diet = None | |
| # Parse price tiers (e.g. "1,2") | |
| price_tiers = None | |
| if price: | |
| try: | |
| price_tiers = [int(p.strip()) for p in price.split(",") if p.strip().isdigit()] | |
| if not price_tiers: | |
| price_tiers = None | |
| except Exception: | |
| price_tiers = None | |
| # Parse bounding box | |
| bbox_coords = None | |
| if bbox: | |
| try: | |
| parts = [float(x.strip()) for x in bbox.split(",") if x.strip()] | |
| if len(parts) == 4: | |
| bbox_coords = parts | |
| except Exception: | |
| bbox_coords = None | |
| results, total_count = engine.search( | |
| query=q, | |
| user_lat=user_lat, | |
| user_lon=user_lon, | |
| offset=offset, | |
| max_results=limit, | |
| cuisine=cuisine if cuisine else None, | |
| diet=diet if diet else None, | |
| outdoor=outdoor, | |
| canal=canal, | |
| wheelchair=wheelchair, | |
| accredited_only=accredited, | |
| monuments_only=monument, | |
| independent_only=independent, | |
| celiac_safe_only=celiac, | |
| scratch_only=scratch, | |
| tap_water_only=water, | |
| clean_only=clean, | |
| late_night_only=late_night, | |
| roastery_only=roastery, | |
| historic_only=historic, | |
| price_tiers=price_tiers, | |
| min_score=min_score, | |
| sort_by=sort, | |
| has_user_coords=has_user_coords, | |
| return_total=True, | |
| bbox=bbox_coords, | |
| max_dist_m=max_dist | |
| ) | |
| if response: | |
| response.headers["X-Total-Count"] = str(total_count) | |
| response.headers["X-Offset"] = str(offset) | |
| response.headers["X-Limit"] = str(limit) | |
| if facets: | |
| active_filters = { | |
| "price": price_tiers, | |
| "cuisine": cuisine if cuisine else None, | |
| "diet": diet if diet else None, | |
| "outdoor": outdoor, | |
| "canal": canal, | |
| "wheelchair": wheelchair, | |
| "accredited": accredited, | |
| "monument": monument, | |
| "independent": independent, | |
| "celiac": celiac, | |
| "scratch": scratch, | |
| "water": water, | |
| "clean": clean, | |
| "late_night": late_night, | |
| "roastery": roastery, | |
| "historic": historic, | |
| "bbox": bbox_coords, | |
| "max_dist": max_dist, | |
| "user_lat": user_lat if has_user_coords else None, | |
| "user_lon": user_lon if has_user_coords else None | |
| } | |
| taxonomy = engine.get_city_taxonomy(city_id, active_filters=active_filters) | |
| return { | |
| "places": results, | |
| "total": total_count, | |
| "taxonomy": taxonomy | |
| } | |
| return results | |
| # 2. API: Head-to-Head Compare | |
| def compare_places( | |
| id1: str = Query(...), | |
| id2: str = Query(...), | |
| city: str = "amsterdam" | |
| ): | |
| engine = manager.get_engine(city.lower().strip()) | |
| comparison = engine.compare_head_to_head(id1, id2) | |
| if comparison: | |
| return comparison | |
| raise HTTPException(status_code=404, detail="Places not found for comparison") | |
| # 3. API: Dynamic City Taxonomy Engine | |
| def get_taxonomy( | |
| city: str = "amsterdam", | |
| price: Optional[str] = None, | |
| cuisine: Optional[str] = None, | |
| diet: Optional[str] = None, | |
| outdoor: bool = False, | |
| canal: bool = False, | |
| wheelchair: bool = False, | |
| accredited: bool = False, | |
| monument: bool = False, | |
| independent: bool = False, | |
| celiac: bool = False, | |
| scratch: bool = False, | |
| water: bool = False, | |
| clean: bool = False, | |
| late_night: bool = False, | |
| roastery: bool = False, | |
| historic: bool = False | |
| ): | |
| city_id = city.lower().strip() | |
| engine = manager.get_engine(city_id) | |
| if diet and diet.lower().strip() in ("celiac", "celiac_safe"): | |
| celiac = True | |
| diet = None | |
| price_tier = None | |
| if price and price.strip().isdigit(): | |
| price_tier = int(price.strip()) | |
| has_filters = any([ | |
| price_tier is not None, cuisine, diet, outdoor, canal, wheelchair, | |
| accredited, monument, independent, celiac, scratch, water, clean, | |
| late_night, roastery, historic | |
| ]) | |
| active_filters = None | |
| if has_filters: | |
| active_filters = { | |
| "price": price_tier, | |
| "cuisine": cuisine if cuisine else None, | |
| "diet": diet if diet else None, | |
| "outdoor": outdoor, | |
| "canal": canal, | |
| "wheelchair": wheelchair, | |
| "accredited": accredited, | |
| "monument": monument, | |
| "independent": independent, | |
| "celiac": celiac, | |
| "scratch": scratch, | |
| "water": water, | |
| "clean": clean, | |
| "late_night": late_night, | |
| "roastery": roastery, | |
| "historic": historic | |
| } | |
| return engine.get_city_taxonomy(city_id, active_filters=active_filters) | |
| # 4. API: Facets & Aggregations | |
| def get_facets(city: str = "amsterdam"): | |
| engine = manager.get_engine(city.lower().strip()) | |
| return engine.get_facets(authentic_only=True) | |
| # 5. API: Stats & System Metrics | |
| def get_stats(city: str = "amsterdam"): | |
| city_id = city.lower().strip() | |
| engine = manager.get_engine(city_id) | |
| facets = engine.get_facets() | |
| return { | |
| "city": engine.city_config.get("name", city_id.capitalize()), | |
| "city_id": city_id, | |
| "country": engine.city_config.get("country", ""), | |
| "flag": engine.city_config.get("flag", ""), | |
| "total_eateries_indexed": facets["total_eateries"], | |
| "craft_artisans_detected": facets["craft_artisans_detected"], | |
| "tourist_traps_flagged": facets["tourist_traps_flagged"], | |
| "mono_specialists": facets["mono_specialists"], | |
| "halal_eateries": facets["halal_count"], | |
| "vegan_eateries": facets["vegan_count"], | |
| "canal_terraces": facets["canal_terrace_count"], | |
| "protected_monuments": facets["monuments_count"], | |
| "independent_artisans": facets["independent_count"], | |
| "celiac_safe_kitchens": facets["celiac_safe_count"], | |
| "scratch_kitchens": facets["scratch_count"], | |
| "tap_water_welcoming": facets["tap_water_count"], | |
| "clean_kitchens_verified": facets.get("clean_kitchen_count", 0), | |
| "data_source": "Overture Maps, OpenStreetMap & Government Registries", | |
| "google_api_cost": "$0.00" | |
| } | |
| # 6. API: Spatial God Mode AI Copilot (GET & POST) | |
| def copilot_ask_get(q: str = Query(...), city: str = "dubai"): | |
| if not q: | |
| raise HTTPException(status_code=400, detail="Query parameter 'q' is required") | |
| return copilot_service.ask(q, city=city.lower().strip()) | |
| async def copilot_ask_post(request: Request): | |
| try: | |
| data = await request.json() | |
| q = data.get("q", "") | |
| city_id = data.get("city", "dubai").lower().strip() | |
| if not q: | |
| raise HTTPException(status_code=400, detail="Field 'q' is required") | |
| return copilot_service.ask(q, city=city_id) | |
| except Exception as e: | |
| raise HTTPException(status_code=400, detail=str(e)) | |
| # 7. API: Community Endorsement | |
| async def endorse_place(request: Request): | |
| try: | |
| data = await request.json() | |
| place_id = data.get("place_id") | |
| positive = data.get("positive", True) | |
| city_id = data.get("city", "amsterdam").lower().strip() | |
| engine = manager.get_engine(city_id) | |
| p = next((x for x in engine.places if x["id"] == place_id), None) | |
| if p: | |
| p["endorsement_count"] = p.get("endorsement_count", 0) + 1 | |
| pos_count = (p.get("endorsement_positive_pct", 85) / 100.0) * (p["endorsement_count"] - 1) | |
| if positive: | |
| pos_count += 1 | |
| p["endorsement_positive_pct"] = int((pos_count / p["endorsement_count"]) * 100) | |
| return {"success": True, "place": p} | |
| raise HTTPException(status_code=404, detail="Place not found") | |
| except Exception as e: | |
| raise HTTPException(status_code=400, detail=str(e)) | |
| # 8. Health check | |
| def health(): | |
| return { | |
| "status": "healthy", | |
| "cities_count": len(manager.cities), | |
| "total_places": sum(len(manager.get_engine(c["id"]).places) for c in manager.cities) | |
| } | |
| # 9. Serve Main Palate Web Application | |
| def serve_root(): | |
| return FileResponse(INDEX_PATH) | |
| def serve_app(): | |
| return FileResponse(INDEX_PATH) | |
| # Gradio Integration | |
| try: | |
| import gradio as gr | |
| def ask_copilot_gradio(city_name: str, query: str): | |
| city_map = { | |
| "Amsterdam": "amsterdam", | |
| "Dubai": "dubai", | |
| "Istanbul": "istanbul", | |
| "Paris": "paris", | |
| "London": "london", | |
| "Tokyo": "tokyo", | |
| "New York": "newyork", | |
| "Rome": "rome" | |
| } | |
| cid = city_map.get(city_name, "dubai") | |
| if not query.strip(): | |
| return "Please provide a culinary inquiry or neighborhood request." | |
| res = copilot_service.ask(query, city=cid) | |
| reply = f"### 🍽️ {res.get('title', 'Culinary Recommendations')}\n\n" | |
| reply += f"*{res.get('rationale', '')}*\n\n" | |
| recs = res.get("recommendations", []) | |
| if recs: | |
| for r in recs: | |
| badge = f" `[{r.get('curator_badge', 'Verified')}]`" if r.get('curator_badge') else "" | |
| reply += f"- **{r.get('name')}**{badge} — {r.get('cuisine', '')}\n" | |
| if r.get('specialty_dish'): | |
| reply += f" - *Specialty:* {r.get('specialty_dish')}\n" | |
| if r.get('transit_guidance'): | |
| reply += f" - *Transit:* {r.get('transit_guidance')}\n" | |
| if r.get('why_recommended'): | |
| reply += f" - *Note:* {r.get('why_recommended')}\n" | |
| else: | |
| reply += "No specific venues matched this exact spatial criteria." | |
| return reply | |
| with gr.Blocks(title="Palate — Spatial Culinary Copilot") as demo: | |
| gr.Markdown( | |
| "# 🍽️ Palate / TasteOS — Spatial Culinary Copilot\n" | |
| "**Zero Paid Placements · Zero Fake Reviews · 82,000+ Ground-Truth Kitchens**\n\n" | |
| "[👉 **Launch Full Interactive Map Experience (Palate Web App)**](/) \n" | |
| ) | |
| with gr.Row(): | |
| city_dropdown = gr.Dropdown( | |
| choices=["Amsterdam", "Dubai", "Istanbul", "Paris", "London", "Tokyo", "New York", "Rome"], | |
| value="Dubai", | |
| label="Select Global Capital" | |
| ) | |
| query_input = gr.Textbox( | |
| placeholder="e.g. Late night craft ramen, sourdough bakery near canal, authentic biryani in Deira...", | |
| label="Ask Spatial Copilot" | |
| ) | |
| submit_btn = gr.Button("Query Copilot", variant="primary") | |
| output_md = gr.Markdown(label="Ground-Truth Recommendations") | |
| submit_btn.click( | |
| fn=ask_copilot_gradio, | |
| inputs=[city_dropdown, query_input], | |
| outputs=[output_md] | |
| ) | |
| gr.Examples( | |
| examples=[ | |
| ["Dubai", "Authentic mutton biryani in historic Deira"], | |
| ["Paris", "Natural wine bistro with craft sourdough near Canal Saint-Martin"], | |
| ["Amsterdam", "Independent specialty roastery with outdoor seating"], | |
| ["Istanbul", "Traditional wood-fired pide in Kadikoy"], | |
| ["Tokyo", "Quiet late-night yakitori specialist in Shibuya"], | |
| ["Rome", "Historic cacio e pepe trattoria away from tourist crowds"] | |
| ], | |
| inputs=[city_dropdown, query_input] | |
| ) | |
| try: | |
| app = gr.mount_gradio_app(app, demo, path="/gradio", ssr_mode=False) | |
| except TypeError: | |
| app = gr.mount_gradio_app(app, demo, path="/gradio") | |
| print("Mounted Gradio application at /gradio") | |
| except Exception as e: | |
| print(f"Gradio mounting skipped: {e}") | |
| # Static file fallback for any assets in public/ | |
| if os.path.exists(PUBLIC_DIR): | |
| app.mount("/static", StaticFiles(directory=PUBLIC_DIR), name="static") | |
| if __name__ == "__main__": | |
| import uvicorn | |
| import socket | |
| import subprocess | |
| port_env = os.environ.get("PORT") | |
| gradio_port_env = os.environ.get("GRADIO_SERVER_PORT") | |
| print(f"=== NETWORK & PROCESS DIAGNOSTICS ===") | |
| print(f"PORT env: {port_env}") | |
| print(f"GRADIO_SERVER_PORT env: {gradio_port_env}") | |
| print(f"Platform: {sys.platform}") | |
| try: | |
| ps_out = subprocess.check_output(["ps", "aux"], text=True) | |
| print(f"Processes:\n{ps_out}") | |
| except Exception as e: | |
| print(f"ps aux check error: {e}") | |
| try: | |
| sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| res = sock.connect_ex(('127.0.0.1', 7860)) | |
| sock.close() | |
| print(f"Socket probe 127.0.0.1:7860 -> result: {res} (0=occupied, non-zero=free)") | |
| except Exception as e: | |
| print(f"Socket probe error: {e}") | |
| target_port = int(port_env or gradio_port_env or 7860) | |
| print(f"==================================================") | |
| print(f" Palate Global Multi-City Engine listening on {target_port}") | |
| print(f" Web Application Root: http://0.0.0.0:{target_port}/") | |
| print(f" Gradio Copilot Portal: http://0.0.0.0:{target_port}/gradio") | |
| print(f"==================================================") | |
| uvicorn.run(app, host="0.0.0.0", port=target_port) | |