Spaces:
Runtime error
Runtime error
File size: 22,852 Bytes
459fa08 9eb9545 459fa08 9eb9545 8a5702c 9eb9545 8a5702c 9eb9545 8a5702c 9eb9545 8a5702c 9eb9545 8a5702c 9eb9545 8a5702c 9eb9545 8a5702c 9eb9545 459fa08 9eb9545 459fa08 9eb9545 459fa08 9eb9545 459fa08 9eb9545 | 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 | import streamlit as st
st.set_page_config(page_title="Photo Shoot Location Finder", layout="wide")
import requests
import os
import re
from datetime import datetime
# API Keys
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
GOOGLE_PLACES_API_KEY = os.getenv("GOOGLE_PLACES_API_KEY")
OPENAI_ENDPOINT = "https://api.openai.com/v1/chat/completions"
def get_location_details(location_name, city, max_retries=2):
"""
Get location details and Google Maps link using Google Places API
"""
if not GOOGLE_PLACES_API_KEY:
return None, "API key not available"
# Clean location name for better search
clean_name = re.sub(r'\([^)]*\)', '', location_name).strip()
# Try multiple search variations for better results
search_queries = [
f"{clean_name} {city}",
f"{clean_name}", # Sometimes city context confuses the search
f"{location_name} {city}", # Try original name too
]
search_url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
for attempt, search_query in enumerate(search_queries):
try:
# Remove type restriction for first attempt, be more flexible
params = {
'query': search_query.strip(),
'key': GOOGLE_PLACES_API_KEY
}
# Add type filter only on subsequent attempts
if attempt > 0:
params['type'] = 'establishment|tourist_attraction|park|point_of_interest'
response = requests.get(search_url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
if data.get('results') and len(data['results']) > 0:
place = data['results'][0]
place_id = place['place_id']
# Get detailed info
details_url = "https://maps.googleapis.com/maps/api/place/details/json"
details_params = {
'place_id': place_id,
'fields': 'name,formatted_address,rating,price_level,opening_hours,website,formatted_phone_number,photos,url,geometry',
'key': GOOGLE_PLACES_API_KEY
}
details_response = requests.get(details_url, params=details_params, timeout=10)
details_response.raise_for_status()
details_data = details_response.json()
if 'result' in details_data:
result = details_data['result']
# Create Google Maps URL if not provided
maps_url = result.get('url', '')
if not maps_url and result.get('geometry', {}).get('location'):
lat = result['geometry']['location']['lat']
lng = result['geometry']['location']['lng']
maps_url = f"https://www.google.com/maps/search/?api=1&query={lat},{lng}"
location_info = {
'name': result.get('name', location_name),
'address': result.get('formatted_address', 'Address not available'),
'rating': result.get('rating', 'N/A'),
'google_maps_url': maps_url,
'website': result.get('website', ''),
'phone': result.get('formatted_phone_number', ''),
'hours': result.get('opening_hours', {}).get('weekday_text', []) if result.get('opening_hours') else []
}
return location_info, "Location found"
# If no results, try next search variation
continue
except requests.exceptions.RequestException as e:
if attempt == len(search_queries) - 1: # Last attempt
return None, f"Network error: {str(e)}"
continue
except Exception as e:
if attempt == len(search_queries) - 1: # Last attempt
return None, f"Location lookup error: {str(e)}"
continue
# If all attempts failed, create a basic Google Maps search URL
fallback_query = f"{location_name} {city}".replace(' ', '+')
fallback_url = f"https://www.google.com/maps/search/{fallback_query}"
fallback_info = {
'name': location_name,
'address': f"Search for {location_name} in {city}",
'rating': 'N/A',
'google_maps_url': fallback_url,
'website': '',
'phone': '',
'hours': []
}
return fallback_info, "Fallback search link created"
def extract_locations_from_recommendations(recommendations_text):
"""
Extract potential location names from the recommendations text
"""
locations = []
# Enhanced patterns to find location names
patterns = [
# Bold text that might be location names
r'\*\*([^*\n]{3,60})\*\*',
# Numbered list items that might be locations
r'^\d+\.\s*\*\*([^*\n]{3,60})\*\*',
# Bullet points with location names
r'^[-β’]\s*\*\*([^*\n]{3,60})\*\*',
# Location mentions with common suffixes
r'([A-Z][a-zA-Z\s&\']{2,50}(?:Park|Bridge|Museum|Gallery|Garden|Plaza|Square|Center|Building|Tower|Beach|Pier|Rooftop|Studio))',
]
for pattern in patterns:
matches = re.findall(pattern, recommendations_text, re.MULTILINE | re.IGNORECASE)
locations.extend(matches)
# Clean up and filter location names
cleaned_locations = []
skip_words = ['morning', 'afternoon', 'evening', 'lighting', 'photography', 'photo', 'shoot', 'recommendation', 'tip', 'note', 'best', 'perfect']
for location in locations:
clean_name = location.strip().replace('*', '').replace('#', '').replace(':', '')
# Skip if too short, too long, or contains skip words
if (len(clean_name) >= 5 and len(clean_name) <= 60 and
not any(skip_word in clean_name.lower() for skip_word in skip_words) and
clean_name not in cleaned_locations):
cleaned_locations.append(clean_name)
return cleaned_locations[:12] # Limit to avoid API quota issues
def research_city_photo_areas(city, photo_type, location_prefs, time_preference, budget_level):
"""Research the best photography areas and neighborhoods in a city."""
current_year = datetime.now().year
prompt = f"""As a professional photography location scout with extensive knowledge of {city}, provide detailed information about the best areas and neighborhoods for {photo_type} photography.
LOCATION PREFERENCES: {', '.join(location_prefs) if location_prefs else 'Mixed locations'}
TIME PREFERENCE: {time_preference}
BUDGET CONSIDERATIONS: {budget_level}
For each recommended area, please provide:
1. Area/neighborhood name and general location
2. Why it's perfect for {photo_type} photography
3. Best lighting conditions and times of day
4. Specific photo opportunities and backdrops
5. Accessibility and parking information
6. Permit requirements or restrictions
7. Equipment considerations
8. Crowd levels and privacy factors
9. Safety considerations
10. Any fees or costs involved
Focus on providing 4-5 distinct areas that offer different photography opportunities and aesthetics. Include both popular established locations and hidden gems that locals know about.
Provide specific, actionable information that a photographer can use to plan their shoot effectively."""
headers = {
"Authorization": f"Bearer {OPENAI_API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": "gpt-4",
"messages": [
{"role": "system", "content": f"You are a professional photography location scout with deep knowledge of {city}. You specialize in finding the perfect shooting locations for different types of photography and understand lighting, permits, logistics, and local regulations."},
{"role": "user", "content": prompt}
],
"temperature": 0.7,
"max_tokens": 2000
}
try:
response = requests.post(OPENAI_ENDPOINT, json=data, headers=headers)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"]
except Exception as e:
st.error(f"API Error: {str(e)}")
return None
def generate_photo_location_recommendations(shoot_info, city, photo_type, location_prefs, time_preference, budget_level, equipment_needs=None):
"""Generate comprehensive photo shoot location recommendations."""
# First get area research
area_research = research_city_photo_areas(city, photo_type, location_prefs, time_preference, budget_level)
if not area_research:
return None
current_year = datetime.now().year
equipment_text = f"Equipment Needs: {', '.join(equipment_needs)}" if equipment_needs and len(equipment_needs) > 0 else ""
prompt = f"""As a professional photography location expert specializing in {city}, create comprehensive location recommendations for the following photo shoot:
{shoot_info}
{equipment_text}
Here's the area research for {city}:
{area_research}
Based on this information, please provide:
1. **Top Photography Areas:** Best 4-5 neighborhoods/areas with specific reasons why each works for this type of shoot
2. **Specific Location Recommendations:**
- **Outdoor Locations:** Parks, streets, rooftops, architectural spots, natural settings
- **Indoor Locations:** Studios, galleries, unique indoor spaces (if applicable)
- Include exact location names when possible
3. **Detailed Location Guide:** For each recommended location provide:
- **Best Times:** Optimal lighting conditions and times of day
- **Photography Opportunities:** Specific shots and backdrops available
- **Logistics:** Parking, accessibility, equipment restrictions
- **Permits & Regulations:** Any permits needed, photography rules
- **Costs:** Entry fees, parking costs, permit fees
- **Crowd Factors:** Best times to avoid crowds, privacy considerations
- **Equipment Considerations:** What works best, any restrictions
4. **Lighting Guide:**
- Golden hour locations and timing
- Blue hour opportunities
- Covered/indoor options for any weather
- Artificial lighting considerations
5. **Practical Shooting Tips:**
- Local photography regulations and etiquette
- Safety considerations
- Backup location options
- Contact information for permits if needed
- Local photography communities or resources
6. **Budget Breakdown:**
- Free locations vs. paid locations
- Estimated costs for permits, parking, entry fees
- Money-saving tips and alternatives
7. **Seasonal Considerations:**
- How locations change throughout the year
- Weather backup plans
- Current conditions for {current_year}
IMPORTANT: When mentioning specific locations, use the exact names of parks, buildings, streets, or landmarks. Be as specific as possible with location names to help with Google Maps integration.
Format your response in clear markdown with headers and provide specific, actionable recommendations that a photographer can immediately use to plan their shoot."""
headers = {
"Authorization": f"Bearer {OPENAI_API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": "gpt-4",
"messages": [
{"role": "system", "content": f"You are a top-tier professional photography location scout with extensive knowledge of {city}. You understand the technical aspects of photography, lighting conditions, permit requirements, and the logistics of organizing photo shoots. You provide detailed, actionable recommendations that photographers can immediately implement."},
{"role": "user", "content": prompt}
],
"temperature": 0.7,
"max_tokens": 4000
}
try:
response = requests.post(OPENAI_ENDPOINT, json=data, headers=headers)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"]
except Exception as e:
st.error(f"API Error: {str(e)}")
return None
def enhance_recommendations_with_maps(recommendations, city):
"""
Enhance recommendations with Google Maps links and location details
"""
if not GOOGLE_PLACES_API_KEY:
return recommendations, []
# Extract location names
locations = extract_locations_from_recommendations(recommendations)
if not locations:
return recommendations, []
# Get details for each location
location_details = []
enhanced_sections = []
with st.spinner(f"Getting location details and Google Maps links for {len(locations)} recommendations..."):
progress_bar = st.progress(0)
for i, location in enumerate(locations):
details, status = get_location_details(location, city)
if details:
location_details.append(details)
enhanced_sections.append(f"""
**π {details['name']}**
- **Address:** {details['address']}
- **Google Maps:** [View Location]({details['google_maps_url']})
- **Rating:** {details['rating']}/5
{f"- **Website:** {details['website']}" if details['website'] else ""}
{f"- **Phone:** {details['phone']}" if details['phone'] else ""}
{f"- **Hours:** {', '.join(details['hours'][:2])}" if details['hours'] else ""}
""")
else:
enhanced_sections.append(f"π **{location}** - {status}")
# Update progress
progress_bar.progress((i + 1) / len(locations))
progress_bar.empty()
# Add enhanced location details to recommendations
if enhanced_sections:
location_summary = "\n\n---\n## πΊοΈ Location Details & Google Maps Links\n\n"
location_summary += "\n".join(enhanced_sections)
location_summary += "\n\n*Location details and links provided via Google Places API*\n"
recommendations = recommendations + location_summary
return recommendations, location_details
# Streamlit UI
st.title("πΈ Photo Shoot Location Finder")
st.markdown("### Discover the perfect photography locations in any city - with Google Maps integration!")
# API Status Check
api_status_col1, api_status_col2 = st.columns(2)
with api_status_col1:
if OPENAI_API_KEY:
st.success("β
OpenAI API Connected")
else:
st.error("β OpenAI API Key Missing")
with api_status_col2:
if GOOGLE_PLACES_API_KEY:
st.success("β
Google Places API Connected")
else:
st.warning("β οΈ Google Places API Missing (location links disabled)")
# Initialize session state
if 'recommendations_generated' not in st.session_state:
st.session_state.recommendations_generated = False
if 'recommendations' not in st.session_state:
st.session_state.recommendations = ""
# Main form
photographer_name = st.text_input("Photographer/Client Name (optional)", help="e.g., 'Sarah Photography', 'The Johnson Wedding'")
city = st.text_input("City*", help="e.g., 'New York City', 'Los Angeles', 'Chicago'")
# Photo shoot type
photo_type = st.selectbox("Photo Shoot Type*",
["Portrait/Headshots", "Wedding/Engagement", "Fashion/Editorial",
"Street Photography", "Landscape/Cityscape", "Product Photography",
"Family/Group Photos", "Maternity", "Senior Portraits", "Corporate/Business",
"Artistic/Creative", "Event Photography", "Other"])
if photo_type == "Other":
photo_type_other = st.text_input("Please specify photo shoot type")
photo_type = photo_type_other if photo_type_other else photo_type
# Location preferences
st.write("**Preferred Location Types (select all that apply):**")
col1, col2, col3, col4 = st.columns(4)
with col1:
outdoor_parks = st.checkbox("Parks & Gardens")
beaches_water = st.checkbox("Beaches/Waterfront")
rooftops_views = st.checkbox("Rooftops/Scenic Views")
with col2:
architecture = st.checkbox("Architecture/Buildings")
street_urban = st.checkbox("Street/Urban Settings")
bridges_landmarks = st.checkbox("Bridges/Landmarks")
with col3:
indoor_studios = st.checkbox("Studios/Indoor Spaces")
galleries_museums = st.checkbox("Galleries/Museums")
cafes_restaurants = st.checkbox("Cafes/Restaurants")
with col4:
street_art_murals = st.checkbox("Street Art/Murals")
historic_sites = st.checkbox("Historic Sites")
natural_settings = st.checkbox("Natural Settings")
# Shoot details
col1, col2 = st.columns(2)
with col1:
group_size = st.number_input("Number of People in Shoot*", min_value=1, value=2, max_value=50)
time_preference = st.selectbox("Preferred Time of Day*",
["Golden Hour (Sunrise)", "Golden Hour (Sunset)", "Blue Hour",
"Mid-Morning", "Afternoon", "Overcast/Any Time", "Indoor/Controlled Lighting"])
with col2:
budget_level = st.selectbox("Budget Level*", ["Free Locations Only", "Low Budget", "Medium Budget", "High Budget", "No Budget Constraints"])
season_timing = st.selectbox("Season/Timing", ["Spring", "Summer", "Fall", "Winter", "Year-Round", "Not Specified"])
# Equipment needs
st.write("**Equipment Considerations (select all that apply):**")
col1, col2, col3 = st.columns(3)
with col1:
tripods = st.checkbox("Tripods/Stands")
lighting_gear = st.checkbox("Lighting Equipment")
props = st.checkbox("Props/Backdrops")
with col2:
vehicles = st.checkbox("Vehicle Access Needed")
power_access = st.checkbox("Power Access Required")
weather_protection = st.checkbox("Weather Protection")
with col3:
privacy_needed = st.checkbox("Privacy/Quiet Needed")
crowd_friendly = st.checkbox("Crowd-Friendly Location")
permit_ok = st.checkbox("Permit Required OK")
# Special requirements
special_requirements = st.text_area("Special Requirements or Preferences",
help="e.g., wheelchair accessible, specific aesthetic, must avoid crowds, specific architectural style needed")
# Google Maps integration option
get_maps_links = st.checkbox("Get Google Maps links and location details (recommended)",
value=bool(GOOGLE_PLACES_API_KEY),
help="Uses Google Places API to provide maps links, addresses, and additional location details",
disabled=not GOOGLE_PLACES_API_KEY)
if st.button("Find Perfect Photo Locations", type="primary"):
if not all([city, photo_type, group_size, time_preference, budget_level]):
st.error("Please fill in all required fields marked with *")
else:
# Collect all form data
location_prefs = []
location_mapping = {
"Parks & Gardens": outdoor_parks,
"Beaches/Waterfront": beaches_water,
"Rooftops/Scenic Views": rooftops_views,
"Architecture/Buildings": architecture,
"Street/Urban Settings": street_urban,
"Bridges/Landmarks": bridges_landmarks,
"Studios/Indoor Spaces": indoor_studios,
"Galleries/Museums": galleries_museums,
"Cafes/Restaurants": cafes_restaurants,
"Street Art/Murals": street_art_murals,
"Historic Sites": historic_sites,
"Natural Settings": natural_settings
}
location_prefs = [location for location, selected in location_mapping.items() if selected]
# Equipment needs
equipment_needs = []
equipment_mapping = {
"Tripods/Stands": tripods,
"Lighting Equipment": lighting_gear,
"Props/Backdrops": props,
"Vehicle Access Needed": vehicles,
"Power Access Required": power_access,
"Weather Protection": weather_protection,
"Privacy/Quiet Needed": privacy_needed,
"Crowd-Friendly Location": crowd_friendly,
"Permit Required OK": permit_ok
}
equipment_needs = [equipment for equipment, selected in equipment_mapping.items() if selected]
shoot_info = f"""
Photographer/Client: {photographer_name if photographer_name else 'Not specified'}
City: {city}
Photo Shoot Type: {photo_type}
Number of People: {group_size}
Preferred Time of Day: {time_preference}
Season/Timing: {season_timing}
Budget Level: {budget_level}
Preferred Location Types: {', '.join(location_prefs) if location_prefs else 'Open to all location types'}
Equipment Considerations: {', '.join(equipment_needs) if equipment_needs else 'Standard photography equipment'}
Special Requirements: {special_requirements if special_requirements else 'None specified'}
"""
with st.spinner(f"Researching the best photography locations in {city}..."):
# Generate location recommendations
recommendations = generate_photo_location_recommendations(
shoot_info, city, photo_type, location_prefs, time_preference, budget_level, equipment_needs
)
if recommendations:
# Enhance with Google Maps links if requested and API is available
if get_maps_links and GOOGLE_PLACES_API_KEY:
recommendations, location_details = enhance_recommendations_with_maps(recommendations, city)
if location_details:
st.success(f"β
Found {len(location_details)} locations with Google Maps links!")
# Store in session state
st.session_state.recommendations = recommendations
st.session_state.recommendations_generated = True
# Display the recommendations
st.markdown("---")
st.markdown("## πΈ Your Perfect Photo Shoot Locations")
st.markdown(recommendations)
# Add sharing/saving tips
st.markdown("---")
st.info("π‘ **Pro Tip:** Bookmark this page or share the Google Maps links directly with your clients. Always check current permit requirements before your shoot!")
else:
st.error("Unable to generate location recommendations. Please try again or contact support.")
# Footer
st.markdown("---")
st.markdown("*Made with β€οΈ for photographers and creatives - Enhanced with Google Maps integration*") |