Spaces:
Sleeping
Sleeping
Download app.py from AbdullahIftikhar77/lead: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/spaces/AbdullahIftikhar77/lead/resolve/main/app.py
- Command line
-
hf download hf://spaces/AbdullahIftikhar77/lead/app.py
-
curl -L -o app.py https://huggingface.co/spaces/AbdullahIftikhar77/lead/resolve/main/app.py
10 kB
| import streamlit as st | |
| import os | |
| import re | |
| import time | |
| import requests | |
| import pandas as pd | |
| from datetime import datetime | |
| import io | |
| # Try importing optional dependencies with error handling | |
| try: | |
| from bs4 import BeautifulSoup | |
| BS4_AVAILABLE = True | |
| except ImportError: | |
| st.error("BeautifulSoup4 not available. Please install: pip install beautifulsoup4") | |
| BS4_AVAILABLE = False | |
| try: | |
| from googleapiclient.discovery import build | |
| GOOGLE_API_AVAILABLE = True | |
| except ImportError: | |
| st.error("Google API client not available. Please install: pip install google-api-python-client") | |
| GOOGLE_API_AVAILABLE = False | |
| # Set page config | |
| st.set_page_config( | |
| page_title="Email Scraper Tool", | |
| page_icon="π§", | |
| layout="wide" | |
| ) | |
| # GitHub-hosted LLM configuration (kept as is from your code) | |
| GITHUB_TOKEN = "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" | |
| AZURE_ENDPOINT = "https://models.github.ai/inference" | |
| AZURE_MODEL = "meta/Llama-4-Scout-17B-16E-Instruct" | |
| def extract_info_emails(text): | |
| """Extract 'info@' emails, avoid support/help emails.""" | |
| emails = re.findall(r"[a-zA-Z0-9._%+-]+@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}", text) | |
| filtered = [email for email in emails if email.startswith("info@") and not any(bad in email for bad in ["support", "help", "customer"])] | |
| return list(set(filtered)) | |
| def google_search(query, api_key, cse_id, num_pages=1): | |
| if not GOOGLE_API_AVAILABLE: | |
| st.error("Google API client not available") | |
| return [] | |
| try: | |
| service = build("customsearch", "v1", developerKey=api_key) | |
| all_links = [] | |
| for i in range(num_pages): | |
| start = i * 10 + 1 | |
| try: | |
| res = service.cse().list(q=query, cx=cse_id, start=start).execute() | |
| items = res.get("items", []) | |
| for item in items: | |
| link = item.get("link") | |
| if link: | |
| all_links.append(link) | |
| time.sleep(1) | |
| except Exception as e: | |
| st.error(f"Google Search API Error: {e}") | |
| break | |
| return all_links | |
| except Exception as e: | |
| st.error(f"Failed to initialize Google Search: {e}") | |
| return [] | |
| def fetch_page_text(url): | |
| if not BS4_AVAILABLE: | |
| st.error("BeautifulSoup4 not available") | |
| return "" | |
| try: | |
| headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"} | |
| response = requests.get(url, headers=headers, timeout=10) | |
| if response.status_code == 200: | |
| soup = BeautifulSoup(response.text, "html.parser") | |
| text = soup.get_text(separator=' ', strip=True) | |
| return text | |
| except Exception as e: | |
| st.warning(f"Failed to fetch {url}: {str(e)}") | |
| return "" | |
| def ask_llm(prompt): | |
| headers = { | |
| "Authorization": f"Bearer {GITHUB_TOKEN}", | |
| "Content-Type": "application/json" | |
| } | |
| payload = { | |
| "model": AZURE_MODEL, | |
| "messages": [ | |
| {"role": "system", "content": "You extract only professional info@ emails from raw web page content. Ignore support/help emails."}, | |
| {"role": "user", "content": prompt} | |
| ] | |
| } | |
| try: | |
| response = requests.post(f"{AZURE_ENDPOINT}/chat/completions", json=payload, headers=headers) | |
| if response.status_code == 200: | |
| return response.json()["choices"][0]["message"]["content"] | |
| else: | |
| st.error(f"LLM Error: {response.text}") | |
| return "" | |
| except Exception as e: | |
| st.error(f"LLM Request Error: {e}") | |
| return "" | |
| def run_email_scraper(custom_query, api_key, cse_id, num_pages): | |
| found_emails = [] | |
| progress_bar = st.progress(0) | |
| status_text = st.empty() | |
| urls = google_search(custom_query, api_key, cse_id, num_pages) | |
| st.success(f"π Found {len(urls)} URLs") | |
| if not urls: | |
| st.warning("No URLs found. Please check your search query and API credentials.") | |
| return [] | |
| for i, url in enumerate(urls): | |
| progress = (i + 1) / len(urls) | |
| progress_bar.progress(progress) | |
| status_text.text(f"π Processing: {url}") | |
| page_text = fetch_page_text(url) | |
| if page_text: | |
| prompt = f"""Extract only professional email addresses that begin with 'info@' from the following text. | |
| Ignore customer service/support/help-related emails. | |
| Text: | |
| {page_text[:3000]}""" # Limit token size for Groq models | |
| llm_output = ask_llm(prompt) | |
| extracted = extract_info_emails(llm_output) | |
| if extracted: | |
| st.success(f"β Emails Found from {url}: {extracted}") | |
| found_emails.extend(extracted) | |
| # Deduplicate | |
| unique_emails = list(set(found_emails)) | |
| progress_bar.progress(1.0) | |
| status_text.text("β Processing complete!") | |
| return unique_emails | |
| # Streamlit UI | |
| st.title("π§ Professional Email Scraper") | |
| st.markdown("Extract professional 'info@' email addresses from web search results") | |
| # Sidebar for configuration | |
| st.sidebar.header("π§ Configuration") | |
| # API Keys input | |
| google_api_key = st.sidebar.text_input( | |
| "Google API Key", | |
| type="password", | |
| help="Enter your Google Custom Search API key" | |
| ) | |
| google_cse_id = st.sidebar.text_input( | |
| "Google CSE ID", | |
| help="Enter your Google Custom Search Engine ID" | |
| ) | |
| # Search parameters | |
| num_pages = st.sidebar.slider( | |
| "Number of Search Pages", | |
| min_value=1, | |
| max_value=5, | |
| value=2, | |
| help="Each page contains ~10 results" | |
| ) | |
| # Main content area | |
| col1, col2 = st.columns([2, 1]) | |
| with col1: | |
| st.header("π Search Query") | |
| # Default query from your code | |
| default_query = '"email: info@" OR "contact: info@" "apparel" "USA" site:.com -job -careers -submit -privacy -terms' | |
| custom_query = st.text_area( | |
| "Search Query", | |
| value=default_query, | |
| height=100, | |
| help="Customize your search query to target specific industries or regions" | |
| ) | |
| with col2: | |
| st.header("π Instructions") | |
| st.markdown(""" | |
| 1. Enter your Google API credentials | |
| 2. Customize the search query if needed | |
| 3. Set the number of pages to scrape | |
| 4. Click 'Start Scraping' to begin | |
| 5. Download the results as CSV | |
| """) | |
| # Validation and scraping | |
| if st.button("π Start Scraping", type="primary"): | |
| # Check dependencies first | |
| if not BS4_AVAILABLE or not GOOGLE_API_AVAILABLE: | |
| st.error("β Missing required dependencies. Please check the installation.") | |
| elif not google_api_key or not google_cse_id: | |
| st.error("β Please provide both Google API Key and CSE ID") | |
| elif not custom_query.strip(): | |
| st.error("β Please provide a search query") | |
| else: | |
| st.info("π Starting email scraping process...") | |
| # Test API connection first | |
| try: | |
| test_urls = google_search("test", google_api_key, google_cse_id, 1) | |
| if test_urls is None: | |
| st.error("β Failed to connect to Google API. Please check your credentials.") | |
| st.stop() | |
| except Exception as e: | |
| st.error(f"β API Connection Error: {str(e)}") | |
| st.stop() | |
| # Run the scraper | |
| results = run_email_scraper(custom_query, google_api_key, google_cse_id, num_pages) | |
| if results: | |
| st.success(f"π― Found {len(results)} unique emails!") | |
| # Display results | |
| st.header("π§ Extracted Emails") | |
| df = pd.DataFrame(results, columns=["Email"]) | |
| st.dataframe(df, use_container_width=True) | |
| # Download functionality | |
| today_str = datetime.now().strftime("%Y-%m-%d") | |
| filename = f"emails_{today_str}.csv" | |
| csv_buffer = io.StringIO() | |
| df.to_csv(csv_buffer, index=False) | |
| csv_data = csv_buffer.getvalue() | |
| st.download_button( | |
| label="π₯ Download CSV", | |
| data=csv_data, | |
| file_name=filename, | |
| mime="text/csv" | |
| ) | |
| # Display individual emails for easy copying | |
| st.header("π Individual Emails") | |
| for email in results: | |
| st.code(email) | |
| else: | |
| st.warning("β οΈ No emails found. Try adjusting your search query or check your API credentials.") | |
| # Footer | |
| st.markdown("---") | |
| st.markdown(""" | |
| <div style='text-align: center'> | |
| <p>Built with Streamlit β’ Professional Email Scraper Tool</p> | |
| <p><small>Make sure to comply with website terms of service and applicable laws when scraping</small></p> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| # Additional information in expander | |
| with st.expander("βΉοΈ How to get Google API credentials"): | |
| st.markdown(""" | |
| **Google Custom Search API Key:** | |
| 1. Go to [Google Cloud Console](https://console.cloud.google.com/) | |
| 2. Create a new project or select an existing one | |
| 3. Enable the Custom Search JSON API | |
| 4. Create credentials (API Key) | |
| **Google Custom Search Engine ID:** | |
| 1. Go to [Google Custom Search Engine](https://cse.google.com/) | |
| 2. Create a new search engine | |
| 3. Add sites you want to search (or use *.com for all sites) | |
| 4. Copy the Search Engine ID from the control panel | |
| """) | |
| with st.expander("π§ Query Optimization Tips"): | |
| st.markdown(""" | |
| **Effective search patterns:** | |
| - `"info@" "industry_name"` - Target specific industries | |
| - `site:.com` - Limit to .com domains | |
| - `-careers -jobs` - Exclude job/career pages | |
| - `"contact us" "info@"` - Find contact pages | |
| - Add location terms like `"USA"`, `"California"`, etc. | |
| **Example queries:** | |
| - Fashion: `"info@" "fashion" "clothing" site:.com -careers` | |
| - Tech: `"info@" "software" "technology" site:.com -support` | |
| - Food: `"info@" "restaurant" "catering" site:.com -jobs` | |
| """) |