Download src/frontend/streamlit.py from MonPrinM/README: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/MonPrinM/README/resolve/main/src/frontend/streamlit.py
- Command line
-
hf download hf://spaces/MonPrinM/README/src/frontend/streamlit.py
-
curl -L -o streamlit.py https://huggingface.co/spaces/MonPrinM/README/resolve/main/src/frontend/streamlit.py
10.5 kB
| 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.") |