Download app.py from macken39/demo: direct link, hf CLI and curl.
- Browser
- Download file 17.7 kB
-
https://huggingface.co/spaces/macken39/demo/resolve/main/app.py
- Command line
-
hf download hf://spaces/macken39/demo/app.py
-
curl -L -o app.py https://huggingface.co/spaces/macken39/demo/resolve/main/app.py
17.7 kB
| import streamlit as st | |
| st.set_page_config(page_title="Corporate Event Venue Matcher", layout="wide") | |
| import requests | |
| import os | |
| from bs4 import BeautifulSoup | |
| from datetime import datetime | |
| # Configure OpenAI API (using OPENAI_API_KEY) | |
| OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") | |
| OPENAI_ENDPOINT = "https://api.openai.com/v1/chat/completions" | |
| # Google Apps Script endpoint - REPLACE WITH YOUR NEW DEPLOYMENT URL | |
| GOOGLE_APPS_SCRIPT_URL = "https://script.google.com/macros/s/AKfycbzQGNdeB-hEg0QqE7HxGuhUskjS2T1ekpf_ZrAc0Wj8KtvGpLjMCfIPHqfsfxNyw94_3Q/exec" | |
| def extract_venue_names(recommendations_text): | |
| """Extracts just the venue names from the full recommendations text.""" | |
| if not recommendations_text: | |
| return "No venues found" | |
| try: | |
| # Look for venue names in various formats | |
| import re | |
| # Pattern to match venue names (typically after headers like "## " or "### " or "**" or numbered lists) | |
| patterns = [ | |
| r'#{2,3}\s+(.+?)(?:\n|$)', # Markdown headers | |
| r'\*\*(.+?)\*\*', # Bold text | |
| r'^\d+\.\s*(.+?)(?:\n|$)', # Numbered lists | |
| r'^-\s*(.+?)(?:\n|$)', # Bullet points | |
| ] | |
| venue_names = [] | |
| lines = recommendations_text.split('\n') | |
| for line in lines: | |
| line = line.strip() | |
| if not line: | |
| continue | |
| # Check each pattern | |
| for pattern in patterns: | |
| matches = re.findall(pattern, line, re.MULTILINE) | |
| for match in matches: | |
| # Clean up the match | |
| clean_name = match.strip().replace('*', '').replace('#', '') | |
| # Skip lines that are clearly not venue names or contain distance info | |
| skip_conditions = [ | |
| 'venue analysis' in clean_name.lower(), | |
| 'checklist' in clean_name.lower(), | |
| 'recommendations' in clean_name.lower(), | |
| 'miles from' in clean_name.lower(), | |
| 'overview' in clean_name.lower(), | |
| 'summary' in clean_name.lower(), | |
| 'preparation' in clean_name.lower(), | |
| 'site visit' in clean_name.lower(), | |
| # Check for distance patterns like "2.5 miles" or "X miles from" | |
| re.search(r'\d+\.?\d*\s*miles?', clean_name.lower()), | |
| # Check for address patterns | |
| re.search(r'\d+\s+\w+\s+(street|st|avenue|ave|road|rd|drive|dr|blvd|boulevard)', clean_name.lower()), | |
| # Skip very short or very long names | |
| len(clean_name) < 5 or len(clean_name) > 80 | |
| ] | |
| if not any(skip_conditions): | |
| venue_names.append(clean_name) | |
| # Remove duplicates while preserving order | |
| unique_venues = [] | |
| for venue in venue_names: | |
| if venue not in unique_venues: | |
| unique_venues.append(venue) | |
| # Return up to 10 venue names, joined by semicolons | |
| return '; '.join(unique_venues[:10]) if unique_venues else "Venues found but names could not be extracted" | |
| except Exception as e: | |
| return f"Error extracting venue names: {str(e)}" | |
| def save_to_google_apps_script(data): | |
| """Saves the submitted event data via Google Apps Script.""" | |
| try: | |
| # Debug: Show what data is being sent | |
| response = requests.post( | |
| GOOGLE_APPS_SCRIPT_URL, | |
| json=data, | |
| timeout=30, | |
| headers={'Content-Type': 'application/json'} | |
| ) | |
| # Debug: Show response details | |
| if response.status_code == 200: | |
| try: | |
| result = response.json() | |
| if result.get('result') == 'success': | |
| return True, "Data submitted successfully! We'll be in touch soon." | |
| else: | |
| return False, f"Script error: {result.get('message', 'Unknown error')}" | |
| except: | |
| # If response is not JSON, treat as success if status is 200 | |
| return True, "Data submitted successfully! We'll be in touch soon." | |
| else: | |
| return False, f"Submission failed with status code: {response.status_code}" | |
| except requests.exceptions.Timeout: | |
| return False, "Request timed out. Please try again later." | |
| except Exception as e: | |
| return False, f"Error submitting data: {str(e)}" | |
| def scrape_website(url): | |
| """Scrapes company content from the given website URL.""" | |
| if not url.startswith("http"): | |
| url = f"https://{url}" | |
| try: | |
| response = requests.get(url, timeout=10) | |
| response.raise_for_status() | |
| soup = BeautifulSoup(response.content, "html.parser") | |
| content = [] | |
| # Extract meta description if available | |
| meta_description = soup.find("meta", {"name": "description"}) | |
| if meta_description and meta_description.get("content"): | |
| content.append(meta_description["content"]) | |
| # Extract text from h1, h2, and p tags | |
| for tag in ['h1', 'h2', 'p']: | |
| elements = soup.find_all(tag) | |
| content.extend([elem.get_text(strip=True) for elem in elements if elem.get_text(strip=True)]) | |
| return " ".join(content[:1500]) | |
| except Exception as e: | |
| st.error(f"Error scraping website: {str(e)}") | |
| return None | |
| def search_real_venues(zip_code, event_type, attendees, event_style): | |
| """Uses OpenAI to research actual venues within 10 miles of the zip code.""" | |
| prompt = f"""Your task is to act as a venue research specialist. Research and identify 5 actual, real-world venues within 10 miles of zip code {zip_code} that would be suitable for a {event_type} event with {attendees} attendees. | |
| The event style preference is: {event_style if event_style else "No specific style preference"} | |
| For each venue, please provide: | |
| 1. Venue name (must be real, verifiable venues) | |
| 2. Exact location/address | |
| 3. Approximate distance from zip code {zip_code} (MUST specify the exact distance in miles, e.g., "3.5 miles from {zip_code}") | |
| 4. Venue type and atmosphere | |
| 5. Capacity information | |
| 6. Key amenities offered | |
| 7. Why this venue would be a good match for this specific event | |
| Be precise, accurate, and only include venues that actually exist and can be verified. Format each venue recommendation as a separate section with a clear heading. Make sure to always include the exact distance in miles from the requested zip code.""" | |
| headers = { | |
| "Authorization": f"Bearer {OPENAI_API_KEY}", | |
| "Content-Type": "application/json" | |
| } | |
| data = { | |
| "model": "gpt-4", # Using OpenAI GPT-4 model | |
| "messages": [ | |
| {"role": "system", "content": "You are a venue research specialist with extensive knowledge of event spaces across the United States. You provide accurate, up-to-date information about real venues, with precise details that can be verified. Always include the exact distance in miles from the requested zip code for each venue."}, | |
| {"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_venue_recommendations(event_info, zip_code, event_type, attendees, event_style, company_info=None, additional_services=None): | |
| """Generates comprehensive venue recommendations using OpenAI GPT-4.""" | |
| # First get real venue research | |
| real_venues = search_real_venues(zip_code, event_type, attendees, event_style) | |
| if not real_venues: | |
| return None | |
| # Include company information if provided | |
| company_info_text = f"Company Information: {company_info}" if company_info else "" | |
| # Include additional services information if provided | |
| additional_services_text = "" | |
| if additional_services and len(additional_services) > 0: | |
| additional_services_text = f"Additional Services Required: {', '.join(additional_services)}" | |
| prompt = f"""As an expert corporate event planning consultant specializing in venue selection, provide detailed venue recommendations for the following event: | |
| {event_info} | |
| {company_info_text} | |
| {additional_services_text} | |
| Here are real venues within 10 miles of the specified zip code that match the event requirements: | |
| {real_venues} | |
| Based on these real venue options, please provide: | |
| 1. **Venue Analysis:** For each of these real venues, analyze how well they match this specific event's needs and provide specific recommendations for utilizing the space. Always include the distance from the zip code in miles when discussing each venue. | |
| 2. **Party Preparation & Site Visit Checklist:** Provide a comprehensive checklist that includes: | |
| - Venue infrastructure inspection points | |
| - Party preparation considerations (decorating timeline, setup requirements, vendor coordination) | |
| - Event flow planning (guest arrival, activities, catering service, entertainment timing) | |
| - Safety and logistics considerations | |
| - Post-event cleanup coordination | |
| - Emergency planning and contingencies | |
| - Guest experience optimization points | |
| - Photography and documentation planning | |
| - Weather contingencies (if applicable) | |
| - Final walkthrough requirements | |
| Format your response in clear markdown with headers and bullet points, and explain the strategic reasoning behind each recommendation. Make sure the distance in miles from the requested zip code is clearly stated for each venue.""" | |
| headers = { | |
| "Authorization": f"Bearer {OPENAI_API_KEY}", | |
| "Content-Type": "application/json" | |
| } | |
| data = { | |
| "model": "gpt-4", # Using OpenAI GPT-4 model | |
| "messages": [ | |
| {"role": "system", "content": "You are a top-tier corporate event planning consultant with extensive experience selecting perfect venues for various event types. Always include the distance in miles from the requested zip code when discussing venues."}, | |
| {"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 | |
| # Streamlit UI | |
| st.title("🏢 Corporate Event Venue Matcher") | |
| st.markdown("### Get personalized venue recommendations for your corporate event.") | |
| # Combined form with all necessary fields | |
| company_name = st.text_input("Company Name*") | |
| event_name = st.text_input("Event Name*") | |
| event_type = st.selectbox("Event Type*", | |
| ["Conference", "Corporate Retreat", "Team Building", "Product Launch", | |
| "Trade Show", "Gala/Award Ceremony", "Executive Meeting", "Training Session", "Other"]) | |
| if event_type == "Other": | |
| event_type_other = st.text_input("Please specify event type") | |
| event_type = event_type_other if event_type_other else event_type | |
| # Add zip code input | |
| zip_code = st.text_input("Event Location Zip Code*", help="We'll find venues within 10 miles of this location") | |
| # Event date and time | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| event_date = st.date_input("Event Date*") | |
| with col2: | |
| event_time = st.time_input("Event Start Time*") | |
| # Add event style checkboxes | |
| st.write("Event Style (select all that apply):") | |
| col1, col2, col3 = st.columns(3) | |
| with col1: | |
| formal = st.checkbox("Formal") | |
| outdoor = st.checkbox("Outdoor") | |
| with col2: | |
| modern = st.checkbox("Modern") | |
| traditional = st.checkbox("Traditional") | |
| with col3: | |
| creative = st.checkbox("Creative") | |
| professional = st.checkbox("Professional") | |
| attendees = st.number_input("Expected Number of Attendees*", min_value=1, value=100) | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| budget_min = st.number_input("Budget Minimum ($)", min_value=0, value=5000, step=1000) | |
| with col2: | |
| budget_max = st.number_input("Budget Maximum ($)", min_value=0, value=20000, step=1000) | |
| # Additional services needed | |
| st.write("Additional Services Needed:") | |
| col1, col2, col3 = st.columns(3) | |
| with col1: | |
| catering = st.checkbox("Catering") | |
| floral = st.checkbox("Floral/Decor") | |
| with col2: | |
| dj = st.checkbox("DJ/Entertainment") | |
| lighting = st.checkbox("Lighting") | |
| with col3: | |
| meeting_space = st.checkbox("Meeting Spaces/Breakouts") | |
| av_services = st.checkbox("AV Services") | |
| # Other services text field | |
| other_services = st.text_input("Other Services Needed (if not listed above)") | |
| # Optional fields | |
| special_requirements = st.text_area("Special Requirements or Preferences", | |
| help="E.g., accessibility needs, catering preferences, technical requirements") | |
| if st.button("Generate Venue Recommendations"): | |
| if not all([company_name, event_name, event_type, attendees, zip_code, event_date, event_time]): | |
| st.error("Please fill in all required fields marked with *") | |
| else: | |
| # Collect all form data | |
| event_style = ', '.join([style for style, selected in zip(['Formal', 'Outdoor', 'Modern', 'Traditional', 'Creative', 'Professional'], | |
| [formal, outdoor, modern, traditional, creative, professional]) if selected]) | |
| # Collect additional services | |
| additional_services = [] | |
| if catering: | |
| additional_services.append("Catering") | |
| if floral: | |
| additional_services.append("Floral/Decor") | |
| if dj: | |
| additional_services.append("DJ/Entertainment") | |
| if lighting: | |
| additional_services.append("Lighting") | |
| if meeting_space: | |
| additional_services.append("Meeting Spaces/Breakouts") | |
| if av_services: | |
| additional_services.append("AV Services") | |
| if other_services: | |
| additional_services.append(other_services) | |
| service_details = ", ".join(additional_services) if additional_services else "None" | |
| # Format event date and time (12-hour format) | |
| formatted_date = event_date.strftime("%Y-%m-%d") | |
| formatted_time = event_time.strftime("%I:%M %p") # 12-hour clock with AM/PM | |
| # Add timestamp | |
| timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
| with st.spinner("Researching real venues and creating your personalized recommendations..."): | |
| event_info = f""" | |
| Company Name: {company_name} | |
| Event Name: {event_name} | |
| Event Type: {event_type} | |
| Event Location Zip Code: {zip_code} (please recommend venues within 10 miles of this location) | |
| Event Date: {formatted_date} | |
| Event Start Time: {formatted_time} | |
| Event Style: {event_style} | |
| Expected Attendees: {attendees} | |
| Budget Range: ${budget_min} - ${budget_max} | |
| Special Requirements: {special_requirements if special_requirements else 'None specified'} | |
| """ | |
| # Generate venue recommendations | |
| recommendations = generate_venue_recommendations(event_info, zip_code, event_type, attendees, event_style, None, additional_services) | |
| if recommendations: | |
| # Extract just the venue names for the Google Sheet | |
| venue_names_only = extract_venue_names(recommendations) | |
| # Format data for Google Apps Script (now including venue names only) | |
| form_data = { | |
| "timestamp": timestamp, | |
| "company_name": company_name, | |
| "event_name": event_name, | |
| "event_type": event_type, | |
| "zip_code": zip_code, | |
| "event_style": event_style, | |
| "attendees": str(attendees), | |
| "event_date": formatted_date, | |
| "event_start_time": formatted_time, | |
| "budget_min": f"${budget_min}", | |
| "budget_max": f"${budget_max}", | |
| "special_requirements": special_requirements if special_requirements else "None specified", | |
| "catering": "Yes" if catering else "No", | |
| "additional_services": ", ".join([service for service in ["Floral/Decor", "DJ/Entertainment", "Lighting", "Meeting Spaces/Breakouts", "AV Services"] | |
| if service in additional_services]), | |
| "service_details": other_services if other_services else "None", | |
| "venue_names": venue_names_only # Added venue names only (truncated) | |
| } | |
| # Save via Google Apps Script | |
| save_success, save_message = save_to_google_apps_script(form_data) | |
| if save_success: | |
| st.success(save_message) | |
| else: | |
| st.warning(save_message) | |
| # Display the recommendations | |
| st.markdown(recommendations) | |
| else: | |
| st.error("Unable to generate venue recommendations. Please try again.") |