Free lead generation tool. Scrape Instagram, Twitch, TikTok, and LinkedIn profiles. Extract emails from bios, verify via SMTP, export to CSV.
initial commit
marcus24b28a5bbb72
diff --git a/.env.example b/.env.examplenew file mode 100644index 0000000..0688ea9--- /dev/null+++ b/.env.example@@ -0,0 +1,10 @@+# LinkedIn (get li_at cookie from browser DevTools > Application > Cookies)+# LINKEDIN_COOKIE=your_li_at_cookie_value++# Hunter.io API key (optional, free tier = 25 lookups/month)+# HUNTER_API_KEY=your_hunter_api_key++# Proxy support (optional, pick one)+# SCOUT_PROXY=http://user:pass@host:port+# SCOUT_PROXY_FILE=proxies.txt+# SCOUT_FREE_PROXY=truediff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..88ab9ed--- /dev/null+++ b/.gitignore@@ -0,0 +1,29 @@+__pycache__/+*.py[cod]+*.so+*.pyc++env/+venv/+.venv/++*.db+*.sqlite3++.env+proxies.txt+*.log+logs/++.DS_Store+Thumbs.db++exports/+*.csv++.claude/++.vscode/+.idea/+*.swp+*.swodiff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..c235d75--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Scout++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..c5d1df1--- /dev/null+++ b/README.md@@ -0,0 +1,98 @@+# Scout++[](https://www.python.org/downloads/)+[](https://opensource.org/licenses/MIT)+[](https://discord.gg/eneDNUbzcc)++> **Early access** — Scout is a CLI tool right now. A full web app with dashboard, CRM, and team features is in development. Looking for testers and feedback. Join the [Discord](https://discord.gg/eneDNUbzcc) or open an issue.++Lead generation tool for appointment setters. Scrapes profiles from Instagram, TikTok, and LinkedIn, enriches them with verified emails using SMTP verification and company domain detection, and exports to CSV.++++## Install++```bash+git clone https://github.com/kiryano/Scout.git+cd Scout+pip install -r requirements.txt+cp .env.example .env+```++## Usage++```bash+python scout.py+```++Interactive CLI for scraping profiles, enriching leads with contact info, and exporting to CSV.++## Features++- Instagram profile scraping (no login required)+- TikTok profile scraping+- LinkedIn profile scraping (session cookie)+- Email enrichment with SMTP verification (no paid API needed)+- Company domain detection from headline/bio+- Email pattern detection ([email protected] patterns)+- Lead scoring (0-100)+- Website deep scraping for contact info+- Bio link scraping (Linktree, WhatsApp, tel: links)+- CSV export+- Bulk scraping from username lists+- Proxy rotation and user-agent rotation++## LinkedIn Setup++1. Log into LinkedIn in Chrome+2. Open DevTools (F12) > Application > Cookies > linkedin.com+3. Copy the value of `li_at`+4. Add to `.env`:++```+LINKEDIN_COOKIE=your_li_at_cookie_value+```++## Proxy Setup++```+# Single proxy+SCOUT_PROXY=http://user:pass@host:port++# Rotating proxies from file (one per line)+SCOUT_PROXY_FILE=proxies.txt++# Free anonymous proxies (no config needed)+SCOUT_FREE_PROXY=true+```++## How Enrichment Works++After scraping, Scout enriches leads with verified email addresses:++1. Extracts email/phone from bio text+2. Scrapes the lead's website, /contact, and /about pages+3. Detects the company from their headline (e.g. "CEO at CompanyX")+4. Finds the company domain via DNS MX lookup+5. Detects the email pattern from existing emails on the site+6. Generates email candidates (first.last@, first@, etc.)+7. Verifies each candidate against the mail server via SMTP+8. Scores confidence 0-100% based on source and verification++No paid API required. Optional Hunter.io support for additional coverage.++## Limitations++- Instagram hashtag scraping is rate-limited; profile scraping works better+- TikTok may serve CAPTCHAs depending on region or IP+- LinkedIn cookies expire periodically+- SMTP verification may be blocked by some mail servers+- Free proxies are unreliable++## Community++[Discord](https://discord.gg/eneDNUbzcc)++## License++MITdiff --git a/app/__init__.py b/app/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/app/scrapers/__init__.py b/app/scrapers/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/app/scrapers/enrichment.py b/app/scrapers/enrichment.pynew file mode 100644index 0000000..79a21c2--- /dev/null+++ b/app/scrapers/enrichment.py@@ -0,0 +1,584 @@+import re+import dns.resolver+import smtplib+import socket+import logging+import threading+from typing import Optional, Dict, List, Tuple+from urllib.parse import urlparse+from concurrent.futures import ThreadPoolExecutor, as_completed++import httpx++from app.scrapers.stealth import random_user_agent, random_delay++logger = logging.getLogger(__name__)++EMAIL_RE = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'+EMAIL_BLACKLIST = ['example.com', 'test.com', 'email.com', 'youremail.com',+ 'sentry.io', 'wixpress.com', 'googleapis.com', 'w3.org',+ 'schema.org', 'gravatar.com', 'wordpress.com']+FILE_EXT_BLACKLIST = ['.png', '.jpg', '.gif', '.css', '.js', '.svg', '.webp', '.ico']+++class LeadEnricher:++ def __init__(self, hunter_api_key: Optional[str] = None):+ self.hunter_api_key = hunter_api_key+ self._domain_pattern_cache: Dict[str, Optional[str]] = {}+ self._cache_lock = threading.Lock()++ def enrich_lead(self, lead_data: Dict) -> Dict:+ enriched = lead_data.copy()+ email_candidates = []++ bio_contacts = self._extract_from_text(lead_data.get('bio', ''))+ if bio_contacts['email']:+ email_candidates.append((bio_contacts['email'], 'bio'))+ if bio_contacts['phone']:+ enriched['phone'] = bio_contacts['phone']++ website = lead_data.get('website', '')+ site_emails = []++ useless_domains = ['youtube.com', 'youtu.be', 'instagram.com', 'tiktok.com',+ 'twitter.com', 'x.com', 'facebook.com', 'linktr.ee',+ 'stan.store', 'beacons.ai', 'bit.ly', 'spotify.com']+ website_is_useful = website and not any(d in website.lower() for d in useless_domains)++ if website_is_useful:+ site_info = self._deep_scrape_website(website)+ site_emails = site_info.get('all_emails', [])++ if site_info['email']:+ email_candidates.append((site_info['email'], 'website'))+ if site_info['phone'] and not enriched.get('phone'):+ enriched['phone'] = site_info['phone']++ company_domain = None+ if not website_is_useful or not site_emails:+ company_domain = self._find_company_domain(lead_data)+ if company_domain:+ enriched['company_domain'] = company_domain+ if not website_is_useful:+ site_info = self._deep_scrape_website('https://' + company_domain)+ site_emails = site_info.get('all_emails', [])+ if site_info['email']:+ email_candidates.append((site_info['email'], 'website'))+ if site_info['phone'] and not enriched.get('phone'):+ enriched['phone'] = site_info['phone']++ work_domain = company_domain or (self._extract_domain(website) if website_is_useful else None)++ if lead_data.get('full_name') and work_domain:+ pattern_email = self._predict_email_from_pattern(+ lead_data['full_name'], 'https://' + work_domain, site_emails+ )+ if pattern_email:+ email_candidates.append((pattern_email, 'pattern'))++ if not email_candidates and lead_data.get('full_name') and work_domain:+ candidates = self._generate_email_candidates(lead_data['full_name'], 'https://' + work_domain)+ for c in candidates[:5]:+ smtp = self._verify_email_smtp(c)+ if smtp['exists'] and not smtp['accept_all']:+ email_candidates.append((c, 'smtp_guess'))+ break++ if self.hunter_api_key and lead_data.get('full_name') and website:+ hunter_email = self._find_with_hunter(+ lead_data.get('full_name'), website+ )+ if hunter_email:+ email_candidates.append((hunter_email, 'hunter.io'))++ bio_links = self._extract_bio_links(lead_data.get('bio', ''))+ if bio_links:+ for link in bio_links[:3]:+ link_info = self._scrape_link_page(link)+ if link_info['email']:+ email_candidates.append((link_info['email'], 'bio_link'))+ if link_info['phone'] and not enriched.get('phone'):+ enriched['phone'] = link_info['phone']++ if email_candidates:+ seen = set()+ unique = []+ for email, source in email_candidates:+ if email.lower() not in seen:+ seen.add(email.lower())+ unique.append((email, source))++ best = None+ best_score = -1++ for email, source in unique:+ scored = self._score_and_verify_email(+ email, source,+ pattern_match=(source == 'pattern'),+ site_emails_count=len(site_emails)+ )+ if scored['score'] > best_score:+ best_score = scored['score']+ best = scored++ if best:+ enriched['email'] = best['email']+ enriched['email_score'] = best['score']+ enriched['email_source'] = best['source']+ enriched['email_verified'] = best['verified']++ if not enriched.get('email') and lead_data.get('full_name') and work_domain:+ enriched['possible_emails'] = self._generate_email_candidates(+ lead_data['full_name'], 'https://' + work_domain+ )++ enriched['lead_score'] = self._calculate_lead_score(enriched)+ return enriched++ def _extract_from_text(self, text: str) -> Dict[str, Optional[str]]:+ result = {'email': None, 'phone': None}+ if not text:+ return result++ emails = re.findall(EMAIL_RE, text)+ valid = [e for e in emails if self._is_valid_email(e)]+ if valid:+ result['email'] = valid[0]++ phone = self._extract_phone_from_text(text)+ if phone:+ result['phone'] = phone++ return result++ def _is_valid_email(self, email: str) -> bool:+ lower = email.lower()+ if any(b in lower for b in EMAIL_BLACKLIST):+ return False+ if any(lower.endswith(ext) for ext in FILE_EXT_BLACKLIST):+ return False+ return True++ def _extract_phone_from_text(self, text: str) -> Optional[str]:+ tel_links = re.findall(r'href=["\']tel:([+\d\s\-().]+)', text)+ for tel in tel_links:+ clean = re.sub(r'[^\d+]', '', tel)+ if 10 <= len(clean) <= 15:+ return tel.strip()++ wa_links = re.findall(r'(?:wa\.me|api\.whatsapp\.com/send\?phone=)(\d+)', text)+ for num in wa_links:+ if 10 <= len(num) <= 15:+ return '+' + num++ visible = re.sub(r'<script[^>]*>.*?</script>', '', text, flags=re.DOTALL)+ visible = re.sub(r'<style[^>]*>.*?</style>', '', visible, flags=re.DOTALL)+ visible = re.sub(r'<[^>]+>', ' ', visible)+ visible = re.sub(r'\s+', ' ', visible)++ phone_patterns = [+ r'\+1[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}',+ r'\+?\d{1,3}[-.\s]\(?\d{3}\)[-.\s]?\d{3}[-.\s]?\d{4}',+ r'\(\d{3}\)[-.\s]?\d{3}[-.\s]?\d{4}',+ ]++ for pattern in phone_patterns:+ phones = re.findall(pattern, visible)+ for phone in phones:+ clean = re.sub(r'[^\d+]', '', phone)+ if 10 <= len(clean) <= 15:+ return phone.strip()++ return None++ def _fetch_page(self, url: str) -> Optional[str]:+ try:+ if not url.startswith('http'):+ url = 'https://' + url+ resp = httpx.get(url, timeout=10, headers={+ 'User-Agent': random_user_agent()+ }, follow_redirects=True)+ if resp.status_code == 200:+ return resp.text+ except Exception as e:+ logger.debug(f"Error fetching {url}: {e}")+ return None++ def _deep_scrape_website(self, website: str) -> Dict:+ result = {'email': None, 'phone': None, 'all_emails': []}++ if not website.startswith('http'):+ website = 'https://' + website++ pages_to_check = [+ website,+ website.rstrip('/') + '/contact',+ website.rstrip('/') + '/contact-us',+ website.rstrip('/') + '/about',+ website.rstrip('/') + '/about-us',+ ]++ all_emails = []++ for url in pages_to_check:+ html = self._fetch_page(url)+ if not html:+ continue++ emails = re.findall(EMAIL_RE, html)+ valid = [e for e in emails if self._is_valid_email(e)]+ all_emails.extend(valid)++ if not result['email'] and valid:+ result['email'] = valid[0]++ if not result['phone']:+ phone = self._extract_phone_from_text(html)+ if phone:+ result['phone'] = phone++ if result['email'] and result['phone']:+ break++ random_delay(0.3, 0.8)++ result['all_emails'] = list(set(all_emails))+ return result++ def _predict_email_from_pattern(self, full_name: str, website: str,+ site_emails: List[str]) -> Optional[str]:+ domain = self._extract_domain(website)+ if not domain:+ return None++ parts = full_name.lower().strip().split()+ if len(parts) < 2:+ return None++ first, last = parts[0], parts[-1]++ domain_emails = [e for e in site_emails if e.lower().endswith('@' + domain)]+ if not domain_emails:+ return None++ sample = domain_emails[0].lower()+ local = sample.split('@')[0]++ pattern = self._detect_pattern(local)+ if not pattern:+ return None++ predicted = self._apply_pattern(pattern, first, last, domain)+ if predicted and predicted.lower() not in [e.lower() for e in domain_emails]:+ return predicted++ return predicted++ def _detect_pattern(self, local_part: str) -> Optional[str]:+ if '.' in local_part:+ parts = local_part.split('.')+ if len(parts) == 2:+ if len(parts[0]) == 1:+ return 'f.last'+ return 'first.last'+ if re.match(r'^[a-z][a-z]+$', local_part):+ return 'first'+ if re.match(r'^[a-z]\.[a-z]+$', local_part):+ return 'f.last'+ return None++ def _apply_pattern(self, pattern: str, first: str, last: str, domain: str) -> Optional[str]:+ templates = {+ 'first.last': f'{first}.{last}@{domain}',+ 'first': f'{first}@{domain}',+ 'f.last': f'{first[0]}.{last}@{domain}',+ 'flast': f'{first[0]}{last}@{domain}',+ 'firstlast': f'{first}{last}@{domain}',+ }+ return templates.get(pattern)++ def _verify_email_smtp(self, email: str) -> Dict:+ parts = email.split('@')+ if len(parts) != 2 or not parts[1]:+ return {'exists': False, 'accept_all': False, 'score': 0}+ domain = parts[1]+ result = {'exists': False, 'accept_all': False, 'score': 0}++ try:+ mx_records = dns.resolver.resolve(domain, 'MX')+ mx_host = str(sorted(mx_records, key=lambda x: x.preference)[0].exchange).rstrip('.')+ except Exception:+ return result++ result['score'] += 10++ try:+ with smtplib.SMTP(timeout=10) as smtp:+ smtp.connect(mx_host, 25)+ smtp.helo('scout-verify.local')+ smtp.mail('[email protected]')+ code, msg = smtp.rcpt(email)++ if code == 250:+ result['exists'] = True+ result['score'] += 80++ fake = f'zzznonexistent999@{domain}'+ code2, _ = smtp.rcpt(fake)+ if code2 == 250:+ result['accept_all'] = True+ result['score'] = max(result['score'] - 40, 30)++ except (smtplib.SMTPServerDisconnected, smtplib.SMTPConnectError,+ socket.timeout, ConnectionRefusedError, OSError) as e:+ logger.debug(f"SMTP verify failed for {email}: {e}")+ result['score'] += 20++ return result++ def _score_and_verify_email(self, email: str, source: str,+ pattern_match: bool = False,+ site_emails_count: int = 0) -> Dict:+ score = 0++ if source == 'bio':+ score += 90+ elif source == 'website':+ score += 70+ elif source == 'contact_page':+ score += 60+ elif source == 'hunter.io':+ score += 80+ elif source == 'smtp_guess':+ score += 70+ elif source == 'bio_link':+ score += 65+ elif source == 'pattern':+ score += 40+ if site_emails_count >= 3:+ score += 15+ elif site_emails_count >= 1:+ score += 10++ smtp_result = self._verify_email_smtp(email)+ if smtp_result['exists']:+ score += 10+ if smtp_result['accept_all']:+ score -= 20++ return {+ 'email': email,+ 'score': min(score, 100),+ 'source': source,+ 'verified': smtp_result['exists'],+ 'accept_all': smtp_result['accept_all'],+ }++ def _extract_domain(self, website: str) -> Optional[str]:+ try:+ if not website.startswith('http'):+ website = 'https://' + website+ domain = urlparse(website).netloc or website+ return domain.replace('www.', '')+ except Exception:+ return None++ def _find_company_domain(self, lead_data: Dict) -> Optional[str]:+ company = lead_data.get('company', '')+ headline = lead_data.get('headline', '')+ bio = lead_data.get('bio', '')++ company_names = []++ if company:+ company_names.append(company)++ if headline:+ for marker in [' at ', ' @ ', ' - ']:+ if marker in headline:+ parts = headline.split(marker)+ if len(parts) >= 2:+ company_names.append(parts[-1].strip().rstrip('.'))++ patterns = [+ r'(?:CEO|CTO|COO|CFO|Founder|Owner|Director|President|Partner)\s+(?:of|at|@|-)\s+(.+?)(?:\s*[|,.]|$)',+ r'(?:at|@)\s+(.+?)(?:\s*[|,.]|$)',+ ]+ for p in patterns:+ m = re.search(p, headline, re.IGNORECASE)+ if m:+ company_names.append(m.group(1).strip())++ seen = set()+ unique_companies = []+ for name in company_names:+ clean = re.sub(r'[^\w\s]', '', name).strip()+ if clean and clean.lower() not in seen and len(clean) > 2:+ seen.add(clean.lower())+ unique_companies.append(clean)++ for name in unique_companies[:3]:+ domain = self._guess_domain(name)+ if domain:+ return domain++ return None++ def _guess_domain(self, company_name: str) -> Optional[str]:+ clean = company_name.lower().strip()+ clean = re.sub(r'\s+(inc|llc|ltd|co|corp|group|holdings)\.?$', '', clean, flags=re.IGNORECASE)+ slug = re.sub(r'[^a-z0-9]', '', clean)++ guesses = [+ f'{slug}.com',+ f'{slug}.io',+ f'{slug}.co',+ ]++ if ' ' in clean:+ parts = clean.split()+ if len(parts) == 2:+ guesses.append(f'{parts[0]}{parts[1]}.com')++ for domain in guesses:+ try:+ dns.resolver.resolve(domain, 'MX')+ return domain+ except Exception:+ continue++ return None++ def _generate_email_candidates(self, full_name: str, website: str) -> List[str]:+ domain = self._extract_domain(website)+ if not domain:+ return []++ parts = full_name.lower().strip().split()+ if len(parts) < 2:+ return []++ first, last = parts[0], parts[-1]+ return [+ f'{first}.{last}@{domain}',+ f'{first}@{domain}',+ f'{first}{last}@{domain}',+ f'{first[0]}{last}@{domain}',+ f'{first[0]}.{last}@{domain}',+ f'contact@{domain}',+ f'info@{domain}',+ ]++ def _extract_bio_links(self, bio: str) -> List[str]:+ if not bio:+ return []++ url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+|(?:linktr\.ee|stan\.store|beacons\.ai)/[^\s<>"{}|\\^`\[\]]+'+ links = re.findall(url_pattern, bio)++ cleaned = []+ for link in links:+ if not link.startswith('http'):+ link = 'https://' + link+ link = link.rstrip('.,;:!?)')+ cleaned.append(link)++ return cleaned++ def _scrape_link_page(self, url: str) -> Dict[str, Optional[str]]:+ result = {'email': None, 'phone': None}++ html = self._fetch_page(url)+ if not html:+ return result++ emails = re.findall(EMAIL_RE, html)+ valid = [e for e in emails if self._is_valid_email(e)]+ if valid:+ result['email'] = valid[0]++ phone = self._extract_phone_from_text(html)+ if phone:+ result['phone'] = phone++ return result++ def _find_with_hunter(self, full_name: Optional[str], website: Optional[str]) -> Optional[str]:+ if not self.hunter_api_key or not full_name or not website:+ return None++ try:+ domain = self._extract_domain(website)+ if not domain:+ return None++ parts = full_name.split()+ if len(parts) < 2:+ return None++ resp = httpx.get('https://api.hunter.io/v2/email-finder', params={+ 'domain': domain,+ 'first_name': parts[0],+ 'last_name': parts[-1],+ 'api_key': self.hunter_api_key,+ }, timeout=10)++ data = resp.json()+ if data.get('data', {}).get('email'):+ return data['data']['email']+ except Exception as e:+ logger.debug(f"Hunter.io error: {e}")++ return None++ def _calculate_lead_score(self, lead_data: Dict) -> int:+ score = 0++ if lead_data.get('email'):+ score += 30+ if lead_data.get('email_source') == 'hunter.io':+ score += 5+ if lead_data.get('phone'):+ score += 30+ if lead_data.get('is_verified'):+ score += 10++ followers = lead_data.get('follower_count', 0)+ if 5000 <= followers <= 50000:+ score += 15+ elif 1000 <= followers <= 100000:+ score += 10+ elif followers > 0:+ score += 5++ if lead_data.get('website'):+ score += 10++ bio = (lead_data.get('bio') or '').lower()+ keywords = ['coach', 'consultant', 'ceo', 'founder', 'entrepreneur',+ 'agency', 'business', 'owner', 'director', 'manager']+ if any(k in bio for k in keywords):+ score += 5++ return min(score, 100)++ def enrich_bulk(self, leads: List[Dict], max_workers: int = 3) -> List[Dict]:+ enriched = []++ with ThreadPoolExecutor(max_workers=max_workers) as executor:+ futures = {executor.submit(self.enrich_lead, lead): lead for lead in leads}++ for future in as_completed(futures):+ try:+ enriched.append(future.result())+ except Exception as e:+ logger.error(f"Enrichment error: {e}")+ enriched.append(futures[future])++ return enriched+++def enrich_lead(lead_data: Dict, hunter_api_key: Optional[str] = None) -> Dict:+ enricher = LeadEnricher(hunter_api_key=hunter_api_key)+ return enricher.enrich_lead(lead_data)diff --git a/app/scrapers/instagram.py b/app/scrapers/instagram.pynew file mode 100644index 0000000..b058ad2--- /dev/null+++ b/app/scrapers/instagram.py@@ -0,0 +1,304 @@+"""+Instagram Profile Scraper++Scrapes public Instagram profiles by parsing the HTML page directly.+Uses mobile user agents and rotating residential proxies to avoid rate limits.++Features:+- Extracts follower/following counts, bio, verification status, etc.+- Multiple regex patterns to handle Instagram's varying HTML structures+- Automatic retry with proxy rotation on extraction failures+- No authentication required (public profiles only)+"""++import requests+from typing import Dict, Optional+import logging+import re++from app.scrapers.stealth import get_requests_proxies++logger = logging.getLogger(__name__)++MOBILE_USER_AGENTS = [+ 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1',+ 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1',+ 'Mozilla/5.0 (Linux; Android 13; SM-G991B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36',+ 'Mozilla/5.0 (Linux; Android 12; Pixel 6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36',+]+++def scrape_profile_no_login(username: str, max_retries: int = 7) -> Optional[Dict]:+ """Scrape Instagram profile using mobile web HTML parsing (no API)."""+ import random+ import time++ url = f'https://www.instagram.com/{username}/'++ for attempt in range(max_retries):+ proxies = get_requests_proxies()++ headers = {+ 'User-Agent': random.choice(MOBILE_USER_AGENTS),+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',+ 'Accept-Language': 'en-US,en;q=0.9',+ }++ try:+ r = requests.get(url, headers=headers, proxies=proxies, timeout=20)++ if r.status_code == 404:+ logger.error(f"Profile @{username} not found")+ return None++ if r.status_code == 429:+ raise RuntimeError("Rate limited by Instagram (429). Wait a few minutes before scraping again.")++ if r.status_code != 200:+ logger.warning(f"HTTP {r.status_code} for @{username}, attempt {attempt + 1}/{max_retries}")+ if attempt < max_retries - 1:+ time.sleep(1)+ continue+ return None++ html = r.text++ # Check if redirected to login+ if '/accounts/login' in r.url or ('login' in html[:5000].lower() and 'password' in html[:5000].lower()):+ logger.error(f"Instagram requires login for @{username}")+ return None++ # Extract data from embedded JSON in HTML+ data = _extract_profile_from_html(html, username)++ if data:+ return data++ # Extraction failed - retry with new proxy/IP+ if attempt < max_retries - 1:+ logger.debug(f"Extraction failed for @{username}, retrying ({attempt + 1}/{max_retries})")+ time.sleep(1.0)+ continue++ logger.error(f"Could not extract profile data for @{username} after {max_retries} attempts")+ return None++ except requests.exceptions.Timeout:+ logger.warning(f"Timeout for @{username}, attempt {attempt + 1}/{max_retries}")+ if attempt < max_retries - 1:+ time.sleep(1)+ continue+ return None+ except RuntimeError:+ raise+ except Exception as e:+ err = str(e)+ if '429' in err:+ raise RuntimeError("Rate limited by Instagram (429). Wait a few minutes before scraping again.")+ logger.warning(f"Error scraping @{username}: {e}, attempt {attempt + 1}/{max_retries}")+ if attempt < max_retries - 1:+ time.sleep(1)+ continue+ return None++ return None+++def _extract_profile_from_html(html: str, username: str) -> Optional[Dict]:+ """Extract profile data from Instagram HTML page."""++ results = {}++ # Multiple patterns for username (Instagram changes HTML structure)+ username_patterns = [+ r'"username":"([^"]+)"',+ r'"owner":\{"username":"([^"]+)"',+ r'instagram\.com/([a-zA-Z0-9_.]+)/"\s*>',+ ]+ for pattern in username_patterns:+ match = re.search(pattern, html)+ if match and match.group(1).lower() == username.lower():+ results['username'] = match.group(1)+ break++ # Multiple patterns for full name+ name_patterns = [+ r'"full_name":"([^"]*)"',+ r'"name":"([^"]*)"',+ r'<title>([^(<]+)\s*\(@' + re.escape(username) + r'\)',+ ]+ for pattern in name_patterns:+ match = re.search(pattern, html, re.IGNORECASE)+ if match and 'full_name' not in results:+ results['full_name'] = match.group(1).strip()+ break++ # Multiple patterns for biography+ bio_patterns = [+ r'"biography":"([^"]*)"',+ r'"bio":"([^"]*)"',+ r'"description":"([^"]*)"',+ ]+ for pattern in bio_patterns:+ match = re.search(pattern, html)+ if match and 'biography' not in results:+ try:+ decoded = match.group(1).encode('utf-8').decode('unicode_escape')+ results['biography'] = decoded.encode('utf-16', 'surrogatepass').decode('utf-16')+ except (UnicodeDecodeError, UnicodeEncodeError):+ results['biography'] = match.group(1).replace('\\u', '')+ break++ # Multiple patterns for follower count+ follower_patterns = [+ r'"follower_count":(\d+)',+ r'"edge_followed_by":\{"count":(\d+)\}',+ r'"userInteractionCount":"?(\d+)"?.*?[Ff]ollow',+ r'followers["\s:]+(\d+)',+ ]+ for pattern in follower_patterns:+ match = re.search(pattern, html)+ if match and 'follower_count' not in results:+ results['follower_count'] = int(match.group(1))+ break++ # Multiple patterns for following count+ following_patterns = [+ r'"following_count":(\d+)',+ r'"edge_follow":\{"count":(\d+)\}',+ ]+ for pattern in following_patterns:+ match = re.search(pattern, html)+ if match and 'following_count' not in results:+ results['following_count'] = int(match.group(1))+ break++ # Multiple patterns for media/post count+ media_patterns = [+ r'"media_count":(\d+)',+ r'"edge_owner_to_timeline_media":\{"count":(\d+)\}',+ ]+ for pattern in media_patterns:+ match = re.search(pattern, html)+ if match and 'media_count' not in results:+ results['media_count'] = int(match.group(1))+ break++ # Meta description fallback: "11M Followers, 7,639 Following, 11K Posts"+ meta_patterns = [+ r'content="([\d.,]+[KMB]?)\s*Followers?,\s*([\d.,]+[KMB]?)\s*Following,\s*([\d.,]+[KMB]?)\s*Posts?',+ r'([\d.,]+[KMB]?)\s*Followers?\s*[,·]\s*([\d.,]+[KMB]?)\s*Following\s*[,·]\s*([\d.,]+[KMB]?)\s*Posts?',+ ]+ for pattern in meta_patterns:+ meta_match = re.search(pattern, html, re.IGNORECASE)+ if meta_match:+ if 'follower_count' not in results:+ results['follower_count'] = _parse_abbreviated_number(meta_match.group(1))+ if 'following_count' not in results:+ results['following_count'] = _parse_abbreviated_number(meta_match.group(2))+ if 'media_count' not in results:+ results['media_count'] = _parse_abbreviated_number(meta_match.group(3))+ break++ # Get verified status+ verified_patterns = [+ r'"is_verified":(true|false)',+ r'"verified":(true|false)',+ ]+ for pattern in verified_patterns:+ match = re.search(pattern, html)+ if match:+ results['is_verified'] = match.group(1) == 'true'+ break++ # Get private status+ match = re.search(r'"is_private":(true|false)', html)+ if match:+ results['is_private'] = match.group(1) == 'true'++ # Get business status+ match = re.search(r'"is_business_account":(true|false)', html)+ if match:+ results['is_business'] = match.group(1) == 'true'++ # Get external URL+ url_patterns = [+ r'"external_url":"([^"]+)"',+ r'"website":"([^"]+)"',+ r'"url":"(https?://[^"]+)"',+ ]+ for pattern in url_patterns:+ match = re.search(pattern, html)+ if match and 'external_url' not in results:+ try:+ decoded = match.group(1).replace('\\/', '/').encode('utf-8').decode('unicode_escape')+ results['external_url'] = decoded.encode('utf-16', 'surrogatepass').decode('utf-16')+ except (UnicodeDecodeError, UnicodeEncodeError):+ results['external_url'] = match.group(1).replace('\\/', '/')+ break++ # Must have follower count to be considered valid+ if 'follower_count' not in results or results.get('follower_count', 0) == 0:+ return None++ bio = results.get('biography', '')++ return {+ 'username': results.get('username', username),+ 'full_name': results.get('full_name', ''),+ 'bio': bio,+ 'follower_count': results.get('follower_count', 0),+ 'following_count': results.get('following_count', 0),+ 'post_count': results.get('media_count', 0),+ 'is_verified': results.get('is_verified', False),+ 'is_private': results.get('is_private', False),+ 'is_business': results.get('is_business', False),+ 'website': results.get('external_url', ''),+ 'email': _extract_email(bio),+ 'phone': _extract_phone(bio),+ 'platform': 'instagram',+ 'profile_url': f'https://www.instagram.com/{username}/',+ }+++def _parse_abbreviated_number(s: str) -> int:+ """Parse abbreviated numbers like 11M, 7.5K, 1.2B into integers."""+ s = s.strip().replace(',', '')+ multipliers = {'K': 1_000, 'M': 1_000_000, 'B': 1_000_000_000}++ for suffix, mult in multipliers.items():+ if s.upper().endswith(suffix):+ try:+ return int(float(s[:-1]) * mult)+ except (ValueError, IndexError):+ return 0++ try:+ return int(float(s))+ except ValueError:+ return 0+++def _extract_email(text: str) -> str:+ if not text:+ return ''+ pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'+ matches = re.findall(pattern, text)+ return matches[0] if matches else ''+++def _extract_phone(text: str) -> str:+ if not text:+ return ''+ patterns = [+ r'\+?\d{1,3}[-.\s]?\(?\d{1,4}\)?[-.\s]?\d{1,4}[-.\s]?\d{1,9}',+ r'\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}',+ r'\d{3}[-.\s]?\d{3}[-.\s]?\d{4}',+ ]+ for pattern in patterns:+ matches = re.findall(pattern, text)+ if matches:+ phone = re.sub(r'[^\d+]', '', matches[0])+ if len(phone) >= 10:+ return phone+ return ''diff --git a/app/scrapers/linkedin_scraper.py b/app/scrapers/linkedin_scraper.pynew file mode 100644index 0000000..c3d542d--- /dev/null+++ b/app/scrapers/linkedin_scraper.py@@ -0,0 +1,144 @@+import json+import logging+import os+import re+from datetime import datetime+from typing import Dict, Any, Optional++import httpx++from app.scrapers.stealth import random_user_agent, get_httpx_proxy++logger = logging.getLogger(__name__)++_session_cache = {'client': None, 'csrf': None}+++def _get_li_cookie() -> Optional[str]:+ cookie = os.environ.get('LINKEDIN_COOKIE', '').strip()+ if not cookie:+ return None+ if len(cookie) < 50:+ logger.warning("LinkedIn cookie seems too short - may be invalid")+ return cookie+++def _get_session():+ if _session_cache['client'] and _session_cache['csrf']:+ return _session_cache['client'], _session_cache['csrf']++ cookie = _get_li_cookie()+ if not cookie:+ return None, None++ client = httpx.Client(follow_redirects=True, timeout=20)+ client.cookies.set('li_at', cookie, domain='.linkedin.com')++ resp = client.get('https://www.linkedin.com/feed/')++ csrf = None+ for c in client.cookies.jar:+ if c.name == 'JSESSIONID':+ csrf = c.value.strip('"')+ break++ if not csrf:+ logger.error("Could not extract CSRF token from LinkedIn")+ return None, None++ _session_cache['client'] = client+ _session_cache['csrf'] = csrf+ return client, csrf+++def scrape_linkedin_profile(username: str) -> Dict[str, Any]:+ cookie = _get_li_cookie()+ if not cookie:+ return {+ 'status': 'error',+ 'message': 'LINKEDIN_COOKIE not set in .env. See README for setup instructions.',+ }++ client, csrf = _get_session()+ if not client or not csrf:+ return {'status': 'error', 'message': 'Failed to initialize LinkedIn session. Cookie may be expired.'}++ logger.info(f"Scraping LinkedIn profile: {username}")++ headers = {+ 'csrf-token': csrf,+ 'Accept': 'application/vnd.linkedin.normalized+json+2.1',+ 'x-li-lang': 'en_US',+ 'x-restli-protocol-version': '2.0.0',+ }++ url = f'https://www.linkedin.com/voyager/api/identity/dash/profiles?q=memberIdentity&memberIdentity={username}'++ try:+ resp = client.get(url, headers=headers)+ except httpx.RequestError as e:+ logger.error(f"Request error for {username}: {e}")+ return {'status': 'error', 'message': str(e)}++ if resp.status_code == 403:+ return {'status': 'error', 'message': f'Profile {username} is restricted or not accessible.'}+ if resp.status_code == 401:+ _session_cache.update({'client': None, 'csrf': None})+ return {'status': 'error', 'message': 'LinkedIn cookie expired. Re-export your li_at cookie.'}+ if resp.status_code != 200:+ return {'status': 'error', 'message': f'HTTP {resp.status_code} for {username}'}++ try:+ data = resp.json()+ except json.JSONDecodeError:+ return {'status': 'error', 'message': f'Invalid response for {username}'}++ profile_data = None+ for item in data.get('included', []):+ if 'firstName' in item and 'lastName' in item:+ profile_data = item+ break++ if not profile_data:+ return {'status': 'error', 'message': f'No profile data found for {username}'}++ summary = profile_data.get('summary', '')+ if not summary:+ multi = profile_data.get('multiLocaleSummary', {})+ summary = multi.get('en_US', '') if isinstance(multi, dict) else ''++ websites = []+ for w in profile_data.get('websites', []):+ if isinstance(w, dict) and w.get('url'):+ websites.append(w['url'])++ profile = {+ 'platform': 'linkedin',+ 'username': profile_data.get('publicIdentifier', username),+ 'full_name': f"{profile_data.get('firstName', '')} {profile_data.get('lastName', '')}".strip(),+ 'headline': profile_data.get('headline', ''),+ 'bio': summary,+ 'profile_url': f"https://www.linkedin.com/in/{profile_data.get('publicIdentifier', username)}/",+ 'is_verified': profile_data.get('showVerificationBadge', False),+ 'is_premium': profile_data.get('premium', False),+ 'is_influencer': profile_data.get('influencer', False),+ 'website': websites[0] if websites else '',+ 'email': _extract_email(summary),+ 'scraped_at': datetime.utcnow().isoformat(),+ }++ logger.info(f"Scraped {username}: {profile['full_name']} | {profile['headline'][:50]}")++ return {+ 'status': 'success',+ 'message': f'Scraped {username} successfully',+ 'profile': profile,+ }+++def _extract_email(text: str) -> str:+ if not text:+ return ''+ pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'+ matches = re.findall(pattern, text)+ return matches[0] if matches else ''diff --git a/app/scrapers/stealth.py b/app/scrapers/stealth.pynew file mode 100644index 0000000..2c048df--- /dev/null+++ b/app/scrapers/stealth.py@@ -0,0 +1,110 @@+import random+import time+import os+import logging+from typing import Optional++logger = logging.getLogger(__name__)++USER_AGENTS = [+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Safari/605.1.15',+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0',+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:133.0) Gecko/20100101 Firefox/133.0',+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',+ 'Mozilla/5.0 (X11; Linux x86_64; rv:133.0) Gecko/20100101 Firefox/133.0',+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0',+]++_free_proxy_cache = []+_free_proxy_last_fetch = 0+_FREE_PROXY_TTL = 300+++def random_user_agent() -> str:+ return random.choice(USER_AGENTS)+++def random_delay(min_seconds: float = 1.5, max_seconds: float = 4.5):+ time.sleep(random.uniform(min_seconds, max_seconds))+++def _fetch_free_proxies() -> list:+ global _free_proxy_cache, _free_proxy_last_fetch++ if _free_proxy_cache and (time.time() - _free_proxy_last_fetch) < _FREE_PROXY_TTL:+ return _free_proxy_cache++ try:+ from fp.fp import FreeProxy+ proxies = []+ for _ in range(5):+ try:+ p = FreeProxy(timeout=1, rand=True, anonym=True).get()+ if p:+ proxies.append(p)+ except Exception:+ continue++ if proxies:+ _free_proxy_cache = proxies+ _free_proxy_last_fetch = time.time()+ logger.info(f"Fetched {len(proxies)} free proxies")+ return proxies+ except ImportError:+ pass+ except Exception as e:+ logger.debug(f"Free proxy fetch failed: {e}")++ return []+++def get_proxy() -> Optional[str]:+ proxy = os.environ.get('SCOUT_PROXY')+ if proxy:+ return proxy++ proxy_file = os.environ.get('SCOUT_PROXY_FILE')+ if proxy_file and os.path.exists(proxy_file):+ with open(proxy_file, 'r') as f:+ proxies = [line.strip() for line in f if line.strip() and not line.startswith('#')]+ if proxies:+ return random.choice(proxies)++ if os.environ.get('SCOUT_FREE_PROXY', '').lower() in ('1', 'true', 'yes'):+ free_proxies = _fetch_free_proxies()+ if free_proxies:+ return random.choice(free_proxies)++ return None+++def get_httpx_proxy() -> Optional[str]:+ proxy = get_proxy()+ if not proxy:+ return None+ if not proxy.startswith('http'):+ proxy = f'http://{proxy}'+ return proxy+++def get_requests_proxies() -> Optional[dict]:+ proxy = get_proxy()+ if not proxy:+ return None+ if not proxy.startswith('http'):+ proxy = f'http://{proxy}'+ return {'http': proxy, 'https': proxy}+++def proxy_status() -> str:+ if os.environ.get('SCOUT_PROXY'):+ return 'custom'+ if os.environ.get('SCOUT_PROXY_FILE'):+ return 'file'+ if os.environ.get('SCOUT_FREE_PROXY', '').lower() in ('1', 'true', 'yes'):+ return 'free'+ return 'none'diff --git a/app/scrapers/tiktok_scraper.py b/app/scrapers/tiktok_scraper.pynew file mode 100644index 0000000..13eeee4--- /dev/null+++ b/app/scrapers/tiktok_scraper.py@@ -0,0 +1,107 @@+import json+import logging+import re+from datetime import datetime+from typing import Dict, Any++import httpx++from app.scrapers.stealth import random_user_agent, get_httpx_proxy++logger = logging.getLogger(__name__)++_client = None+++def _get_client():+ global _client+ if _client is None:+ proxy = get_httpx_proxy()+ _client = httpx.Client(follow_redirects=True, timeout=20, proxy=proxy)+ return _client+++def _build_headers() -> dict:+ return {+ 'User-Agent': random_user_agent(),+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',+ 'Accept-Language': 'en-US,en;q=0.9',+ 'Accept-Encoding': 'gzip, deflate',+ 'Sec-Fetch-Mode': 'navigate',+ 'Sec-Fetch-Site': 'none',+ 'Sec-Fetch-Dest': 'document',+ 'Sec-Ch-Ua-Mobile': '?0',+ 'Sec-Ch-Ua-Platform': '"Windows"',+ }+++def scrape_tiktok_profile(username: str) -> Dict[str, Any]:+ url = f'https://www.tiktok.com/@{username}'+ logger.info(f"Scraping TikTok profile: {url}")++ try:+ client = _get_client()+ resp = client.get(url, headers=_build_headers())+ resp.raise_for_status()+ except httpx.HTTPStatusError as e:+ logger.error(f"HTTP error for @{username}: {e.response.status_code}")+ return {'status': 'error', 'message': f'HTTP {e.response.status_code} for @{username}'}+ except httpx.RequestError as e:+ logger.error(f"Request error for @{username}: {e}")+ return {'status': 'error', 'message': str(e)}++ html = resp.text++ match = re.search(+ r'<script\s+id="__UNIVERSAL_DATA_FOR_REHYDRATION__"[^>]*>(.*?)</script>',+ html,+ re.DOTALL,+ )+ if not match:+ logger.warning(f"Could not find rehydration data for @{username}")+ return {+ 'status': 'error',+ 'message': f'Could not extract profile data for @{username}. Page may require CAPTCHA or profile does not exist.',+ }++ try:+ data = json.loads(match.group(1))+ except json.JSONDecodeError as e:+ logger.error(f"JSON parse error for @{username}: {e}")+ return {'status': 'error', 'message': f'Failed to parse profile data for @{username}'}++ try:+ user_detail = data['__DEFAULT_SCOPE__']['webapp.user-detail']+ user_info = user_detail['userInfo']+ user = user_info.get('user', {})+ stats = user_info.get('stats', {})+ except (KeyError, TypeError) as e:+ logger.error(f"Unexpected JSON structure for @{username}: {e}")+ return {'status': 'error', 'message': f'Unexpected data structure for @{username}'}++ profile = {+ 'platform': 'tiktok',+ 'username': user.get('uniqueId', username),+ 'full_name': user.get('nickname', ''),+ 'bio': user.get('signature', ''),+ 'profile_url': url,+ 'is_verified': user.get('verified', False),+ 'profile_pic_url': user.get('avatarLarger', ''),+ 'follower_count': stats.get('followerCount', 0),+ 'following_count': stats.get('followingCount', 0),+ 'likes_count': stats.get('heartCount', 0),+ 'video_count': stats.get('videoCount', 0),+ 'scraped_from': f'@{username}',+ 'scraped_at': datetime.utcnow().isoformat(),+ }++ logger.info(+ f"Scraped @{username}: {profile['full_name']} | "+ f"{profile['follower_count']} followers | {profile['likes_count']} likes"+ )++ return {+ 'status': 'success',+ 'message': f'Scraped @{username} successfully',+ 'profile': profile,+ }diff --git a/proxies.example.txt b/proxies.example.txtnew file mode 100644index 0000000..6578d98--- /dev/null+++ b/proxies.example.txt@@ -0,0 +1,12 @@+# Proxy file for Scout+# One proxy per line in the format: http://username:password@host:port+# Lines starting with # are ignored++# Example residential proxy (Smartproxy/Decodo):+# http://username:[email protected]:7000++# Example datacenter proxy:+# http://username:[email protected]:8080++# Example without auth:+# http://proxy.example.com:8080diff --git a/requirements.txt b/requirements.txtnew file mode 100644index 0000000..7c464b8--- /dev/null+++ b/requirements.txt@@ -0,0 +1,5 @@+requests>=2.28.0+httpx>=0.27.0+dnspython>=2.4.0+free-proxy>=1.1.1+rich>=13.7.0diff --git a/scout.py b/scout.pynew file mode 100644index 0000000..a502d66--- /dev/null+++ b/scout.py@@ -0,0 +1,884 @@+#!/usr/bin/env python3++import sys+import csv+import time+import os+from pathlib import Path++if sys.platform == 'win32':+ os.system('chcp 65001 >nul 2>&1')+ if hasattr(sys.stdout, 'reconfigure'):+ sys.stdout.reconfigure(encoding='utf-8', errors='replace')++sys.path.insert(0, str(Path(__file__).parent))++env_file = Path(__file__).parent / '.env'+if env_file.exists():+ with open(env_file) as _f:+ for _line in _f:+ _line = _line.strip()+ if _line and not _line.startswith('#') and '=' in _line:+ _key, _, _val = _line.partition('=')+ os.environ.setdefault(_key.strip(), _val.strip())++from rich.console import Console+from rich.panel import Panel+from rich.prompt import Prompt, Confirm+from rich.table import Table+from rich.progress import Progress, SpinnerColumn, TextColumn+from rich import box+from rich.layout import Layout+from rich.text import Text++from app.scrapers.instagram import scrape_profile_no_login+from app.scrapers.stealth import random_delay, proxy_status++console = Console()+++def _update_env(key, value):+ env_path = Path(__file__).parent / '.env'+ lines = []+ found = False+ if env_path.exists():+ with open(env_path) as f:+ for line in f:+ if line.strip().startswith(key + '='):+ lines.append(f'{key}={value}\n')+ found = True+ else:+ lines.append(line)+ if not found:+ lines.append(f'{key}={value}\n')+ with open(env_path, 'w') as f:+ f.writelines(lines)+ os.environ[key] = value+++def enrich_profiles(profiles):+ if not profiles:+ return profiles++ if not Confirm.ask("\n[cyan][+] Enrich leads with contact info?[/cyan]", default=True):+ return profiles++ from app.scrapers.enrichment import LeadEnricher+ hunter_key = os.environ.get('HUNTER_API_KEY', '').strip() or None+ enricher = LeadEnricher(hunter_api_key=hunter_key)++ console.print()+ emails_found = 0+ phones_found = 0++ with Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ console=console+ ) as progress:+ task = progress.add_task("[cyan]Enriching leads...", total=len(profiles))++ enriched = []+ for p in profiles:+ had_email = bool(p.get('email'))+ had_phone = bool(p.get('phone'))++ result = enricher.enrich_lead(p)+ enriched.append(result)++ if result.get('email') and not had_email:+ emails_found += 1+ if result.get('phone') and not had_phone:+ phones_found += 1++ progress.advance(task)++ console.print()++ summary_parts = []+ if emails_found:+ summary_parts.append(f"[green]{emails_found} emails found[/green]")+ if phones_found:+ summary_parts.append(f"[green]{phones_found} phones found[/green]")+ if not summary_parts:+ summary_parts.append("[yellow]No new contact info found[/yellow]")++ scores = [e.get('lead_score', 0) for e in enriched]+ avg_score = sum(scores) // len(scores) if scores else 0+ summary_parts.append(f"[cyan]Avg lead score: {avg_score}/100[/cyan]")++ console.print(Panel(+ "\n".join(summary_parts),+ title="[bold]Enrichment Results[/bold]",+ border_style="cyan"+ ))++ email_leads = [e for e in enriched if e.get('email')]+ if email_leads:+ console.print()+ t = Table(show_header=True, box=box.SIMPLE)+ t.add_column("Lead", style="white")+ t.add_column("Email", style="cyan")+ t.add_column("Confidence", style="green")+ t.add_column("Source", style="dim")+ t.add_column("Verified", style="yellow")++ for e in email_leads:+ name = e.get('full_name') or e.get('username', '?')+ email_score = e.get('email_score', 0)+ score_color = 'green' if email_score >= 70 else 'yellow' if email_score >= 40 else 'red'+ verified = 'Yes' if e.get('email_verified') else 'No'+ t.add_row(+ name[:25],+ e['email'],+ f"[{score_color}]{email_score}%[/{score_color}]",+ e.get('email_source', '?'),+ verified+ )++ console.print(t)++ return enriched+++def show_header():+ header_text = Text()+ header_text.append("SCOUT", style="bold cyan")+ header_text.append("\n", style="white")+ header_text.append("Free Lead Generation Tool", style="dim")++ console.print(Panel(+ header_text,+ box=box.DOUBLE,+ style="cyan",+ padding=(1, 20)+ ))++ console.print(+ "[dim]Lead generation for appointment setters[/dim]",+ justify="center"+ )+ console.print(+ "[dim]Discord: [cyan]https://discord.gg/eneDNUbzcc[/cyan][/dim]",+ justify="center"+ )++ ps = proxy_status()+ if ps == 'custom':+ console.print("[green]Proxy: custom[/green]", justify="center")+ elif ps == 'file':+ console.print("[green]Proxy: rotating from file[/green]", justify="center")+ elif ps == 'free':+ console.print("[yellow]Proxy: free (unstable)[/yellow]", justify="center")+ else:+ console.print("[dim]Proxy: off (set SCOUT_PROXY or SCOUT_FREE_PROXY=true)[/dim]", justify="center")++ console.print()+++def show_menu():+ table = Table(+ show_header=False,+ box=box.ROUNDED,+ style="cyan",+ padding=(0, 2)+ )++ table.add_column("Option", style="bold cyan", width=8)+ table.add_column("Description", style="white")++ table.add_row("1", "[>] Scrape Instagram Profiles")+ table.add_row("2", "[#] Scrape TikTok Profiles")+ table.add_row("3", "[~] Scrape LinkedIn Profiles (Cookie Required)")+ table.add_row("4", "[*] Scrape from Username List File")+ table.add_row("5", "[~] View Recent Exports")+ table.add_row("6", "[⚙] Proxy Settings")+ table.add_row("7", "[X] Exit")++ console.print(Panel(+ table,+ title="[bold]What would you like to do?[/bold]",+ border_style="cyan",+ box=box.ROUNDED+ ))+ console.print()+++def scrape_instagram_interactive():+ console.print()+ console.print(Panel(+ "[bold]Instagram Profile Scraper[/bold]\n[dim]No login required![/dim]",+ style="green",+ box=box.DOUBLE+ ))+ console.print()++ console.print("[cyan]Enter Instagram usernames (one per line)[/cyan]")+ console.print("[dim]Press Enter on empty line when done[/dim]")+ console.print()++ usernames = []+ while True:+ username = Prompt.ask("Username", default="")+ if not username:+ break+ username = username.replace('@', '').strip()+ if username:+ usernames.append(username)+ console.print(f"[green]✓[/green] Added @{username}")++ if not usernames:+ console.print("[yellow]⚠ No usernames entered![/yellow]")+ return++ console.print()+ console.print(f"[bold cyan]Scraping {len(usernames)} profiles...[/bold cyan]")+ console.print()++ profiles = []+ successful = 0++ with Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ console=console+ ) as progress:++ for i, username in enumerate(usernames, 1):+ task = progress.add_task(+ f"[cyan]Scraping @{username}...",+ total=None+ )++ try:+ profile = scrape_profile_no_login(username)++ if profile:+ profiles.append(profile)+ successful += 1++ progress.update(task, description=f"[green]✓ @{username}")++ info_table = Table(show_header=False, box=None, padding=(0, 2))+ info_table.add_column(style="dim")+ info_table.add_column(style="white")++ info_table.add_row("Followers:", f"{profile['follower_count']:,}")++ if profile.get('full_name'):+ info_table.add_row("Name:", profile['full_name'][:50])++ if profile.get('bio'):+ bio = profile['bio'][:80] + '...' if len(profile['bio']) > 80 else profile['bio']+ info_table.add_row("Bio:", bio)++ if profile.get('email'):+ info_table.add_row("Email:", profile['email'])++ if profile.get('website'):+ info_table.add_row("Website:", profile['website'])++ console.print(info_table)+ console.print()++ else:+ progress.update(task, description=f"[red]✗ @{username} - Failed")++ except RuntimeError as e:+ progress.update(task, description=f"[red]✗ @{username} - Rate Limited")+ console.print(f"\n[bold red]⚠ {e}[/bold red]")+ break+ except Exception as e:+ progress.update(task, description=f"[red]✗ @{username} - Error")+ console.print(f"[dim red]Error: {str(e)[:100]}[/dim red]")++ if i < len(usernames):+ random_delay(1.5, 4.0)++ console.print()++ if profiles:+ result_panel = Panel(+ f"[bold green]Successfully scraped {successful}/{len(usernames)} profiles[/bold green]",+ style="green",+ box=box.DOUBLE+ )+ console.print(result_panel)+ console.print()++ profiles = enrich_profiles(profiles)++ if Confirm.ask("[+] Export to CSV?", default=True):+ timestamp = time.strftime("%Y%m%d_%H%M%S")+ filename = f"instagram_export_{timestamp}.csv"++ with open(filename, 'w', newline='', encoding='utf-8') as f:+ if profiles:+ writer = csv.DictWriter(f, fieldnames=profiles[0].keys())+ writer.writeheader()+ writer.writerows(profiles)++ console.print()+ console.print(Panel(+ f"[bold]Exported to:[/bold] [cyan]{filename}[/cyan]\n"+ f"[bold]Total profiles:[/bold] {len(profiles)}",+ title="[green]✓ Export Complete[/green]",+ border_style="green"+ ))+ else:+ console.print(Panel(+ "[yellow]No profiles were scraped successfully[/yellow]",+ style="yellow"+ ))+++def scrape_tiktok_interactive():+ from app.scrapers.tiktok_scraper import scrape_tiktok_profile++ console.print()+ console.print(Panel(+ "[bold]TikTok Profile Scraper[/bold]",+ style="magenta",+ box=box.DOUBLE+ ))+ console.print()++ console.print("[cyan]Enter TikTok usernames (one per line, without @)[/cyan]")+ console.print("[dim]Press Enter on empty line when done[/dim]")+ console.print()++ usernames = []+ while True:+ username = Prompt.ask("Username", default="")+ if not username:+ break+ username = username.replace('@', '').strip()+ if username:+ usernames.append(username)+ console.print(f"[green]✓[/green] Added @{username}")++ if not usernames:+ console.print("[yellow]⚠ No usernames entered![/yellow]")+ return++ console.print()+ console.print(f"[bold cyan]Scraping {len(usernames)} TikTok profiles...[/bold cyan]")+ console.print()++ profiles = []++ with Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ console=console+ ) as progress:++ for i, username in enumerate(usernames, 1):+ task = progress.add_task(+ f"[cyan]Scraping @{username}...",+ total=None+ )++ try:+ result = scrape_tiktok_profile(username)++ if result.get('status') == 'success' and result.get('profile'):+ profile = result['profile']+ profiles.append(profile)++ progress.update(task, description=f"[green]✓ @{username}")++ info_table = Table(show_header=False, box=None, padding=(0, 2))+ info_table.add_column(style="dim")+ info_table.add_column(style="white")++ if profile.get('follower_count'):+ info_table.add_row("Followers:", str(profile['follower_count']))+ if profile.get('full_name'):+ info_table.add_row("Name:", profile['full_name'][:50])+ if profile.get('bio'):+ bio = profile['bio'][:80] + '...' if len(profile['bio']) > 80 else profile['bio']+ info_table.add_row("Bio:", bio)++ console.print(info_table)+ console.print()+ else:+ progress.update(task, description=f"[red]✗ @{username} - Failed")++ except Exception as e:+ progress.update(task, description=f"[red]✗ @{username} - Error")+ console.print(f"[dim red]Error: {str(e)[:100]}[/dim red]")++ if i < len(usernames):+ random_delay(2.0, 5.0)++ console.print()++ if profiles:+ result_panel = Panel(+ f"[bold green]Successfully scraped {len(profiles)}/{len(usernames)} profiles[/bold green]",+ style="green",+ box=box.DOUBLE+ )+ console.print(result_panel)+ console.print()++ profiles = enrich_profiles(profiles)++ if Confirm.ask("[+] Export to CSV?", default=True):+ timestamp = time.strftime("%Y%m%d_%H%M%S")+ filename = f"tiktok_export_{timestamp}.csv"++ with open(filename, 'w', newline='', encoding='utf-8') as f:+ if profiles:+ writer = csv.DictWriter(f, fieldnames=profiles[0].keys())+ writer.writeheader()+ writer.writerows(profiles)++ console.print()+ console.print(Panel(+ f"[bold]Exported to:[/bold] [cyan]{filename}[/cyan]\n"+ f"[bold]Total profiles:[/bold] {len(profiles)}",+ title="[green]✓ Export Complete[/green]",+ border_style="green"+ ))+ else:+ console.print(Panel(+ "[yellow]No profiles were scraped successfully[/yellow]",+ style="yellow"+ ))+++def scrape_linkedin_interactive():+ from app.scrapers.linkedin_scraper import scrape_linkedin_profile++ console.print()++ cookie = os.environ.get('LINKEDIN_COOKIE', '').strip()+ if not cookie:+ console.print(Panel(+ "[bold yellow]LinkedIn Cookie Required[/bold yellow]\n\n"+ "[cyan]To scrape LinkedIn profiles:[/cyan]\n"+ "1. Open Chrome and go to linkedin.com (logged in)\n"+ "2. Press F12 > Application > Cookies > linkedin.com\n"+ "3. Copy the value of [white]li_at[/white]\n"+ "4. Add to your .env file: [white]LINKEDIN_COOKIE=your_value_here[/white]\n"+ "5. Restart Scout",+ style="yellow",+ box=box.DOUBLE+ ))+ console.print()+ return++ console.print(Panel(+ "[bold]LinkedIn Profile Scraper[/bold]\n[dim]Using session cookie[/dim]",+ style="blue",+ box=box.DOUBLE+ ))+ console.print()++ console.print("[cyan]Enter LinkedIn usernames or profile URLs (one per line)[/cyan]")+ console.print("[dim]Press Enter on empty line when done[/dim]")+ console.print()++ usernames = []+ while True:+ entry = Prompt.ask("Username/URL", default="")+ if not entry:+ break+ entry = entry.strip().rstrip('/')+ if '/in/' in entry:+ entry = entry.split('/in/')[-1]+ entry = entry.lstrip('@').strip()+ if entry:+ usernames.append(entry)+ console.print(f"[green]✓[/green] Added {entry}")++ if not usernames:+ console.print("[yellow]No usernames entered![/yellow]")+ return++ console.print()+ console.print(f"[bold cyan]Scraping {len(usernames)} LinkedIn profiles...[/bold cyan]")+ console.print()++ profiles = []++ with Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ console=console+ ) as progress:++ for i, username in enumerate(usernames, 1):+ task = progress.add_task(+ f"[cyan]Scraping {username}...",+ total=None+ )++ try:+ result = scrape_linkedin_profile(username)++ if result.get('status') == 'success' and result.get('profile'):+ profile = result['profile']+ profiles.append(profile)++ progress.update(task, description=f"[green]✓ {username}")++ info_table = Table(show_header=False, box=None, padding=(0, 2))+ info_table.add_column(style="dim")+ info_table.add_column(style="white")++ if profile.get('full_name'):+ info_table.add_row("Name:", profile['full_name'][:50])+ if profile.get('headline'):+ info_table.add_row("Title:", profile['headline'][:80])+ if profile.get('company'):+ info_table.add_row("Company:", profile['company'][:50])+ if profile.get('location'):+ info_table.add_row("Location:", profile['location'][:50])+ if profile.get('email'):+ info_table.add_row("Email:", profile['email'])++ console.print(info_table)+ console.print()+ else:+ msg = result.get('message', 'Failed')+ progress.update(task, description=f"[red]✗ {username} - {msg[:60]}")++ except Exception as e:+ progress.update(task, description=f"[red]✗ {username} - Error")+ console.print(f"[dim red]Error: {str(e)[:100]}[/dim red]")++ if i < len(usernames):+ random_delay(3.0, 6.0)++ console.print()++ if profiles:+ result_panel = Panel(+ f"[bold green]Successfully scraped {len(profiles)}/{len(usernames)} profiles[/bold green]",+ style="green",+ box=box.DOUBLE+ )+ console.print(result_panel)+ console.print()++ profiles = enrich_profiles(profiles)++ if Confirm.ask("[+] Export to CSV?", default=True):+ timestamp = time.strftime("%Y%m%d_%H%M%S")+ filename = f"linkedin_export_{timestamp}.csv"++ with open(filename, 'w', newline='', encoding='utf-8') as f:+ if profiles:+ writer = csv.DictWriter(f, fieldnames=profiles[0].keys())+ writer.writeheader()+ writer.writerows(profiles)++ console.print()+ console.print(Panel(+ f"[bold]Exported to:[/bold] [cyan]{filename}[/cyan]\n"+ f"[bold]Total profiles:[/bold] {len(profiles)}",+ title="[green]✓ Export Complete[/green]",+ border_style="green"+ ))+ else:+ console.print(Panel(+ "[yellow]No profiles were scraped successfully[/yellow]",+ style="yellow"+ ))+++def scrape_from_file():+ console.print()+ console.print(Panel(+ "[bold]Scrape from File[/bold]\n[dim]Bulk scrape from username list[/dim]",+ style="blue",+ box=box.DOUBLE+ ))+ console.print()++ filename = Prompt.ask("[>] Enter filename", default="usernames.txt")++ try:+ with open(filename, 'r') as f:+ usernames = [line.strip().replace('@', '') for line in f if line.strip()]++ console.print(f"\n[cyan]Found {len(usernames)} usernames in {filename}[/cyan]")++ if not Confirm.ask("Continue?", default=True):+ return++ console.print()+ console.print(f"[bold cyan]Scraping {len(usernames)} profiles...[/bold cyan]")+ console.print()++ profiles = []+ successful = 0++ with Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ console=console+ ) as progress:++ for i, username in enumerate(usernames, 1):+ task = progress.add_task(+ f"[{i}/{len(usernames)}] @{username}...",+ total=None+ )++ try:+ profile = scrape_profile_no_login(username)++ if profile:+ profiles.append(profile)+ successful += 1+ progress.update(+ task,+ description=f"[green]✓[/green] [{i}/{len(usernames)}] @{username} ({profile['follower_count']:,} followers)"+ )+ else:+ progress.update(+ task,+ description=f"[red]✗[/red] [{i}/{len(usernames)}] @{username}"+ )++ except Exception as e:+ progress.update(+ task,+ description=f"[red]✗[/red] [{i}/{len(usernames)}] @{username}"+ )++ if i < len(usernames):+ random_delay(1.5, 4.0)++ console.print()++ if profiles:+ timestamp = time.strftime("%Y%m%d_%H%M%S")+ export_filename = f"instagram_export_{timestamp}.csv"++ with open(export_filename, 'w', newline='', encoding='utf-8') as f:+ if profiles:+ writer = csv.DictWriter(f, fieldnames=profiles[0].keys())+ writer.writeheader()+ writer.writerows(profiles)++ console.print(Panel(+ f"[bold green]SUCCESS![/bold green]\n\n"+ f"[bold]Scraped:[/bold] {successful}/{len(usernames)} profiles\n"+ f"[bold]Exported to:[/bold] [cyan]{export_filename}[/cyan]",+ title="[green]✓ Complete[/green]",+ border_style="green",+ box=box.DOUBLE+ ))+ else:+ console.print(Panel(+ "[yellow]No profiles were scraped successfully[/yellow]",+ style="yellow"+ ))++ except FileNotFoundError:+ console.print(f"\n[red]✗ Error: File '{filename}' not found![/red]")+ except Exception as e:+ console.print(f"\n[red]✗ Error: {e}[/red]")+++def proxy_settings():+ import httpx as _httpx++ console.print()+ console.print(Panel(+ "[bold]Proxy Settings[/bold]\n[dim]Configure proxy for scraping[/dim]",+ style="yellow",+ box=box.DOUBLE+ ))+ console.print()++ ps = proxy_status()+ current_proxy = os.environ.get('SCOUT_PROXY', '')+ free_enabled = os.environ.get('SCOUT_FREE_PROXY', '').lower() in ('1', 'true', 'yes')++ status_table = Table(show_header=False, box=None, padding=(0, 2))+ status_table.add_column(style="dim")+ status_table.add_column(style="white")+ status_table.add_row("Status:", f"[green]{ps}[/green]" if ps != 'none' else "[red]off[/red]")+ if current_proxy:+ status_table.add_row("Proxy URL:", current_proxy[:60])+ status_table.add_row("Free Proxy:", "[green]on[/green]" if free_enabled else "[dim]off[/dim]")+ console.print(status_table)+ console.print()++ options = Table(show_header=False, box=box.ROUNDED, style="yellow", padding=(0, 2))+ options.add_column("Option", style="bold yellow", width=8)+ options.add_column("Description", style="white")+ options.add_row("1", "Set proxy URL")+ options.add_row("2", "Toggle free proxy on/off")+ options.add_row("3", "Test proxy connection")+ options.add_row("4", "Remove proxy")+ options.add_row("5", "Back to menu")+ console.print(options)+ console.print()++ choice = Prompt.ask("[bold yellow]Choose[/bold yellow]", choices=["1", "2", "3", "4", "5"], default="5")++ if choice == '1':+ url = Prompt.ask("[>] Enter proxy URL (e.g. http://user:pass@host:port)")+ if url.strip():+ _update_env('SCOUT_PROXY', url.strip())+ console.print(f"[green]✓ Proxy set to {url.strip()[:60]}[/green]")++ elif choice == '2':+ if free_enabled:+ _update_env('SCOUT_FREE_PROXY', 'false')+ console.print("[yellow]✓ Free proxy disabled[/yellow]")+ else:+ _update_env('SCOUT_FREE_PROXY', 'true')+ console.print("[green]✓ Free proxy enabled[/green]")++ elif choice == '3':+ console.print("[cyan]Testing proxy connection...[/cyan]")+ from app.scrapers.stealth import get_proxy+ px = get_proxy()+ if not px:+ console.print("[yellow]No proxy configured. Testing direct connection...[/yellow]")+ try:+ resp = _httpx.get('https://httpbin.org/ip', timeout=10)+ ip = resp.json().get('origin', '?')+ console.print(f"[green]✓ Direct connection works. Your IP: {ip}[/green]")+ except Exception as e:+ console.print(f"[red]✗ Connection failed: {str(e)[:100]}[/red]")+ else:+ console.print(f"[dim]Trying proxy: {px[:60]}[/dim]")+ proxy_url = px if px.startswith('http') else f'http://{px}'+ try:+ resp = _httpx.get('https://httpbin.org/ip', proxy=proxy_url, timeout=10, verify=False)+ ip = resp.json().get('origin', '?')+ console.print(f"[green]✓ Proxy works! IP: {ip}[/green]")+ except Exception as e:+ console.print(f"[red]✗ Proxy failed: {str(e)[:80]}[/red]")+ if free_enabled:+ console.print("[yellow]Free proxies are unreliable. Trying another...[/yellow]")+ from app.scrapers.stealth import _fetch_free_proxies+ import random as _rand+ proxies = _fetch_free_proxies()+ for p in proxies[:3]:+ p_url = p if p.startswith('http') else f'http://{p}'+ console.print(f"[dim]Trying: {p_url[:60]}[/dim]")+ try:+ resp = _httpx.get('https://httpbin.org/ip', proxy=p_url, timeout=8, verify=False)+ ip = resp.json().get('origin', '?')+ console.print(f"[green]✓ Found working proxy! IP: {ip}[/green]")+ break+ except Exception:+ console.print(f"[red]✗ Dead[/red]")+ else:+ console.print("[red]All free proxies failed. Use a paid proxy for reliability.[/red]")++ elif choice == '4':+ _update_env('SCOUT_PROXY', '')+ _update_env('SCOUT_FREE_PROXY', 'false')+ os.environ.pop('SCOUT_PROXY', None)+ console.print("[yellow]✓ Proxy removed[/yellow]")+++def view_exports():+ console.print()+ console.print(Panel(+ "[bold]Recent Exports[/bold]\n[dim]Your scraped data[/dim]",+ style="magenta",+ box=box.DOUBLE+ ))+ console.print()++ csv_files = list(Path('.').glob('*_export_*.csv'))++ if not csv_files:+ console.print("[yellow]No exports found yet![/yellow]")+ console.print("[dim]Run a scrape to create your first export[/dim]")+ return++ csv_files.sort(key=lambda x: x.stat().st_mtime, reverse=True)++ table = Table(+ title=f"[bold]Found {len(csv_files)} exports[/bold]",+ box=box.ROUNDED,+ style="magenta"+ )++ table.add_column("#", style="dim", width=4)+ table.add_column("Filename", style="cyan")+ table.add_column("Size", style="white", justify="right")+ table.add_column("Date", style="dim")++ for i, file in enumerate(csv_files[:10], 1):+ size = file.stat().st_size / 1024+ mtime = time.strftime("%Y-%m-%d %H:%M", time.localtime(file.stat().st_mtime))++ table.add_row(+ str(i),+ file.name,+ f"{size:.1f} KB",+ mtime+ )++ console.print(table)+++def main():+ console.clear()+ show_header()++ while True:+ show_menu()++ try:+ choice = Prompt.ask(+ "[bold cyan]Choose an option[/bold cyan]",+ choices=["1", "2", "3", "4", "5", "6", "7"],+ default="1"+ )++ if choice == '1':+ scrape_instagram_interactive()++ elif choice == '2':+ scrape_tiktok_interactive()++ elif choice == '3':+ scrape_linkedin_interactive()++ elif choice == '4':+ scrape_from_file()++ elif choice == '5':+ view_exports()++ elif choice == '6':+ proxy_settings()++ elif choice == '7':+ console.print()+ console.print(Panel(+ "[bold]Thanks for using Scout![/bold]\n\n"+ "[cyan]Star us on GitHub:[/cyan]\n"+ "[link]https://github.com/kiryano/scout[/link]\n\n"+ "[dim]Made by appointment setters, for appointment setters[/dim]",+ style="green",+ box=box.DOUBLE+ ))+ break++ console.print("\n" + "─" * 60 + "\n")++ except KeyboardInterrupt:+ console.print("\n\n[yellow]Exiting...[/yellow]")+ break+ except Exception as e:+ console.print(f"\n[red]✗ Error: {e}[/red]")+++if __name__ == '__main__':+ main()diff --git a/screenshot.png b/screenshot.pngnew file mode 100644index 0000000..b19abb5Binary files /dev/null and b/screenshot.png differ