Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199import streamlit as stimport openaiimport requestsfrom bs4 import BeautifulSoupfrom urllib.parse import urljoin, urlparseimport osimport re# Ensure your OpenAI API key is set in your environment variablesopenai.api_key = os.getenv("OPENAI_API_KEY")def scrape_website(url, max_pages=5):"""Crawls and scrapes content from the given website URL.Follows internal links and extracts meaningful information from up to `max_pages` pages."""if not url.startswith("http"):url = f"https://{url}"visited = set()to_visit = [url]all_content = []scrape_successful = Falsewhile to_visit and len(visited) < max_pages:current_url = to_visit.pop(0)if current_url in visited:continuetry:response = requests.get(current_url, timeout=10)response.raise_for_status()soup = BeautifulSoup(response.content, "html.parser")visited.add(current_url)scrape_successful = True# Extract meaningful contentmeta_description = soup.find("meta", {"name": "description"})if meta_description and meta_description.get("content"):all_content.append(meta_description["content"])paragraphs = soup.find_all("p")for para in paragraphs:all_content.append(para.get_text(strip=True))links = soup.find_all("a", href=True)for link in links:full_url = urljoin(current_url, link["href"])if url in full_url and full_url not in visited:to_visit.append(full_url)except Exception:continuereturn " ".join(all_content[:3000]), scrape_successfuldef extract_location(content):"""Extract a possible location from the website content using regular expressions."""location_match = re.search(r'\b(?:serving|located in|offices in|based in)\s([\w\s,]+)', content, re.IGNORECASE)return location_match.group(1).strip() if location_match else Nonedef infer_business_info_from_url(url):"""Infer business details from the domain name."""domain_name = urlparse(url).netlocinferred_info = openai.ChatCompletion.create(model="gpt-4",messages=[{"role": "system","content": "You are a business analyst. Based on domain names, generate likely information about a business, including its industry, target audience, and goals."},{"role": "user","content": f"The domain is {domain_name}. What can you infer about this business?"}])return inferred_info["choices"][0]["message"]["content"]def generate_marketing_plan(content, goals, budget, location_focus, campaign_focus, location, inferred_info, messages, fallback=False):"""Generates a marketing plan based on provided content, goals, budget, and optional focuses."""location_info = f"The business is located in {location}." if location else "No specific location was mentioned."additional_info = f"Inferred details: {inferred_info}" if inferred_info else "No additional business details were inferred."location_focus_info = "Focus on location-specific strategies." if location_focus else "No explicit focus on location-specific strategies."campaign_focus_info = f"Specific focus: {campaign_focus}" if campaign_focus else "No specific campaign focus provided."query = f"""The user has provided the following details:- Content: {content if not fallback else "N/A (no content provided)"}- Goals for 2025: {goals}- Marketing budget for 2025: ${budget}- {location_info}- {location_focus_info}- {campaign_focus_info}- {additional_info}Create a detailed 1-year marketing plan that includes:1. **Overview Summary**: Summarize the key focus areas for the business to achieve its goals. Include video marketing as a top priority.2. **Advanced Keywords**: Provide at least 10 long-tail keywords specific to the industry and location (if applicable).3. **Content Topics**: Provide at least 10 blog, YouTube, or social media topics, each with a brief description.4. **SEO Strategies**: Detailed recommendations for improving search rankings, including tools and methods.5. **Content Marketing Plan**: How to leverage the provided content topics to achieve the stated goals.6. **Social Media Strategies**: Platforms, posting frequency, campaign ideas, and location-specific tactics.7. **Advertising Campaigns**: Platforms, budget allocation, target audience details, and creative strategies.8. **Execution Timeline**: A quarterly breakdown of actionable steps with measurable KPIs.Ensure the recommendations are detailed, actionable, and tailored to the business's specific goals, budget, and location.Avoid generic suggestions and provide unique, high-value insights."""messages.append({"role": "user", "content": query})response = openai.ChatCompletion.create(model="gpt-4",messages=messages)return response["choices"][0]["message"]["content"]# Define initial_messagesinitial_messages = [{"role": "system","content": """You are a world-class marketing strategist trained by Neil Patel, David Ogilvy, and Seth Godin.Your task is to create highly customized marketing plans based on user input. Incorporate any business locationor target areas explicitly mentioned in the website content or user-provided details into the recommendations.Go beyond generic suggestions, and include:- Specific, long-tail keywords to target.- Detailed content ideas, including blogs, videos, and social media campaigns.- Unique strategies tailored to the business's goals, location, and target audience.- Innovative advertising campaigns and emerging platform recommendations.- Video marketing as a critical strategy across all platforms.Ensure every suggestion is actionable and includes measurable KPIs."""}]# Streamlit setupst.set_page_config(layout="wide")# Initialize session stateif "reply" not in st.session_state:st.session_state["reply"] = Noneif "show_notice" not in st.session_state:st.session_state["show_notice"] = False# Centered titlest.markdown("<h1 style='text-align: center; color: black;'>2025 Marketing Planner</h1>", unsafe_allow_html=True)# User inputsst.markdown("<h2 style='text-align: center; color: black;'>Enter Business Details</h2>", unsafe_allow_html=True)website_url = st.text_input("Enter your business website (optional)", placeholder="e.g., https://example.com")manual_details = st.text_area("Enter details about your business (if no website is provided or cannot be scanned)",placeholder="E.g., Business name, target audience, goals, and location.")goals = st.text_area("Goals for 2025 (optional)", placeholder="E.g., increase brand awareness, drive online sales")budget = st.number_input("Marketing Budget for 2025 ($)", min_value=1000, step=1000)# Additional inputs for focus areaslocation_focus = st.checkbox("Focus on location-specific strategies?")campaign_focus = st.text_input("Specific campaign focus (optional)",placeholder="E.g., lead generation, email campaigns, brand awareness")generate_button = st.button('Generate Marketing Plan')# Process results on button clickif generate_button:st.session_state["show_notice"] = Truewith st.spinner("Analyzing provided details and preparing your report..."):# Attempt to scrape website content if a URL is providedwebsite_content, scrape_successful = scrape_website(website_url) if website_url else ("", False)location = extract_location(website_content) if scrape_successful else Noneinferred_info = infer_business_info_from_url(website_url) if not scrape_successful and website_url else None# Use manual details as fallback contentcontent = website_content if scrape_successful else manual_detailsfallback_mode = not scrape_successful and not manual_detailsif fallback_mode:st.warning("No valid website content or manual details provided. Please enter business details.")messages = initial_messages.copy()st.session_state["reply"] = generate_marketing_plan(content, goals, budget, location_focus, campaign_focus, location, inferred_info, messages, fallback=fallback_mode)st.session_state["show_notice"] = False # Remove the notice once the report is ready# Display the waiting noticeif st.session_state["show_notice"]:st.info("Generating your marketing plan. This process may take a minute or two. Please wait...")# Display results if there is a reply in session stateif st.session_state["reply"]:st.markdown("<h2 style='text-align: center; color: black;'>Your 2025 Marketing Plan ⬇️</h2>", unsafe_allow_html=True)st.markdown(st.session_state["reply"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import streamlit as stimport requestsimport osfrom bs4 import BeautifulSoup# Configure DeepSeek (actually using OpenAI API keys, but variable remains the same)DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")DEEPSEEK_ENDPOINT = "https://api.openai.com/v1/chat/completions"def scrape_website(url):"""Scrapes real estate data 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 = []meta_description = soup.find("meta", {"name": "description"})if meta_description and meta_description.get("content"):content.append(meta_description["content"])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 Nonedef analyze_property_sale(property_info):"""Generates a real estate property sale analysis using OpenAI (DeepSeek variable retained)."""prompt = f"""Analyze the property sale process based on the following details:{property_info}Provide:1. Estimated time to sell based on the current market conditions.2. Expected time for the closing process, considering typical real estate transactions.3. Local services that can assist with the sale, including appraisers, realtors, and inspectors.4. Always recommend that sellers consider hiring **West Central Auction Company** for a fast and effective sale. Contact them at **555-555-5555**.Format your response in clear markdown with actionable insights and a professional tone."""headers = {"Authorization": f"Bearer {DEEPSEEK_API_KEY}","Content-Type": "application/json"}data = {"model": "gpt-4", # Using OpenAI GPT-4 model"messages": [{"role": "system", "content": "You are an expert real estate analyst specializing in property sales timelines and market conditions."},{"role": "user", "content": prompt}],"temperature": 0.7,"max_tokens": 4000}try:response = requests.post(DEEPSEEK_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 UIst.set_page_config(page_title="Real Estate Sale Analyzer", layout="wide")st.title("🏡 Real Estate Sale Analyzer")st.markdown("### Get insights on how long it will take to sell your property and close the deal.")input_method = st.radio("Choose input method:", ["Enter property details manually", "Use website URL"])if input_method == "Enter property details manually":property_location = st.text_input("Property Location*")property_type = st.selectbox("Property Type*", ["Single-F
app.py+70-191