Spaces:
Sleeping
Sleeping
Download api/app.py from neurostack-in/talk2map-test: direct link, hf CLI and curl.
- Browser
- Download file 5.96 kB
-
https://huggingface.co/spaces/neurostack-in/talk2map-test/resolve/main/api/app.py
- Command line
-
hf download hf://spaces/neurostack-in/talk2map-test/api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/neurostack-in/talk2map-test/resolve/main/api/app.py
5.96 kB
| # app.py | |
| from __future__ import annotations | |
| import json | |
| import re | |
| from typing import List, Optional | |
| from fastapi import FastAPI | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import HTMLResponse | |
| import uvicorn | |
| from agent.agent_runner import run_agent | |
| from agent.models import ( | |
| LatLon, | |
| BoundingBox, | |
| Place, | |
| AgentReply, | |
| Turn, | |
| ChatRequest, | |
| ChatResponse, | |
| ) | |
| app = FastAPI(title="Talk2Map API", version="1.0.0") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| def _sanitize_text(s: Optional[str]) -> str: | |
| if not s: | |
| return "" | |
| s = re.sub(r"<\|header_start\|>.*?<\|header_end\|>", "", s, flags=re.S | re.I) | |
| s = re.sub(r"<\|im_start\|>.*?<\|im_end\|>", "", s, flags=re.S | re.I) | |
| s = re.sub(r"<\|[^>]*\|>", "", s) | |
| return s.strip() | |
| def _looks_like_tool_json(s: Optional[str]) -> bool: | |
| if not s or not isinstance(s, str): | |
| return False | |
| s = s.strip() | |
| if not s or s[0] not in "[{": | |
| return False | |
| try: | |
| obj = json.loads(s) | |
| return isinstance(obj, list) and (len(obj) == 0 or isinstance(obj[0], dict)) | |
| except Exception: | |
| return False | |
| def _tool_json_to_places(raw_json: Optional[str]) -> List[Place]: | |
| if not raw_json: | |
| return [] | |
| try: | |
| data = json.loads(raw_json) | |
| except Exception: | |
| return [] | |
| if not isinstance(data, list): | |
| return [] | |
| out: List[Place] = [] | |
| for p in data: | |
| vp = p.get("viewport") or {} | |
| low = vp.get("low") or {} | |
| high = vp.get("high") or {} | |
| out.append( | |
| Place( | |
| name=p.get("name"), | |
| address=p.get("address"), | |
| latitude=p.get("lat"), | |
| longitude=p.get("lng"), | |
| bounding_box=( | |
| BoundingBox( | |
| north_east=LatLon(lat=high.get("latitude"), lon=high.get("longitude")), | |
| south_west=LatLon(lat=low.get("latitude"), lon=low.get("longitude")), | |
| ) | |
| if vp | |
| else None | |
| ), | |
| rating=p.get("rating"), | |
| user_rating_count=p.get("userRatingCount"), | |
| maps_url=p.get("mapsUrl"), | |
| ) | |
| ) | |
| return out | |
| def _fmt_places_md(places: List[Place]) -> str: | |
| lines = [] | |
| for i, p in enumerate(places, 1): | |
| rating = f" (Rating ★ {p.rating}, Reviews {p.user_rating_count})" if p.rating is not None else "" | |
| url = f" — {p.maps_url}" if p.maps_url else "" | |
| latlng = f"\nlat,lng: {p.latitude},{p.longitude}" | |
| box = "" | |
| if p.bounding_box and p.bounding_box.north_east and p.bounding_box.south_west: | |
| ne, sw = p.bounding_box.north_east, p.bounding_box.south_west | |
| box = f"\nSW: ({sw.lat}, {sw.lon}), NE: ({ne.lat}, {ne.lon})" | |
| lines.append(f"{i}. {p.name} — {p.address}{rating}{url}{latlng}{box}") | |
| return "\n".join(lines) | |
| def chat(req: ChatRequest) -> ChatResponse: | |
| lc_history = [] | |
| for t in (req.conversation_history or [])[-8:]: | |
| if t.human: | |
| lc_history.append({"type": "human", "content": str(t.human)[:2000]}) | |
| if t.ai is not None: | |
| ai_text = t.ai["message"] if isinstance(t.ai, dict) and "message" in t.ai else str(t.ai) | |
| lc_history.append({"type": "ai", "content": ai_text[:2000]}) | |
| bbox = None | |
| if req.bounding_box and req.bounding_box.north_east and req.bounding_box.south_west: | |
| bbox = { | |
| "north_east": {"lat": req.bounding_box.north_east.lat, "lon": req.bounding_box.north_east.lon}, | |
| "south_west": {"lat": req.bounding_box.south_west.lat, "lon": req.bounding_box.south_west.lon}, | |
| } | |
| result = run_agent(req.user_input or "", lc_history, bbox=bbox) | |
| message_text = result.get("final_text") or "" | |
| last_tool_json = result.get("last_tool_json") | |
| if _looks_like_tool_json(message_text): | |
| last_tool_json = message_text | |
| message_text = "" | |
| places = _tool_json_to_places(last_tool_json) | |
| if not message_text and places: | |
| message_text = _fmt_places_md(places) | |
| # Provide more contextual fallback message | |
| if not message_text: | |
| if bbox and req.user_input: | |
| message_text = f"No {req.user_input} found in the specified area. This area might not have any {req.user_input} or try expanding the search boundary." | |
| elif bbox: | |
| message_text = "No places found in the specified area. Try expanding the search boundary or searching in a different location." | |
| elif req.user_input: | |
| message_text = f"No {req.user_input} found in this region. This area might not have any {req.user_input} or try searching in a nearby city." | |
| else: | |
| message_text = "I couldn't find anything for that request." | |
| message_text = _sanitize_text(message_text) | |
| agent_reply = AgentReply(message=message_text, places=places) | |
| updated_history: List[Turn] = list(req.conversation_history or []) | |
| updated_history.append(Turn(human=req.user_input or "", ai=agent_reply.model_dump())) | |
| return ChatResponse(agent_reply=agent_reply, conversation_history=updated_history) | |
| def index(): | |
| try: | |
| with open("api/static/index.html", "r", encoding="utf-8") as f: | |
| return f.read() | |
| except Exception: | |
| return HTMLResponse( | |
| "<!doctype html><html><head><meta charset='utf-8'><title>Talk2Map</title></head>" | |
| "<body><h1>Talk2Map API</h1><p>POST to <code>/chat</code> to use the assistant.</p></body></html>" | |
| ) | |
| def health(): | |
| return {"status": "ok"} | |
| if __name__ == "__main__": | |
| uvicorn.run("app:app", host="127.0.0.1", port=8000, reload=True) | |