File size: 14,835 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
from PIL import Image, ImageTk
import threading
import sys
import os
import re
from pathlib import Path

# Add path to backend
sys.path.append(str(Path(__file__).parent.parent))

from backend.core.Facade import ScraperFacade


class ModernScraperApp:
    def __init__(self, root):
        self.root = root
        self.root.title("G-Maps Ultra Scraper")
        self.root.geometry("1400x900")
        
        # Style settings (Modern Look)
        self.style = ttk.Style()
        self.style.theme_use('clam')
        self.configure_styles()
        
        self.root.configure(bg='#F5F7FA')
        
        self.facade = ScraperFacade()
        self.is_running = False
        self.current_records = [] # Keep data in memory
        
        self.create_layout()
        
    def configure_styles(self):
        bg_color = '#F5F7FA'
        accent_color = '#4A90E2'
        text_color = '#333333'
        
        self.style.configure('TFrame', background=bg_color)
        self.style.configure('TLabelframe', background=bg_color, foreground=text_color)
        self.style.configure('TLabelframe.Label', background=bg_color, foreground='#555', font=('Segoe UI', 10, 'bold'))
        self.style.configure('TLabel', background=bg_color, foreground=text_color, font=('Segoe UI', 10))
        self.style.configure('Header.TLabel', font=('Segoe UI', 12, 'bold'), foreground='#2C3E50')
        self.style.configure('TButton', font=('Segoe UI', 10), padding=6)
        self.style.map('TButton', background=[('active', '#357ABD')])
        
        self.style.configure("Treeview", 
                             background="white",
                             foreground="black",
                             rowheight=30,
                             fieldbackground="white",
                             font=('Segoe UI', 10))
        self.style.configure("Treeview.Heading", font=('Segoe UI', 10, 'bold'))
        self.style.map("Treeview", background=[('selected', accent_color)])

    def create_layout(self):
        top_frame = ttk.Frame(self.root, padding="20 20 20 10")
        top_frame.pack(fill=tk.X)
        
        ttk.Label(top_frame, text="SEARCH QUERY:", style='Header.TLabel').pack(side=tk.LEFT, padx=(0, 10))
        
        self.search_entry = ttk.Entry(top_frame, font=("Segoe UI", 12), width=50)
        self.search_entry.pack(side=tk.LEFT, padx=5, ipady=5)
        self.search_entry.insert(0, "Lawyers London") 
        
        self.start_btn = tk.Button(top_frame, text="START SCRAPING", 
                                   bg='#4CAF50', fg='white', font=("Segoe UI", 10, "bold"),
                                   relief=tk.FLAT, padx=20, pady=5,
                                   command=self.start_process)
        self.start_btn.pack(side=tk.LEFT, padx=20)
        
        main_pane = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
        main_pane.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        left_frame = ttk.LabelFrame(main_pane, text=" Search Results ", padding=10)
        main_pane.add(left_frame, weight=2)
        
        columns = ('id', 'name', 'website', 'rating', 'reviews')
        self.tree = ttk.Treeview(left_frame, columns=columns, show='headings')
        
        self.tree.heading('id', text='#')
        self.tree.heading('name', text='Name')
        self.tree.heading('website', text='Website')
        self.tree.heading('rating', text='Rating')
        self.tree.heading('reviews', text='Reviews')
        
        self.tree.column('id', width=50, stretch=False)
        self.tree.column('name', width=200)
        self.tree.column('website', width=200)
        self.tree.column('rating', width=70, stretch=False)
        self.tree.column('reviews', width=70, stretch=False)
        
        scrollbar = ttk.Scrollbar(left_frame, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.configure(yscroll=scrollbar.set)
        
        self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        self.tree.bind('<<TreeviewSelect>>', self.on_row_click)
        
        right_frame = ttk.Frame(main_pane, padding=(10, 0))
        main_pane.add(right_frame, weight=1)
        
        img_group = ttk.LabelFrame(right_frame, text=" Website Screenshot ", padding=10)
        img_group.pack(fill=tk.BOTH, expand=False)
        
        self.image_label = ttk.Label(img_group, text="No Image", anchor="center")
        self.image_label.pack(fill=tk.BOTH, expand=True)
        img_group.pack_propagate(False)
        img_group.configure(height=350) 
        
        details_group = ttk.LabelFrame(right_frame, text=" Selected Item Parameters ", padding=15)
        details_group.pack(fill=tk.X, pady=15)
        
        self.detail_widgets = {}
        # Added "Website" field to list
        fields = [("Name", "name_val"), 
                  ("Website", "website_val"),
                  ("Rating", "rating_val"), 
                  ("Reviews", "reviews_val"), 
                  ("Phone (Parsed)", "phone_val"), 
                  ("Location (Parsed)", "loc_val")]
        
        for i, (label, key) in enumerate(fields):
            ttk.Label(details_group, text=f"{label}:", font=("Segoe UI", 9, 'bold')).grid(row=i, column=0, sticky='w', pady=5)
            entry = ttk.Entry(details_group, width=35)
            entry.grid(row=i, column=1, sticky='ew', padx=10, pady=5)
            self.detail_widgets[key] = entry
            
        # Action buttons (Website and WhatsApp)
        btn_frame = ttk.Frame(details_group)
        btn_frame.grid(row=len(fields), column=1, sticky='e', pady=10, padx=10)
        
        web_btn = tk.Button(btn_frame, text="Open Website", bg='#357ABD', fg='white',
                           font=("Segoe UI", 9, "bold"), relief=tk.FLAT,
                           command=self.open_website_from_details)
        web_btn.pack(side=tk.LEFT, padx=5)

        wa_btn = tk.Button(btn_frame, text="WhatsApp", bg='#25D366', fg='white',
                           font=("Segoe UI", 9, "bold"), relief=tk.FLAT,
                           command=self.open_whatsapp_from_details)
        wa_btn.pack(side=tk.LEFT, padx=5)
            
        bottom_ctrl = ttk.Frame(right_frame)
        bottom_ctrl.pack(fill=tk.BOTH, expand=True)
        
        act_frame = ttk.Frame(bottom_ctrl)
        act_frame.pack(fill=tk.X, pady=5)
        
        ttk.Button(act_frame, text="Save CSV", command=self.save_csv).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=2)
        ttk.Button(act_frame, text="Clear All", command=self.clear_data).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=2)
        
        log_group = ttk.LabelFrame(bottom_ctrl, text=" System Log ")
        log_group.pack(fill=tk.BOTH, expand=True, pady=5)
        
        self.console = scrolledtext.ScrolledText(log_group, height=8, bg='#1E1E1E', fg='#00FF00', font=("Consolas", 9))
        self.console.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        self.status_var = tk.StringVar(value="Ready")
        status_bar = ttk.Label(self.root, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W, padding=5)
        status_bar.pack(side=tk.BOTTOM, fill=tk.X)

    def log(self, message):
        self.console.insert(tk.END, f">> {message}\n")
        self.console.see(tk.END)

    def start_process(self):
        if self.is_running:
            return
        
        query = self.search_entry.get().strip()
        if not query:
            messagebox.showerror("Error", "Enter a search query")
            return
            
        self.is_running = True
        self.start_btn.config(state=tk.DISABLED, bg='#A5A5A5')
        self.status_var.set("Process running...")
        self.log(f"Start scraping: {query}")
        
        for item in self.tree.get_children():
            self.tree.delete(item)
        
        def run():
            count, screens = self.facade.start_scraping_process(query)
            self.root.after(0, lambda: self.finish_process(count, screens))
            
        thread = threading.Thread(target=run, daemon=True)
        thread.start()

    def finish_process(self, count, screens):
        self.is_running = False
        self.start_btn.config(state=tk.NORMAL, bg='#4CAF50')
        self.status_var.set(f"Done. Records: {count}, Screenshots: {screens}")
        self.log(f"Finished. Found: {count}, Screenshots: {screens}")
        self.refresh_table()

    def refresh_table(self):
        self.current_records = self.facade.get_all_records()
        for idx, record in enumerate(self.current_records, 1):
            self.tree.insert('', tk.END, values=(
                idx,
                record.get('name', 'Unknown'),
                record.get('website', ''),
                record.get('rating', ''),
                record.get('reviews', 0)
            ))

    def on_row_click(self, event):
        selection = self.tree.selection()
        if not selection:
            return
        
        item_id = self.tree.item(selection[0])
        values = item_id['values']
        if not values: return
        
        idx_table = int(values[0]) - 1
        
        if idx_table < len(self.current_records):
            record = self.current_records[idx_table]
            self.update_details_panel(record)
            self.show_screenshot(idx_table + 1)

    def update_details_panel(self, record):
        """

        Updated phone and location parsing

        """
        # Clear
        for entry in self.detail_widgets.values():
            entry.delete(0, tk.END)
            
        # Fill basic fields
        # FIX: Use (val or '') to convert None to empty string
        self.detail_widgets['name_val'].insert(0, record.get('name') or '')
        self.detail_widgets['website_val'].insert(0, record.get('website') or '') 
        self.detail_widgets['rating_val'].insert(0, str(record.get('rating') or ''))
        self.detail_widgets['reviews_val'].insert(0, str(record.get('reviews') or 0))
        
        raw_text = record.get('raw_text', [])
        phone = "Not found"
        location = "Not found"
        
        if raw_text:
            for line in raw_text:
                line = line.strip()
                if not line:
                    continue
                
                parts = []
                if '路' in line:
                    parts = line.split('路')
                else:
                    parts = [line]
                
                for part in parts:
                    clean_part = part.strip()
                    if any(x in clean_part for x in ["AM", "PM", "Opens", "Closes", "Open", "袟邪泻褉褘褌芯", "袨褌泻褉褘褌芯"]):
                        continue

                    digits_only = re.sub(r'\D', '', clean_part)
                    if len(digits_only) >= 9:
                        phone = clean_part
                        break
                
                if phone != "Not found":
                    break

            for line in raw_text:
                if '路' in line and not any(x in line for x in ["Open", "Closes", "AM", "PM"]):
                    if phone == "Not found" or phone not in line:
                         parts = line.split('路')
                         candidate = parts[-1].strip()
                         if len(candidate) > 5 and not candidate.replace('.','',1).isdigit():
                             location = candidate
                             break
                
                elif ',' in line and len(line) > 10 and line[0].isdigit():
                     if phone not in line and "reviews" not in line and "(" not in line:
                         location = line.strip()
                         break

        self.detail_widgets['phone_val'].insert(0, phone)
        self.detail_widgets['loc_val'].insert(0, location)

    def show_screenshot(self, index):
        filename = f"{index:03d}_screenshot.png"
        filepath = self.facade.config.SCREENSHOTS_DIR / filename
        
        if filepath.exists():
            try:
                pil_image = Image.open(filepath)
                target_w = 450
                w_percent = (target_w / float(pil_image.size[0]))
                target_h = int((float(pil_image.size[1]) * float(w_percent)))
                
                if target_h > 320:
                    target_h = 320
                    h_percent = (target_h / float(pil_image.size[1]))
                    target_w = int((float(pil_image.size[0]) * float(h_percent)))
                
                pil_image = pil_image.resize((target_w, target_h), Image.Resampling.LANCZOS)
                tk_image = ImageTk.PhotoImage(pil_image)
                
                self.image_label.configure(image=tk_image, text="")
                self.image_label.image = tk_image
            except Exception as e:
                self.log(f"Error loading image: {e}")
                self.image_label.configure(image='', text=f"Image Error")
        else:
            self.image_label.configure(image='', text="Screenshot missing")

    def open_whatsapp_from_details(self):
        phone = self.detail_widgets['phone_val'].get()
        if not phone or "Not found" in phone:
            messagebox.showwarning("WhatsApp", "Phone number not recognized")
            return
        self.facade.open_whatsapp(phone)
        
    def open_website_from_details(self):
        url = self.detail_widgets['website_val'].get()
        if not url:
            messagebox.showwarning("Website", "URL missing")
            return
        if not self.facade.open_website(url):
             messagebox.showerror("Error", "Failed to open link")

    def save_csv(self):
        if self.facade.export_to_csv("results.csv"):
            messagebox.showinfo("Success", "Data saved to output/results.csv")
        else:
            messagebox.showerror("Error", "Failed to save file")

    def clear_data(self):
        if messagebox.askyesno("Cleanup", "Delete all data and screenshots?"):
            self.facade.clear_all_data()
            self.current_records = []
            for item in self.tree.get_children():
                self.tree.delete(item)
            self.image_label.configure(image='', text="No Image")
            self.log("Data cleaned.")


def main():
    root = tk.Tk()
    app = ModernScraperApp(root)
    root.mainloop()


if __name__ == "__main__":
    main()