Tozma / app.py
Danielzapirtan's picture
Update app.py
4a01d5f verified
import gradio as gr
import requests
import json
from datetime import datetime
def query_overpass(query):
"""Query the Overpass API for OSM data"""
overpass_url = "http://overpass-api.de/api/interpreter"
try:
response = requests.post(overpass_url, data={'data': query}, timeout=180)
response.raise_for_status()
return response.json()
except Exception as e:
return {"error": str(e)}
def search_bucharest_locations():
"""Search for furniture stores, deposits, and shoe stores in Bucharest"""
# Overpass QL query for Bucharest
# Searches for:
# - shop=furniture (Furnituri)
# - amenity=storage_rental, shop=storage (Depozit)
# - shop=shoes (Cizmărie)
overpass_query = """
[out:json][timeout:180];
area["name"="București"]["admin_level"="4"]->.searchArea;
(
node["shop"="wholesale"](area.searchArea);
way["shop"="wholesale"](area.searchArea);
);
out body;
>;
out skel qt;
"""
status_msg = "Querying OpenStreetMap for Bucharest locations...\n"
status_msg += "Searching for: Furniture stores, Deposits/Storage, Shoe stores\n"
status_msg += "This may take up to 3 minutes...\n\n"
data = query_overpass(overpass_query)
if "error" in data:
status_msg += f"❌ Error: {data['error']}"
return status_msg, None
# Process results
elements = data.get('elements', [])
# Categorize results
furniture = []
deposits = []
shoes = []
other = []
for element in elements:
tags = element.get('tags', {})
if not tags:
continue
obj = {
'id': element.get('id'),
'type': element.get('type'),
'lat': element.get('lat'),
'lon': element.get('lon'),
'tags': tags
}
# Add center coordinates for ways/relations
if element.get('type') in ['way', 'relation'] and 'center' in element:
obj['lat'] = element['center']['lat']
obj['lon'] = element['center']['lon']
# Categorize
if tags.get('shop') == 'furniture':
furniture.append(obj)
elif tags.get('shop') == 'shoes':
shoes.append(obj)
elif tags.get('amenity') == 'storage_rental' or tags.get('shop') == 'storage' or tags.get('landuse') == 'depot':
deposits.append(obj)
else:
other.append(obj)
# Create output data
output_data = {
'query_date': datetime.now().isoformat(),
'location': 'București, Romania',
'summary': {
'total_results': len([e for e in elements if e.get('tags')]),
'furniture_stores': len(furniture),
'deposits_storage': len(deposits),
'shoe_stores': len(shoes),
'other': len(other)
},
'categories': {
'furniture': furniture,
'deposits_storage': deposits,
'shoes': shoes,
'other': other
},
'all_elements': elements
}
# Create JSON file
json_str = json.dumps(output_data, indent=2, ensure_ascii=False)
filename = f"bucharest_osm_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
# Status message
status_msg += "✅ Query completed successfully!\n\n"
status_msg += f"📊 Results Summary:\n"
status_msg += f" • Furniture stores: {len(furniture)}\n"
status_msg += f" • Deposits/Storage: {len(deposits)}\n"
status_msg += f" • Shoe stores: {len(shoes)}\n"
status_msg += f" • Other: {len(other)}\n"
status_msg += f" • Total: {len([e for e in elements if e.get('tags')])}\n\n"
status_msg += f"📁 Download the JSON file below for complete data"
return status_msg, json_str
def create_interface():
with gr.Blocks(title="Bucharest OSM Location Finder") as app:
gr.Markdown("""
# 🗺️ Bucharest Location Finder
Search OpenStreetMap for **Depozit** (deposits/storage), **Furnituri** (furniture stores),
and **Cizmărie** (shoe stores) in Bucharest, Romania.
Click the button below to query OSM and download a detailed JSON file with all found locations.
""")
with gr.Row():
search_btn = gr.Button("🔍 Search OpenStreetMap", variant="primary", size="lg")
status_output = gr.Textbox(
label="Search Status",
lines=10,
interactive=False
)
json_output = gr.File(
label="Download JSON Results",
interactive=False
)
gr.Markdown("""
---
### About the data:
- **Source**: OpenStreetMap (OSM) via Overpass API
- **Categories searched**:
- `shop=furniture` - Furniture stores
- `shop=shoes` - Shoe stores
- `amenity=storage_rental`, `shop=storage`, `landuse=depot` - Storage/deposit facilities
- **JSON structure**: Results are categorized and include coordinates, OSM IDs, and all available tags
- **Filtering**: Use the downloaded JSON file with your preferred tools (Python, jq, Excel, etc.)
💡 The JSON file includes full OSM data including names, addresses, phone numbers, websites,
opening hours, and other tags where available.
""")
def search_and_save():
status, json_data = search_bucharest_locations()
if json_data:
filename = f"bucharest_osm_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
with open(filename, 'w', encoding='utf-8') as f:
f.write(json_data)
return status, filename
return status, None
search_btn.click(
fn=search_and_save,
outputs=[status_output, json_output]
)
return app
if __name__ == "__main__":
app = create_interface()
app.launch()