Spaces:
Runtime error
Runtime error
Download src/streamlit_app.py from macken39/Photo-Locations: direct link, hf CLI and curl.
- Browser
- Download file 22.9 kB
-
https://huggingface.co/spaces/macken39/Photo-Locations/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/macken39/Photo-Locations/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/macken39/Photo-Locations/resolve/main/src/streamlit_app.py
22.9 kB
| 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*") |