Jorakz commited on
Commit
1f8acec
·
verified ·
1 Parent(s): 44f0c2f

Upload 26 files

Browse files
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+
9
+ # Virtual environments
10
+ .venv
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.12
Dockerfile ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ # 1. Установка системных зависимостей (от имени ROOT)
4
+ USER root
5
+ RUN apt-get update && apt-get install -y \
6
+ wget \
7
+ gnupg \
8
+ && rm -rf /var/lib/apt/lists/*
9
+
10
+ # 2. Подготовка рабочей директории с правами для пользователя 1000
11
+ WORKDIR /app
12
+ RUN useradd -m -u 1000 user
13
+ RUN chown -R user:user /app
14
+
15
+ # 3. Установка зависимостей Python
16
+ COPY requirements.txt .
17
+ RUN pip install --no-cache-dir -r requirements.txt
18
+
19
+ # 4. Установка Playwright и браузеров (нужен Root для зависимостей)
20
+ RUN playwright install chromium
21
+ RUN playwright install-deps chromium
22
+
23
+ # 5. Копирование кода приложения и смена владельца
24
+ COPY --chown=user . /app
25
+
26
+ # 6. Переключение на пользователя (требование Hugging Face)
27
+ USER user
28
+ ENV PATH="/home/user/.local/bin:$PATH"
29
+
30
+ # 7. Запуск на порту 7860 (требование Hugging Face)
31
+ CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,10 +0,0 @@
1
- ---
2
- title: README
3
- emoji: 📚
4
- colorFrom: pink
5
- colorTo: pink
6
- sdk: docker
7
- pinned: false
8
- ---
9
-
10
- Edit this `README.md` markdown file to author your organization card.
 
 
 
 
 
 
 
 
 
 
 
docker-compose.yml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ scraper-app:
5
+ build: .
6
+ container_name: gmaps-scraper
7
+ ports:
8
+ - "8501:8501"
9
+ volumes:
10
+ # Важно: пробрасываем output, чтобы файлы сохранялись на вашем диске,
11
+ # а не исчезали внутри контейнера
12
+ - ./output:/app/output
13
+
14
+ # (Опционально) Можно пробросить код, чтобы редактировать без пересборки:
15
+ # - ./src:/app/src
16
+ environment:
17
+ - HEADLESS_MODE=true
18
+ restart: unless-stopped
pyproject.toml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "map"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ dependencies = []
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ streamlit
2
+ pandas
3
+ playwright
4
+ Pillow
src/backend/core/Facade.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import json
4
+ import csv
5
+ import webbrowser
6
+ from pathlib import Path
7
+
8
+ # Add paths for module imports
9
+ sys.path.append(str(Path(__file__).parent.parent))
10
+
11
+ from scraper.google_maps_scraper import scrape_google_maps
12
+ from scraper.screenshot_module import take_screenshots
13
+ from utils.logger import Logger
14
+ from utils.config import Config
15
+
16
+
17
+ class ScraperFacade:
18
+ """Facade for managing all scraping operations"""
19
+
20
+ def __init__(self):
21
+ self.config = Config()
22
+ self.logger = Logger()
23
+ self.data_file = self.config.DATA_FILE
24
+ self.screenshots_dir = self.config.SCREENSHOTS_DIR
25
+
26
+ def start_scraping_process(self, full_query):
27
+ """
28
+ Start full cycle: scraping + screenshots
29
+ full_query: Query string (e.g., 'Lawyers, London')
30
+ """
31
+ try:
32
+ self.logger.log(f"Starting process for: {full_query}")
33
+
34
+ # 1. Clear old data
35
+ self.clear_all_data()
36
+
37
+ # 2. Start scraping
38
+ count = scrape_google_maps(full_query, self.data_file, self.logger)
39
+
40
+ self.logger.log(f"Scraping completed. Records found: {count}")
41
+
42
+ # 3. If records exist, automatically start screenshots
43
+ screenshots_count = 0
44
+ if count > 0:
45
+ self.logger.log("Automatically starting screenshot capture...")
46
+ screenshots_count = take_screenshots(self.data_file, self.screenshots_dir, self.logger)
47
+ self.logger.log(f"Screenshots ready: {screenshots_count}")
48
+
49
+ return count, screenshots_count
50
+
51
+ except Exception as e:
52
+ self.logger.log(f"Critical process error: {e}", level="ERROR")
53
+ return 0, 0
54
+
55
+ def export_to_csv(self, csv_filename):
56
+ """Export data to CSV"""
57
+ try:
58
+ if not os.path.exists(self.data_file):
59
+ self.logger.log("Data file not found", level="ERROR")
60
+ return False
61
+
62
+ self.logger.log(f"Exporting to CSV: {csv_filename}")
63
+
64
+ data = []
65
+ with open(self.data_file, 'r', encoding='utf-8') as f:
66
+ for line in f:
67
+ if line.strip():
68
+ data.append(json.loads(line))
69
+
70
+ if not data:
71
+ self.logger.log("No data to export", level="WARNING")
72
+ return False
73
+
74
+ csv_path = os.path.join(self.config.OUTPUT_DIR, csv_filename)
75
+
76
+ with open(csv_path, 'w', newline='', encoding='utf-8-sig') as csvfile:
77
+ # Add phone and location to CSV if parsed
78
+ fieldnames = ['name', 'website', 'maps_link', 'rating', 'reviews', 'phone', 'address']
79
+ writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
80
+
81
+ writer.writeheader()
82
+ for item in data:
83
+ raw = item.get('raw_text', [])
84
+ phone = ''
85
+ address = ''
86
+ # Note: Parsing logic for phone/address is currently in the UI layer in main.py
87
+ # To export them here, you would need to move that logic to a shared utility or here.
88
+
89
+ writer.writerow({
90
+ 'name': item.get('name', ''),
91
+ 'website': item.get('website', ''),
92
+ 'maps_link': item.get('maps_link', ''),
93
+ 'rating': item.get('rating', ''),
94
+ 'reviews': item.get('reviews', 0),
95
+ 'phone': phone,
96
+ 'address': address
97
+ })
98
+
99
+ self.logger.log(f"CSV file saved: {csv_path}")
100
+ return True
101
+ except Exception as e:
102
+ self.logger.log(f"CSV export error: {e}", level="ERROR")
103
+ return False
104
+
105
+ def clear_all_data(self):
106
+ """Complete data cleanup (JSONL and screenshots)"""
107
+ try:
108
+ self.logger.log("Cleaning temporary files...")
109
+
110
+ if os.path.exists(self.data_file):
111
+ os.remove(self.data_file)
112
+
113
+ if os.path.exists(self.screenshots_dir):
114
+ for file in os.listdir(self.screenshots_dir):
115
+ file_path = os.path.join(self.screenshots_dir, file)
116
+ if os.path.isfile(file_path):
117
+ os.remove(file_path)
118
+
119
+ return True
120
+ except Exception as e:
121
+ self.logger.log(f"Error cleaning data: {e}", level="ERROR")
122
+ return False
123
+
124
+ def open_whatsapp(self, phone_number=None):
125
+ """Open WhatsApp"""
126
+ try:
127
+ if phone_number:
128
+ clean_number = ''.join(filter(str.isdigit, phone_number))
129
+ url = f"https://wa.me/{clean_number}"
130
+ else:
131
+ url = "https://web.whatsapp.com"
132
+
133
+ self.logger.log(f"Opening WhatsApp: {url}")
134
+ webbrowser.open(url)
135
+ return True
136
+ except Exception as e:
137
+ self.logger.log(f"Error opening WhatsApp: {e}", level="ERROR")
138
+ return False
139
+
140
+ def open_website(self, url):
141
+ """Open Website"""
142
+ if not url or url == "None" or url == "":
143
+ return False
144
+ try:
145
+ self.logger.log(f"Opening website: {url}")
146
+ webbrowser.open(url)
147
+ return True
148
+ except Exception as e:
149
+ self.logger.log(f"Error opening website: {e}", level="ERROR")
150
+ return False
151
+
152
+ def get_statistics(self):
153
+ """Get statistics"""
154
+ try:
155
+ stats = {
156
+ 'total_records': 0,
157
+ 'with_website': 0,
158
+ 'screenshots_count': 0
159
+ }
160
+
161
+ if os.path.exists(self.data_file):
162
+ with open(self.data_file, 'r', encoding='utf-8') as f:
163
+ for line in f:
164
+ if line.strip():
165
+ data = json.loads(line)
166
+ stats['total_records'] += 1
167
+ if data.get('website'):
168
+ stats['with_website'] += 1
169
+
170
+ if os.path.exists(self.screenshots_dir):
171
+ stats['screenshots_count'] = len([f for f in os.listdir(self.screenshots_dir)
172
+ if f.endswith('.png')])
173
+
174
+ return stats
175
+ except Exception as e:
176
+ self.logger.log(f"Error getting statistics: {e}", level="ERROR")
177
+ return None
178
+
179
+ def get_all_records(self):
180
+ """Get all records"""
181
+ try:
182
+ if not os.path.exists(self.data_file):
183
+ return []
184
+
185
+ records = []
186
+ with open(self.data_file, 'r', encoding='utf-8') as f:
187
+ for line in f:
188
+ if line.strip():
189
+ records.append(json.loads(line))
190
+ return records
191
+ except Exception as e:
192
+ self.logger.log(f"Error reading records: {e}", level="ERROR")
193
+ return []
src/backend/core/__pycache__/Facade.cpython-311.pyc ADDED
Binary file (11.4 kB). View file
 
src/backend/core/__pycache__/Facade.cpython-312.pyc ADDED
Binary file (10.2 kB). View file
 
src/backend/scraper/__pycache__/google_maps_scraper.cpython-311.pyc ADDED
Binary file (8.38 kB). View file
 
src/backend/scraper/__pycache__/google_maps_scraper.cpython-312.pyc ADDED
Binary file (6.91 kB). View file
 
src/backend/scraper/__pycache__/screenshot_module.cpython-311.pyc ADDED
Binary file (6.59 kB). View file
 
src/backend/scraper/__pycache__/screenshot_module.cpython-312.pyc ADDED
Binary file (6.07 kB). View file
 
src/backend/scraper/google_maps_scraper.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+ from playwright.sync_api import sync_playwright
4
+ import os
5
+
6
+ def save_to_jsonl(data, filename):
7
+ """Save data to JSONL format"""
8
+ with open(filename, 'a', encoding='utf-8') as f:
9
+ json.dump(data, f, ensure_ascii=False)
10
+ f.write('\n')
11
+
12
+
13
+ def scrape_google_maps(search_query, output_file, logger):
14
+ """Google Maps Scraping"""
15
+ scraped_count = 0
16
+ is_headless = os.environ.get("HEADLESS_MODE", "False").lower() == "true"
17
+ with sync_playwright() as p:
18
+
19
+
20
+ browser = p.chromium.launch(headless=is_headless)
21
+ context = browser.new_context(
22
+ locale="en-US",
23
+ viewport={"width": 1920, "height": 1080}
24
+ )
25
+ page = context.new_page()
26
+
27
+ logger.log(f"Search: {search_query}")
28
+ page.goto("https://www.google.com/maps?hl=en", timeout=60000)
29
+
30
+ # Accept cookies
31
+ try:
32
+ consent = page.locator("button", has_text="Accept all").or_(
33
+ page.locator("button", has_text="Принять все")
34
+ )
35
+ if consent.is_visible(timeout=3000):
36
+ consent.first.click()
37
+ except:
38
+ pass
39
+
40
+ # Search
41
+ try:
42
+ page.wait_for_selector("input#searchboxinput", timeout=10000)
43
+ page.fill("input#searchboxinput", search_query)
44
+ page.keyboard.press("Enter")
45
+ except Exception as e:
46
+ logger.log(f"Search error: {e}", level="ERROR")
47
+ browser.close()
48
+ return 0
49
+
50
+ feed_selector = 'div[role="feed"]'
51
+ try:
52
+ page.wait_for_selector(feed_selector, timeout=15000)
53
+ except:
54
+ logger.log("Result list not found", level="ERROR")
55
+ browser.close()
56
+ return 0
57
+
58
+ last_height = 0
59
+ no_change_count = 0
60
+ scraped_links = set()
61
+
62
+ logger.log("Scrolling and collecting data...")
63
+
64
+ while True:
65
+ # Scrolling
66
+ try:
67
+ page.locator(feed_selector).evaluate("el => el.scrollTo(0, el.scrollHeight)")
68
+ except:
69
+ break
70
+
71
+ page.wait_for_timeout(2000)
72
+ cards = page.locator('div[role="article"]').all()
73
+ logger.log(f"Cards on screen: {len(cards)}")
74
+
75
+ for card in cards:
76
+ try:
77
+ # Google Maps Link
78
+ link_locator = card.locator("a").first
79
+ maps_href = link_locator.get_attribute("href") if link_locator.count() > 0 else None
80
+
81
+ if not maps_href or maps_href in scraped_links:
82
+ continue
83
+
84
+ # Get raw text of the entire card (for later phone and address analysis)
85
+ full_text_str = card.inner_text()
86
+ # Split into lines for convenience
87
+ raw_text_list = full_text_str.split('\n')
88
+
89
+ # Name
90
+ aria_label = card.get_attribute("aria-label")
91
+ name = aria_label if aria_label else "No Name"
92
+
93
+ # Find Website
94
+ website = None
95
+ website_btn = card.locator('a[data-value="Website"]').or_(
96
+ card.locator('a[data-value="Сайт"]')
97
+ )
98
+
99
+ if website_btn.count() > 0:
100
+ website = website_btn.first.get_attribute("href")
101
+ else:
102
+ links = card.locator("a").all()
103
+ for lnk in links:
104
+ href = lnk.get_attribute("href")
105
+ if href and "google.com/maps" not in href and "google.com/search" not in href:
106
+ website = href
107
+ break
108
+
109
+ # Rating and Reviews
110
+ rating = None
111
+ reviews_count = 0
112
+ star_loc = card.locator('span[role="img"]').first
113
+ star_aria = star_loc.get_attribute("aria-label") if star_loc.count() > 0 else ""
114
+
115
+ if star_aria:
116
+ rating_match = re.search(r'(\d+[.,]\d+)', star_aria)
117
+ if rating_match:
118
+ rating = rating_match.group(1).replace(',', '.')
119
+
120
+ clean_aria = star_aria.replace('\xa0', ' ')
121
+ rev_match = re.search(r'(\d+)\s*(reviews?|отзыв)', clean_aria, re.IGNORECASE)
122
+ if rev_match:
123
+ reviews_count = int(rev_match.group(1))
124
+
125
+ if reviews_count == 0:
126
+ paren_match = re.search(r'\(\s*(\d+)\s*\)', full_text_str)
127
+ if paren_match:
128
+ reviews_count = int(paren_match.group(1))
129
+
130
+ item = {
131
+ "name": name,
132
+ "website": website,
133
+ "maps_link": maps_href,
134
+ "rating": rating,
135
+ "reviews": reviews_count,
136
+ "raw_text": raw_text_list # Saving raw text
137
+ }
138
+
139
+ save_to_jsonl(item, output_file)
140
+ scraped_links.add(maps_href)
141
+ scraped_count += 1
142
+
143
+ site_status = "YES" if website else "NO"
144
+ logger.log(f"Saved: {name} | Website: {site_status}")
145
+
146
+ except Exception as e:
147
+ continue
148
+
149
+ # Check end of list
150
+ new_height = page.locator(feed_selector).evaluate("el => el.scrollHeight")
151
+ end_text = page.locator("text=You've reached the end of the list").or_(
152
+ page.locator("text=Больше результатов нет")
153
+ ).is_visible()
154
+
155
+ if new_height == last_height:
156
+ no_change_count += 1
157
+ if no_change_count >= 3 or end_text:
158
+ logger.log("End of list reached")
159
+ break
160
+ else:
161
+ no_change_count = 0
162
+ last_height = new_height
163
+
164
+ logger.log(f"Total records: {scraped_count}")
165
+ browser.close()
166
+ return scraped_count
src/backend/scraper/screenshot_module.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import random
4
+ from playwright.sync_api import sync_playwright, Error as PlaywrightError
5
+
6
+ USER_AGENTS = [
7
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
8
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
9
+ ]
10
+
11
+ def take_screenshots(input_file, output_dir, logger):
12
+ """Capture website screenshots"""
13
+ if not os.path.exists(output_dir):
14
+ os.makedirs(output_dir)
15
+
16
+ sites = []
17
+ try:
18
+ with open(input_file, 'r', encoding='utf-8') as f:
19
+ for line in f:
20
+ if line.strip():
21
+ sites.append(json.loads(line))
22
+ except FileNotFoundError:
23
+ logger.log("Data file not found", level="ERROR")
24
+ return 0
25
+
26
+ screenshot_count = 0
27
+
28
+ with sync_playwright() as p:
29
+ browser = p.chromium.launch(
30
+ headless=True,
31
+ args=[
32
+ "--disable-blink-features=AutomationControlled",
33
+ "--no-sandbox",
34
+ "--disable-setuid-sandbox"
35
+ ]
36
+ )
37
+
38
+ context = browser.new_context(
39
+ viewport={'width': 1920, 'height': 1080},
40
+ user_agent=random.choice(USER_AGENTS),
41
+ locale="en-GB",
42
+ timezone_id="Europe/London"
43
+ )
44
+
45
+ context.add_init_script("""
46
+ Object.defineProperty(navigator, 'webdriver', {
47
+ get: () => undefined
48
+ });
49
+ """)
50
+
51
+ page = context.new_page()
52
+
53
+ for index, site in enumerate(sites):
54
+ url = site.get('website')
55
+ name = site.get('name', 'Unknown')
56
+ file_index = f"{index + 1:03d}"
57
+ filename = f"{file_index}_screenshot.png"
58
+ filepath = os.path.join(output_dir, filename)
59
+
60
+ if not url:
61
+ continue
62
+
63
+ logger.log(f"[{file_index}] Accessing: {url}")
64
+
65
+ try:
66
+ # --- FIX START: Handle Redirects ---
67
+ try:
68
+ response = page.goto(url, timeout=60000, wait_until='domcontentloaded')
69
+ except PlaywrightError as e:
70
+ # If the navigation is interrupted by a redirect, we catch it and wait for the new page
71
+ if "interrupted by another navigation" in str(e):
72
+ logger.log("Redirect detected, waiting for new page load...")
73
+ try:
74
+ page.wait_for_load_state("domcontentloaded", timeout=30000)
75
+ except:
76
+ pass # If it times out, we try to screenshot anyway
77
+ else:
78
+ raise e # If it's a different error, re-raise it to the outer except block
79
+ # --- FIX END ---
80
+
81
+ page.wait_for_timeout(3000)
82
+
83
+ # Check for Cloudflare
84
+ cloudflare_indicators = [
85
+ "Verify you are human",
86
+ "Checking your browser before accessing",
87
+ "Just a moment..."
88
+ ]
89
+
90
+ page_content = page.content()
91
+
92
+ if any(indicator in page_content for indicator in cloudflare_indicators):
93
+ logger.log(f"Cloudflare detected, attempting bypass...")
94
+
95
+ try:
96
+ frame_element = page.frame_locator("iframe[src*='cloudflare']").first
97
+ checkbox = frame_element.locator("input[type='checkbox'], span.mark").first
98
+
99
+ if checkbox.is_visible():
100
+ box = checkbox.bounding_box()
101
+ if box:
102
+ page.mouse.move(box['x'] + 5, box['y'] + 5)
103
+ page.wait_for_timeout(random.randint(200, 500))
104
+ page.mouse.down()
105
+ page.wait_for_timeout(random.randint(50, 150))
106
+ page.mouse.up()
107
+ logger.log("Clicked Cloudflare")
108
+ page.wait_for_timeout(5000)
109
+ except Exception as e:
110
+ logger.log(f"Failed to click: {e}")
111
+
112
+ # Close cookie banner
113
+ try:
114
+ page.locator("button:text-matches('Accept|Agree|Allow|Cookie|Принять', 'i')").first.click(timeout=2000)
115
+ page.wait_for_timeout(1000)
116
+ except:
117
+ pass
118
+
119
+ page.screenshot(path=filepath)
120
+ screenshot_count += 1
121
+ logger.log(f"Screenshot saved: {filename}")
122
+
123
+ except Exception as e:
124
+ logger.log(f"Error: {e}", level="ERROR")
125
+
126
+ browser.close()
127
+
128
+ return screenshot_count
src/backend/utils/__pycache__/config.cpython-311.pyc ADDED
Binary file (1.84 kB). View file
 
src/backend/utils/__pycache__/config.cpython-312.pyc ADDED
Binary file (1.72 kB). View file
 
src/backend/utils/__pycache__/logger.cpython-311.pyc ADDED
Binary file (1.61 kB). View file
 
src/backend/utils/__pycache__/logger.cpython-312.pyc ADDED
Binary file (1.33 kB). View file
 
src/backend/utils/config.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+
4
+
5
+ class Config:
6
+ """Application Configuration"""
7
+
8
+ # Base directories
9
+ BASE_DIR = Path(__file__).parent.parent.parent.parent
10
+ OUTPUT_DIR = BASE_DIR / 'output'
11
+ SCREENSHOTS_DIR = OUTPUT_DIR / 'screenshots'
12
+
13
+ # Data files
14
+ DATA_FILE = OUTPUT_DIR / 'data.jsonl'
15
+
16
+ # Parser settings
17
+ TIMEOUT_MS = 60000
18
+ SCROLL_DELAY = 2000
19
+ MAX_NO_CHANGE_COUNT = 3
20
+
21
+ # User Agents
22
+ USER_AGENTS = [
23
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
24
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
25
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
26
+ ]
27
+
28
+ # Screenshot settings
29
+ SCREENSHOT_VIEWPORT = {'width': 1920, 'height': 1080}
30
+ SCREENSHOT_WAIT_TIME = 3000
31
+
32
+ # Cloudflare bypass
33
+ CLOUDFLARE_WAIT_TIME = 5000
34
+ CLOUDFLARE_INDICATORS = [
35
+ "Verify you are human",
36
+ "Checking your browser before accessing",
37
+ "Just a moment..."
38
+ ]
39
+
40
+ def __init__(self):
41
+ # Create necessary directories
42
+ self.OUTPUT_DIR.mkdir(exist_ok=True)
43
+ self.SCREENSHOTS_DIR.mkdir(exist_ok=True)
src/backend/utils/logger.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+
3
+
4
+ class Logger:
5
+ """Simple logger for console output"""
6
+
7
+ def __init__(self):
8
+ self.logs = []
9
+
10
+ def log(self, message, level="INFO"):
11
+ """Log message"""
12
+ timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
13
+ log_entry = f"[{timestamp}] [{level}] {message}"
14
+ print(log_entry)
15
+ self.logs.append(log_entry)
16
+
17
+ def get_logs(self):
18
+ """Get all logs"""
19
+ return self.logs
20
+
21
+ def clear_logs(self):
22
+ """Clear logs"""
23
+ self.logs = []
src/frontend/__pycache__/main.cpython-311.pyc ADDED
Binary file (23.6 kB). View file
 
src/frontend/__pycache__/main.cpython-312.pyc ADDED
Binary file (22.3 kB). View file
 
src/frontend/main.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tkinter as tk
2
+ from tkinter import ttk, messagebox, scrolledtext
3
+ from PIL import Image, ImageTk
4
+ import threading
5
+ import sys
6
+ import os
7
+ import re
8
+ from pathlib import Path
9
+
10
+ # Add path to backend
11
+ sys.path.append(str(Path(__file__).parent.parent))
12
+
13
+ from backend.core.Facade import ScraperFacade
14
+
15
+
16
+ class ModernScraperApp:
17
+ def __init__(self, root):
18
+ self.root = root
19
+ self.root.title("G-Maps Ultra Scraper")
20
+ self.root.geometry("1400x900")
21
+
22
+ # Style settings (Modern Look)
23
+ self.style = ttk.Style()
24
+ self.style.theme_use('clam')
25
+ self.configure_styles()
26
+
27
+ self.root.configure(bg='#F5F7FA')
28
+
29
+ self.facade = ScraperFacade()
30
+ self.is_running = False
31
+ self.current_records = [] # Keep data in memory
32
+
33
+ self.create_layout()
34
+
35
+ def configure_styles(self):
36
+ bg_color = '#F5F7FA'
37
+ accent_color = '#4A90E2'
38
+ text_color = '#333333'
39
+
40
+ self.style.configure('TFrame', background=bg_color)
41
+ self.style.configure('TLabelframe', background=bg_color, foreground=text_color)
42
+ self.style.configure('TLabelframe.Label', background=bg_color, foreground='#555', font=('Segoe UI', 10, 'bold'))
43
+ self.style.configure('TLabel', background=bg_color, foreground=text_color, font=('Segoe UI', 10))
44
+ self.style.configure('Header.TLabel', font=('Segoe UI', 12, 'bold'), foreground='#2C3E50')
45
+ self.style.configure('TButton', font=('Segoe UI', 10), padding=6)
46
+ self.style.map('TButton', background=[('active', '#357ABD')])
47
+
48
+ self.style.configure("Treeview",
49
+ background="white",
50
+ foreground="black",
51
+ rowheight=30,
52
+ fieldbackground="white",
53
+ font=('Segoe UI', 10))
54
+ self.style.configure("Treeview.Heading", font=('Segoe UI', 10, 'bold'))
55
+ self.style.map("Treeview", background=[('selected', accent_color)])
56
+
57
+ def create_layout(self):
58
+ top_frame = ttk.Frame(self.root, padding="20 20 20 10")
59
+ top_frame.pack(fill=tk.X)
60
+
61
+ ttk.Label(top_frame, text="SEARCH QUERY:", style='Header.TLabel').pack(side=tk.LEFT, padx=(0, 10))
62
+
63
+ self.search_entry = ttk.Entry(top_frame, font=("Segoe UI", 12), width=50)
64
+ self.search_entry.pack(side=tk.LEFT, padx=5, ipady=5)
65
+ self.search_entry.insert(0, "Lawyers London")
66
+
67
+ self.start_btn = tk.Button(top_frame, text="START SCRAPING",
68
+ bg='#4CAF50', fg='white', font=("Segoe UI", 10, "bold"),
69
+ relief=tk.FLAT, padx=20, pady=5,
70
+ command=self.start_process)
71
+ self.start_btn.pack(side=tk.LEFT, padx=20)
72
+
73
+ main_pane = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
74
+ main_pane.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
75
+
76
+ left_frame = ttk.LabelFrame(main_pane, text=" Search Results ", padding=10)
77
+ main_pane.add(left_frame, weight=2)
78
+
79
+ columns = ('id', 'name', 'website', 'rating', 'reviews')
80
+ self.tree = ttk.Treeview(left_frame, columns=columns, show='headings')
81
+
82
+ self.tree.heading('id', text='#')
83
+ self.tree.heading('name', text='Name')
84
+ self.tree.heading('website', text='Website')
85
+ self.tree.heading('rating', text='Rating')
86
+ self.tree.heading('reviews', text='Reviews')
87
+
88
+ self.tree.column('id', width=50, stretch=False)
89
+ self.tree.column('name', width=200)
90
+ self.tree.column('website', width=200)
91
+ self.tree.column('rating', width=70, stretch=False)
92
+ self.tree.column('reviews', width=70, stretch=False)
93
+
94
+ scrollbar = ttk.Scrollbar(left_frame, orient=tk.VERTICAL, command=self.tree.yview)
95
+ self.tree.configure(yscroll=scrollbar.set)
96
+
97
+ self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
98
+ scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
99
+
100
+ self.tree.bind('<<TreeviewSelect>>', self.on_row_click)
101
+
102
+ right_frame = ttk.Frame(main_pane, padding=(10, 0))
103
+ main_pane.add(right_frame, weight=1)
104
+
105
+ img_group = ttk.LabelFrame(right_frame, text=" Website Screenshot ", padding=10)
106
+ img_group.pack(fill=tk.BOTH, expand=False)
107
+
108
+ self.image_label = ttk.Label(img_group, text="No Image", anchor="center")
109
+ self.image_label.pack(fill=tk.BOTH, expand=True)
110
+ img_group.pack_propagate(False)
111
+ img_group.configure(height=350)
112
+
113
+ details_group = ttk.LabelFrame(right_frame, text=" Selected Item Parameters ", padding=15)
114
+ details_group.pack(fill=tk.X, pady=15)
115
+
116
+ self.detail_widgets = {}
117
+ # Added "Website" field to list
118
+ fields = [("Name", "name_val"),
119
+ ("Website", "website_val"),
120
+ ("Rating", "rating_val"),
121
+ ("Reviews", "reviews_val"),
122
+ ("Phone (Parsed)", "phone_val"),
123
+ ("Location (Parsed)", "loc_val")]
124
+
125
+ for i, (label, key) in enumerate(fields):
126
+ ttk.Label(details_group, text=f"{label}:", font=("Segoe UI", 9, 'bold')).grid(row=i, column=0, sticky='w', pady=5)
127
+ entry = ttk.Entry(details_group, width=35)
128
+ entry.grid(row=i, column=1, sticky='ew', padx=10, pady=5)
129
+ self.detail_widgets[key] = entry
130
+
131
+ # Action buttons (Website and WhatsApp)
132
+ btn_frame = ttk.Frame(details_group)
133
+ btn_frame.grid(row=len(fields), column=1, sticky='e', pady=10, padx=10)
134
+
135
+ web_btn = tk.Button(btn_frame, text="Open Website", bg='#357ABD', fg='white',
136
+ font=("Segoe UI", 9, "bold"), relief=tk.FLAT,
137
+ command=self.open_website_from_details)
138
+ web_btn.pack(side=tk.LEFT, padx=5)
139
+
140
+ wa_btn = tk.Button(btn_frame, text="WhatsApp", bg='#25D366', fg='white',
141
+ font=("Segoe UI", 9, "bold"), relief=tk.FLAT,
142
+ command=self.open_whatsapp_from_details)
143
+ wa_btn.pack(side=tk.LEFT, padx=5)
144
+
145
+ bottom_ctrl = ttk.Frame(right_frame)
146
+ bottom_ctrl.pack(fill=tk.BOTH, expand=True)
147
+
148
+ act_frame = ttk.Frame(bottom_ctrl)
149
+ act_frame.pack(fill=tk.X, pady=5)
150
+
151
+ ttk.Button(act_frame, text="Save CSV", command=self.save_csv).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=2)
152
+ ttk.Button(act_frame, text="Clear All", command=self.clear_data).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=2)
153
+
154
+ log_group = ttk.LabelFrame(bottom_ctrl, text=" System Log ")
155
+ log_group.pack(fill=tk.BOTH, expand=True, pady=5)
156
+
157
+ self.console = scrolledtext.ScrolledText(log_group, height=8, bg='#1E1E1E', fg='#00FF00', font=("Consolas", 9))
158
+ self.console.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
159
+
160
+ self.status_var = tk.StringVar(value="Ready")
161
+ status_bar = ttk.Label(self.root, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W, padding=5)
162
+ status_bar.pack(side=tk.BOTTOM, fill=tk.X)
163
+
164
+ def log(self, message):
165
+ self.console.insert(tk.END, f">> {message}\n")
166
+ self.console.see(tk.END)
167
+
168
+ def start_process(self):
169
+ if self.is_running:
170
+ return
171
+
172
+ query = self.search_entry.get().strip()
173
+ if not query:
174
+ messagebox.showerror("Error", "Enter a search query")
175
+ return
176
+
177
+ self.is_running = True
178
+ self.start_btn.config(state=tk.DISABLED, bg='#A5A5A5')
179
+ self.status_var.set("Process running...")
180
+ self.log(f"Start scraping: {query}")
181
+
182
+ for item in self.tree.get_children():
183
+ self.tree.delete(item)
184
+
185
+ def run():
186
+ count, screens = self.facade.start_scraping_process(query)
187
+ self.root.after(0, lambda: self.finish_process(count, screens))
188
+
189
+ thread = threading.Thread(target=run, daemon=True)
190
+ thread.start()
191
+
192
+ def finish_process(self, count, screens):
193
+ self.is_running = False
194
+ self.start_btn.config(state=tk.NORMAL, bg='#4CAF50')
195
+ self.status_var.set(f"Done. Records: {count}, Screenshots: {screens}")
196
+ self.log(f"Finished. Found: {count}, Screenshots: {screens}")
197
+ self.refresh_table()
198
+
199
+ def refresh_table(self):
200
+ self.current_records = self.facade.get_all_records()
201
+ for idx, record in enumerate(self.current_records, 1):
202
+ self.tree.insert('', tk.END, values=(
203
+ idx,
204
+ record.get('name', 'Unknown'),
205
+ record.get('website', ''),
206
+ record.get('rating', ''),
207
+ record.get('reviews', 0)
208
+ ))
209
+
210
+ def on_row_click(self, event):
211
+ selection = self.tree.selection()
212
+ if not selection:
213
+ return
214
+
215
+ item_id = self.tree.item(selection[0])
216
+ values = item_id['values']
217
+ if not values: return
218
+
219
+ idx_table = int(values[0]) - 1
220
+
221
+ if idx_table < len(self.current_records):
222
+ record = self.current_records[idx_table]
223
+ self.update_details_panel(record)
224
+ self.show_screenshot(idx_table + 1)
225
+
226
+ def update_details_panel(self, record):
227
+ """
228
+ Updated phone and location parsing
229
+ """
230
+ # Clear
231
+ for entry in self.detail_widgets.values():
232
+ entry.delete(0, tk.END)
233
+
234
+ # Fill basic fields
235
+ # FIX: Use (val or '') to convert None to empty string
236
+ self.detail_widgets['name_val'].insert(0, record.get('name') or '')
237
+ self.detail_widgets['website_val'].insert(0, record.get('website') or '')
238
+ self.detail_widgets['rating_val'].insert(0, str(record.get('rating') or ''))
239
+ self.detail_widgets['reviews_val'].insert(0, str(record.get('reviews') or 0))
240
+
241
+ raw_text = record.get('raw_text', [])
242
+ phone = "Not found"
243
+ location = "Not found"
244
+
245
+ if raw_text:
246
+ for line in raw_text:
247
+ line = line.strip()
248
+ if not line:
249
+ continue
250
+
251
+ parts = []
252
+ if '·' in line:
253
+ parts = line.split('·')
254
+ else:
255
+ parts = [line]
256
+
257
+ for part in parts:
258
+ clean_part = part.strip()
259
+ if any(x in clean_part for x in ["AM", "PM", "Opens", "Closes", "Open", "Закрыто", "Открыто"]):
260
+ continue
261
+
262
+ digits_only = re.sub(r'\D', '', clean_part)
263
+ if len(digits_only) >= 9:
264
+ phone = clean_part
265
+ break
266
+
267
+ if phone != "Not found":
268
+ break
269
+
270
+ for line in raw_text:
271
+ if '·' in line and not any(x in line for x in ["Open", "Closes", "AM", "PM"]):
272
+ if phone == "Not found" or phone not in line:
273
+ parts = line.split('·')
274
+ candidate = parts[-1].strip()
275
+ if len(candidate) > 5 and not candidate.replace('.','',1).isdigit():
276
+ location = candidate
277
+ break
278
+
279
+ elif ',' in line and len(line) > 10 and line[0].isdigit():
280
+ if phone not in line and "reviews" not in line and "(" not in line:
281
+ location = line.strip()
282
+ break
283
+
284
+ self.detail_widgets['phone_val'].insert(0, phone)
285
+ self.detail_widgets['loc_val'].insert(0, location)
286
+
287
+ def show_screenshot(self, index):
288
+ filename = f"{index:03d}_screenshot.png"
289
+ filepath = self.facade.config.SCREENSHOTS_DIR / filename
290
+
291
+ if filepath.exists():
292
+ try:
293
+ pil_image = Image.open(filepath)
294
+ target_w = 450
295
+ w_percent = (target_w / float(pil_image.size[0]))
296
+ target_h = int((float(pil_image.size[1]) * float(w_percent)))
297
+
298
+ if target_h > 320:
299
+ target_h = 320
300
+ h_percent = (target_h / float(pil_image.size[1]))
301
+ target_w = int((float(pil_image.size[0]) * float(h_percent)))
302
+
303
+ pil_image = pil_image.resize((target_w, target_h), Image.Resampling.LANCZOS)
304
+ tk_image = ImageTk.PhotoImage(pil_image)
305
+
306
+ self.image_label.configure(image=tk_image, text="")
307
+ self.image_label.image = tk_image
308
+ except Exception as e:
309
+ self.log(f"Error loading image: {e}")
310
+ self.image_label.configure(image='', text=f"Image Error")
311
+ else:
312
+ self.image_label.configure(image='', text="Screenshot missing")
313
+
314
+ def open_whatsapp_from_details(self):
315
+ phone = self.detail_widgets['phone_val'].get()
316
+ if not phone or "Not found" in phone:
317
+ messagebox.showwarning("WhatsApp", "Phone number not recognized")
318
+ return
319
+ self.facade.open_whatsapp(phone)
320
+
321
+ def open_website_from_details(self):
322
+ url = self.detail_widgets['website_val'].get()
323
+ if not url:
324
+ messagebox.showwarning("Website", "URL missing")
325
+ return
326
+ if not self.facade.open_website(url):
327
+ messagebox.showerror("Error", "Failed to open link")
328
+
329
+ def save_csv(self):
330
+ if self.facade.export_to_csv("results.csv"):
331
+ messagebox.showinfo("Success", "Data saved to output/results.csv")
332
+ else:
333
+ messagebox.showerror("Error", "Failed to save file")
334
+
335
+ def clear_data(self):
336
+ if messagebox.askyesno("Cleanup", "Delete all data and screenshots?"):
337
+ self.facade.clear_all_data()
338
+ self.current_records = []
339
+ for item in self.tree.get_children():
340
+ self.tree.delete(item)
341
+ self.image_label.configure(image='', text="No Image")
342
+ self.log("Data cleaned.")
343
+
344
+
345
+ def main():
346
+ root = tk.Tk()
347
+ app = ModernScraperApp(root)
348
+ root.mainloop()
349
+
350
+
351
+ if __name__ == "__main__":
352
+ main()
src/frontend/streamlit.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import os
4
+ import sys
5
+ import re
6
+ import json
7
+ import time
8
+ import queue
9
+ import asyncio
10
+ from pathlib import Path
11
+ from PIL import Image
12
+ from concurrent.futures import ThreadPoolExecutor
13
+
14
+ # Добавляем путь к бэкенду
15
+ sys.path.append(str(Path(__file__).parent.parent.parent))
16
+
17
+ # Импорт существующей логики
18
+ from src.backend.core.Facade import ScraperFacade
19
+
20
+ # --- Настройка страницы ---
21
+ st.set_page_config(
22
+ page_title="G-Maps Ultra Scraper",
23
+ page_icon="🗺️",
24
+ layout="wide",
25
+ initial_sidebar_state="expanded"
26
+ )
27
+
28
+ # --- CSS стили ---
29
+ st.markdown("""
30
+ <style>
31
+ .stButton>button {
32
+ width: 100%;
33
+ border-radius: 5px;
34
+ height: 3em;
35
+ font-weight: bold;
36
+ }
37
+ .stSuccess {
38
+ background-color: #d4edda;
39
+ color: #155724;
40
+ padding: 10px;
41
+ border-radius: 5px;
42
+ }
43
+ </style>
44
+ """, unsafe_allow_html=True)
45
+
46
+ # --- Вспомогательные классы и функции ---
47
+
48
+ class ThreadSafeLogger:
49
+ """Логгер, безопасный для потоков. Пишет в очередь."""
50
+ def __init__(self, log_queue):
51
+ self.log_queue = log_queue
52
+
53
+ def log(self, message, level="INFO"):
54
+ entry = f"[{level}] {message}"
55
+ print(entry)
56
+ self.log_queue.put(entry)
57
+
58
+ def parse_contact_details(raw_text_list):
59
+ phone = "Not found"
60
+ location = "Not found"
61
+
62
+ if not raw_text_list:
63
+ return phone, location
64
+
65
+ for line in raw_text_list:
66
+ line = line.strip()
67
+ if not line: continue
68
+
69
+ parts = line.split('·') if '·' in line else [line]
70
+
71
+ for part in parts:
72
+ clean_part = part.strip()
73
+ if any(x in clean_part for x in ["AM", "PM", "Opens", "Closes", "Open", "Закрыто", "Открыто"]):
74
+ continue
75
+
76
+ digits_only = re.sub(r'\D', '', clean_part)
77
+ if len(digits_only) >= 9:
78
+ phone = clean_part
79
+ break
80
+ if phone != "Not found": break
81
+
82
+ for line in raw_text_list:
83
+ if '·' in line and not any(x in line for x in ["Open", "Closes", "AM", "PM"]):
84
+ if phone == "Not found" or phone not in line:
85
+ parts = line.split('·')
86
+ candidate = parts[-1].strip()
87
+ if len(candidate) > 5 and not candidate.replace('.','',1).isdigit():
88
+ location = candidate
89
+ break
90
+ elif ',' in line and len(line) > 10 and line[0].isdigit():
91
+ if phone not in line and "reviews" not in line and "(" not in line:
92
+ location = line.strip()
93
+ break
94
+
95
+ return phone, location
96
+
97
+ def load_data():
98
+ facade = ScraperFacade()
99
+ records = facade.get_all_records()
100
+ if not records:
101
+ return pd.DataFrame()
102
+ df = pd.DataFrame(records)
103
+ df.insert(0, 'ID', range(1, len(df) + 1))
104
+ return df
105
+
106
+ def run_scraper_in_thread(facade, query):
107
+ """
108
+ Запускает скрапинг в отдельном потоке.
109
+ Использует try-except для настройки Windows (Feature Detection).
110
+ """
111
+ # Пытаемся включить поддержку Windows Proactor (нужно для подпроцессов браузера)
112
+ # На Linux/Mac этого атрибута нет, поэтому сработает except, и код просто пойдет дальше.
113
+ try:
114
+ asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
115
+ except AttributeError:
116
+ pass # Мы не на Windows, стандартная политика подойдет
117
+
118
+ # Создаем новый чистый цикл событий для этого потока
119
+ loop = asyncio.new_event_loop()
120
+ asyncio.set_event_loop(loop)
121
+
122
+ try:
123
+ return facade.start_scraping_process(query)
124
+ finally:
125
+ loop.close()
126
+
127
+ # --- Инициализация Session State ---
128
+ if 'facade' not in st.session_state:
129
+ st.session_state.facade = ScraperFacade()
130
+
131
+ if 'logs' not in st.session_state:
132
+ st.session_state.logs = []
133
+
134
+ # --- Боковая панель ---
135
+ with st.sidebar:
136
+ st.header("⚙️ Control Panel")
137
+ query = st.text_input("Search Query", value="Lawyers London", help="Enter business type and city")
138
+
139
+ col1, col2 = st.columns(2)
140
+ with col1:
141
+ start_btn = st.button("🚀 Start", type="primary")
142
+ with col2:
143
+ clear_btn = st.button("🗑️ Clear All", type="secondary")
144
+
145
+ st.divider()
146
+ st.subheader("Actions")
147
+ export_btn = st.button("💾 Export to CSV")
148
+
149
+ # --- Основная логика ---
150
+
151
+ log_placeholder = st.empty()
152
+
153
+ def render_logs():
154
+ with log_placeholder.container():
155
+ with st.expander("🖥️ System Logs", expanded=True):
156
+ st.code("\n".join(st.session_state.logs[-10:]), language="text")
157
+
158
+ if start_btn:
159
+ st.session_state.logs = []
160
+
161
+ log_queue = queue.Queue()
162
+ thread_logger = ThreadSafeLogger(log_queue)
163
+ st.session_state.facade.logger = thread_logger
164
+
165
+ with st.status("Scraping in progress...", expanded=True) as status:
166
+
167
+ with ThreadPoolExecutor(max_workers=1) as executor:
168
+ future = executor.submit(run_scraper_in_thread, st.session_state.facade, query)
169
+
170
+ while not future.done():
171
+ try:
172
+ while True:
173
+ msg = log_queue.get_nowait()
174
+ st.session_state.logs.append(msg)
175
+ except queue.Empty:
176
+ pass
177
+
178
+ status.write(f"Processing... Logs: {len(st.session_state.logs)}")
179
+ render_logs()
180
+ time.sleep(0.5)
181
+
182
+ try:
183
+ count, screens = future.result()
184
+ status.update(label="Scraping Complete!", state="complete", expanded=False)
185
+ st.success(f"Found {count} records and taken {screens} screenshots.")
186
+ except Exception as e:
187
+ st.error(f"Error during execution: {e}")
188
+
189
+ st.rerun()
190
+
191
+ if clear_btn:
192
+ if st.session_state.facade.clear_all_data():
193
+ st.session_state.logs = []
194
+ st.toast("Data cleared successfully!")
195
+ st.rerun()
196
+
197
+ if export_btn:
198
+ if st.session_state.facade.export_to_csv("results.csv"):
199
+ csv_path = st.session_state.facade.config.OUTPUT_DIR / "results.csv"
200
+ try:
201
+ with open(csv_path, "rb") as f:
202
+ st.sidebar.download_button(
203
+ label="⬇️ Download CSV",
204
+ data=f,
205
+ file_name="google_maps_results.csv",
206
+ mime="text/csv"
207
+ )
208
+ except FileNotFoundError:
209
+ st.error("File not found after export.")
210
+ else:
211
+ st.error("No data to export or error occurred.")
212
+
213
+ # --- Результаты ---
214
+
215
+ st.title("🗺️ G-Maps Ultra Scraper")
216
+ df = load_data()
217
+
218
+ if not start_btn:
219
+ render_logs()
220
+
221
+ stat_cols = st.columns(4)
222
+ if not df.empty:
223
+ stat_cols[0].metric("Total Records", len(df))
224
+ stat_cols[1].metric("With Website", len(df[df['website'].notna() & (df['website'] != '')]))
225
+ stat_cols[2].metric("Avg Rating", f"{pd.to_numeric(df['rating'], errors='coerce').mean():.1f}")
226
+ else:
227
+ st.info("No data found. Enter a query and click Start.")
228
+
229
+ st.divider()
230
+
231
+ col_left, col_right = st.columns([1.5, 1])
232
+
233
+ with col_left:
234
+ st.subheader("📋 Results List")
235
+ if not df.empty:
236
+ selection = st.dataframe(
237
+ df[['ID', 'name', 'website', 'rating', 'reviews']],
238
+ use_container_width=True,
239
+ hide_index=True,
240
+ on_select="rerun",
241
+ selection_mode="single-row"
242
+ )
243
+ selected_row_index = None
244
+ if selection.selection.rows:
245
+ selected_row_index = selection.selection.rows[0]
246
+ else:
247
+ st.write("Waiting for data...")
248
+
249
+ with col_right:
250
+ st.subheader("🔍 Details & Screenshot")
251
+
252
+ if not df.empty and selected_row_index is not None:
253
+ record = df.iloc[selected_row_index]
254
+ record_idx = int(record['ID'])
255
+
256
+ raw_text = record.get('raw_text', [])
257
+ phone, location = parse_contact_details(raw_text)
258
+
259
+ screenshot_filename = f"{record_idx:03d}_screenshot.png"
260
+ screenshot_path = st.session_state.facade.config.SCREENSHOTS_DIR / screenshot_filename
261
+
262
+ if screenshot_path.exists():
263
+ image = Image.open(screenshot_path)
264
+ st.image(image, caption=f"Screenshot: {record['name']}", use_container_width=True)
265
+ else:
266
+ st.warning("Screenshot not available")
267
+
268
+ with st.container(border=True):
269
+ st.text_input("Name", value=record['name'], disabled=True)
270
+ st.text_input("Website", value=record['website'] if record['website'] else "N/A", disabled=True)
271
+
272
+ c1, c2 = st.columns(2)
273
+ c1.text_input("Rating", value=str(record['rating']), disabled=True)
274
+ c2.text_input("Reviews", value=str(record['reviews']), disabled=True)
275
+
276
+ st.text_input("Phone (Parsed)", value=phone, disabled=True)
277
+ st.text_area("Location (Parsed)", value=location, disabled=True, height=68)
278
+
279
+ btn_c1, btn_c2 = st.columns(2)
280
+
281
+ if phone and phone != "Not found":
282
+ clean_number = ''.join(filter(str.isdigit, phone))
283
+ wa_url = f"https://wa.me/{clean_number}"
284
+ btn_c1.link_button("💬 WhatsApp", wa_url, use_container_width=True)
285
+ else:
286
+ btn_c1.button("💬 WhatsApp", disabled=True, use_container_width=True)
287
+
288
+ url = record.get('website')
289
+ if url and url.startswith('http'):
290
+ btn_c2.link_button("🌐 Open Site", url, use_container_width=True)
291
+ else:
292
+ btn_c2.button("🌐 Open Site", disabled=True, use_container_width=True)
293
+
294
+ else:
295
+ st.info("Select a row from the table to view details.")