import os import sys import json import csv import webbrowser from pathlib import Path # Add paths for module imports sys.path.append(str(Path(__file__).parent.parent)) from scraper.google_maps_scraper import scrape_google_maps from scraper.screenshot_module import take_screenshots from utils.logger import Logger from utils.config import Config class ScraperFacade: """Facade for managing all scraping operations""" def __init__(self): self.config = Config() self.logger = Logger() self.data_file = self.config.DATA_FILE self.screenshots_dir = self.config.SCREENSHOTS_DIR def start_scraping_process(self, full_query): """ Start full cycle: scraping + screenshots full_query: Query string (e.g., 'Lawyers, London') """ try: self.logger.log(f"Starting process for: {full_query}") # 1. Clear old data self.clear_all_data() # 2. Start scraping count = scrape_google_maps(full_query, self.data_file, self.logger) self.logger.log(f"Scraping completed. Records found: {count}") # 3. If records exist, automatically start screenshots screenshots_count = 0 if count > 0: self.logger.log("Automatically starting screenshot capture...") screenshots_count = take_screenshots(self.data_file, self.screenshots_dir, self.logger) self.logger.log(f"Screenshots ready: {screenshots_count}") return count, screenshots_count except Exception as e: self.logger.log(f"Critical process error: {e}", level="ERROR") return 0, 0 def export_to_csv(self, csv_filename): """Export data to CSV""" try: if not os.path.exists(self.data_file): self.logger.log("Data file not found", level="ERROR") return False self.logger.log(f"Exporting to CSV: {csv_filename}") data = [] with open(self.data_file, 'r', encoding='utf-8') as f: for line in f: if line.strip(): data.append(json.loads(line)) if not data: self.logger.log("No data to export", level="WARNING") return False csv_path = os.path.join(self.config.OUTPUT_DIR, csv_filename) with open(csv_path, 'w', newline='', encoding='utf-8-sig') as csvfile: # Add phone and location to CSV if parsed fieldnames = ['name', 'website', 'maps_link', 'rating', 'reviews', 'phone', 'address'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for item in data: raw = item.get('raw_text', []) phone = '' address = '' # Note: Parsing logic for phone/address is currently in the UI layer in main.py # To export them here, you would need to move that logic to a shared utility or here. writer.writerow({ 'name': item.get('name', ''), 'website': item.get('website', ''), 'maps_link': item.get('maps_link', ''), 'rating': item.get('rating', ''), 'reviews': item.get('reviews', 0), 'phone': phone, 'address': address }) self.logger.log(f"CSV file saved: {csv_path}") return True except Exception as e: self.logger.log(f"CSV export error: {e}", level="ERROR") return False def clear_all_data(self): """Complete data cleanup (JSONL and screenshots)""" try: self.logger.log("Cleaning temporary files...") if os.path.exists(self.data_file): os.remove(self.data_file) if os.path.exists(self.screenshots_dir): for file in os.listdir(self.screenshots_dir): file_path = os.path.join(self.screenshots_dir, file) if os.path.isfile(file_path): os.remove(file_path) return True except Exception as e: self.logger.log(f"Error cleaning data: {e}", level="ERROR") return False def open_whatsapp(self, phone_number=None): """Open WhatsApp""" try: if phone_number: clean_number = ''.join(filter(str.isdigit, phone_number)) url = f"https://wa.me/{clean_number}" else: url = "https://web.whatsapp.com" self.logger.log(f"Opening WhatsApp: {url}") webbrowser.open(url) return True except Exception as e: self.logger.log(f"Error opening WhatsApp: {e}", level="ERROR") return False def open_website(self, url): """Open Website""" if not url or url == "None" or url == "": return False try: self.logger.log(f"Opening website: {url}") webbrowser.open(url) return True except Exception as e: self.logger.log(f"Error opening website: {e}", level="ERROR") return False def get_statistics(self): """Get statistics""" try: stats = { 'total_records': 0, 'with_website': 0, 'screenshots_count': 0 } if os.path.exists(self.data_file): with open(self.data_file, 'r', encoding='utf-8') as f: for line in f: if line.strip(): data = json.loads(line) stats['total_records'] += 1 if data.get('website'): stats['with_website'] += 1 if os.path.exists(self.screenshots_dir): stats['screenshots_count'] = len([f for f in os.listdir(self.screenshots_dir) if f.endswith('.png')]) return stats except Exception as e: self.logger.log(f"Error getting statistics: {e}", level="ERROR") return None def get_all_records(self): """Get all records""" try: if not os.path.exists(self.data_file): return [] records = [] with open(self.data_file, 'r', encoding='utf-8') as f: for line in f: if line.strip(): records.append(json.loads(line)) return records except Exception as e: self.logger.log(f"Error reading records: {e}", level="ERROR") return []