File size: 7,456 Bytes
1f8acec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
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 []