File size: 10,453 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
import streamlit as st
import pandas as pd
import os
import sys
import re
import json
import time
import queue
import asyncio 
from pathlib import Path
from PIL import Image
from concurrent.futures import ThreadPoolExecutor

# Добавляем путь к бэкенду
sys.path.append(str(Path(__file__).parent.parent.parent))

# Импорт существующей логики
from src.backend.core.Facade import ScraperFacade

# --- Настройка страницы ---
st.set_page_config(
    page_title="G-Maps Ultra Scraper",
    page_icon="🗺️",
    layout="wide",
    initial_sidebar_state="expanded"
)

# --- CSS стили ---
st.markdown("""

    <style>

    .stButton>button {

        width: 100%;

        border-radius: 5px;

        height: 3em;

        font-weight: bold;

    }

    .stSuccess {

        background-color: #d4edda;

        color: #155724;

        padding: 10px;

        border-radius: 5px;

    }

    </style>

""", unsafe_allow_html=True)

# --- Вспомогательные классы и функции ---

class ThreadSafeLogger:
    """Логгер, безопасный для потоков. Пишет в очередь."""
    def __init__(self, log_queue):
        self.log_queue = log_queue

    def log(self, message, level="INFO"):
        entry = f"[{level}] {message}"
        print(entry)
        self.log_queue.put(entry)

def parse_contact_details(raw_text_list):
    phone = "Not found"
    location = "Not found"
    
    if not raw_text_list:
        return phone, location

    for line in raw_text_list:
        line = line.strip()
        if not line: continue
        
        parts = line.split('·') if '·' in line else [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_list:
        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
    
    return phone, location

def load_data():
    facade = ScraperFacade()
    records = facade.get_all_records()
    if not records:
        return pd.DataFrame()
    df = pd.DataFrame(records)
    df.insert(0, 'ID', range(1, len(df) + 1))
    return df

def run_scraper_in_thread(facade, query):
    """

    Запускает скрапинг в отдельном потоке.

    Использует try-except для настройки Windows (Feature Detection).

    """
    # Пытаемся включить поддержку Windows Proactor (нужно для подпроцессов браузера)
    # На Linux/Mac этого атрибута нет, поэтому сработает except, и код просто пойдет дальше.
    try:
        asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
    except AttributeError:
        pass  # Мы не на Windows, стандартная политика подойдет
        
    # Создаем новый чистый цикл событий для этого потока
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    
    try:
        return facade.start_scraping_process(query)
    finally:
        loop.close()

# --- Инициализация Session State ---
if 'facade' not in st.session_state:
    st.session_state.facade = ScraperFacade()

if 'logs' not in st.session_state:
    st.session_state.logs = []

# --- Боковая панель ---
with st.sidebar:
    st.header("⚙️ Control Panel")
    query = st.text_input("Search Query", value="Lawyers London", help="Enter business type and city")
    
    col1, col2 = st.columns(2)
    with col1:
        start_btn = st.button("🚀 Start", type="primary")
    with col2:
        clear_btn = st.button("🗑️ Clear All", type="secondary")

    st.divider()
    st.subheader("Actions")
    export_btn = st.button("💾 Export to CSV")

# --- Основная логика ---

log_placeholder = st.empty()

def render_logs():
    with log_placeholder.container():
        with st.expander("🖥️ System Logs", expanded=True):
             st.code("\n".join(st.session_state.logs[-10:]), language="text")

if start_btn:
    st.session_state.logs = []
    
    log_queue = queue.Queue()
    thread_logger = ThreadSafeLogger(log_queue)
    st.session_state.facade.logger = thread_logger
    
    with st.status("Scraping in progress...", expanded=True) as status:
        
        with ThreadPoolExecutor(max_workers=1) as executor:
            future = executor.submit(run_scraper_in_thread, st.session_state.facade, query)
            
            while not future.done():
                try:
                    while True:
                        msg = log_queue.get_nowait()
                        st.session_state.logs.append(msg)
                except queue.Empty:
                    pass
                
                status.write(f"Processing... Logs: {len(st.session_state.logs)}")
                render_logs()
                time.sleep(0.5)
            
            try:
                count, screens = future.result()
                status.update(label="Scraping Complete!", state="complete", expanded=False)
                st.success(f"Found {count} records and taken {screens} screenshots.")
            except Exception as e:
                st.error(f"Error during execution: {e}")
    
    st.rerun()

if clear_btn:
    if st.session_state.facade.clear_all_data():
        st.session_state.logs = []
        st.toast("Data cleared successfully!")
        st.rerun()

if export_btn:
    if st.session_state.facade.export_to_csv("results.csv"):
        csv_path = st.session_state.facade.config.OUTPUT_DIR / "results.csv"
        try:
            with open(csv_path, "rb") as f:
                st.sidebar.download_button(
                    label="⬇️ Download CSV",
                    data=f,
                    file_name="google_maps_results.csv",
                    mime="text/csv"
                )
        except FileNotFoundError:
            st.error("File not found after export.")
    else:
        st.error("No data to export or error occurred.")

# --- Результаты ---

st.title("🗺️ G-Maps Ultra Scraper")
df = load_data()

if not start_btn:
    render_logs()

stat_cols = st.columns(4)
if not df.empty:
    stat_cols[0].metric("Total Records", len(df))
    stat_cols[1].metric("With Website", len(df[df['website'].notna() & (df['website'] != '')]))
    stat_cols[2].metric("Avg Rating", f"{pd.to_numeric(df['rating'], errors='coerce').mean():.1f}")
else:
    st.info("No data found. Enter a query and click Start.")

st.divider()

col_left, col_right = st.columns([1.5, 1])

with col_left:
    st.subheader("📋 Results List")
    if not df.empty:
        selection = st.dataframe(
            df[['ID', 'name', 'website', 'rating', 'reviews']],
            use_container_width=True,
            hide_index=True,
            on_select="rerun",
            selection_mode="single-row"
        )
        selected_row_index = None
        if selection.selection.rows:
            selected_row_index = selection.selection.rows[0]
    else:
        st.write("Waiting for data...")

with col_right:
    st.subheader("🔍 Details & Screenshot")
    
    if not df.empty and selected_row_index is not None:
        record = df.iloc[selected_row_index]
        record_idx = int(record['ID'])
        
        raw_text = record.get('raw_text', [])
        phone, location = parse_contact_details(raw_text)

        screenshot_filename = f"{record_idx:03d}_screenshot.png"
        screenshot_path = st.session_state.facade.config.SCREENSHOTS_DIR / screenshot_filename
        
        if screenshot_path.exists():
            image = Image.open(screenshot_path)
            st.image(image, caption=f"Screenshot: {record['name']}", use_container_width=True)
        else:
            st.warning("Screenshot not available")

        with st.container(border=True):
            st.text_input("Name", value=record['name'], disabled=True)
            st.text_input("Website", value=record['website'] if record['website'] else "N/A", disabled=True)
            
            c1, c2 = st.columns(2)
            c1.text_input("Rating", value=str(record['rating']), disabled=True)
            c2.text_input("Reviews", value=str(record['reviews']), disabled=True)
            
            st.text_input("Phone (Parsed)", value=phone, disabled=True)
            st.text_area("Location (Parsed)", value=location, disabled=True, height=68)
            
            btn_c1, btn_c2 = st.columns(2)
            
            if phone and phone != "Not found":
                clean_number = ''.join(filter(str.isdigit, phone))
                wa_url = f"https://wa.me/{clean_number}"
                btn_c1.link_button("💬 WhatsApp", wa_url, use_container_width=True)
            else:
                btn_c1.button("💬 WhatsApp", disabled=True, use_container_width=True)
            
            url = record.get('website')
            if url and url.startswith('http'):
                btn_c2.link_button("🌐 Open Site", url, use_container_width=True)
            else:
                btn_c2.button("🌐 Open Site", disabled=True, use_container_width=True)

    else:
        st.info("Select a row from the table to view details.")