Download dashboard_engine.py from cg-preis/radar: direct link, hf CLI and curl.
- Browser
- Download file 41.9 kB
-
https://huggingface.co/spaces/cg-preis/radar/resolve/main/dashboard_engine.py
- Command line
-
hf download hf://spaces/cg-preis/radar/dashboard_engine.py
-
curl -L -o dashboard_engine.py https://huggingface.co/spaces/cg-preis/radar/resolve/main/dashboard_engine.py
41.9 kB
| # Datei: dashboard_engine.py | |
| # VERSION: Phönix 5.11 (Fix: Full Logic + Stable Module Import) | |
| import json | |
| import os | |
| import time | |
| import re | |
| from datetime import datetime, timedelta | |
| import sys | |
| import random | |
| import requests | |
| from bs4 import BeautifulSoup | |
| import warnings | |
| import subprocess | |
| import concurrent.futures | |
| import base64 | |
| import sqlite3 | |
| # --- STABILER IMPORT (Zirkelbezug-Schutz) --- | |
| # Wir importieren das Modul als Objekt ('drm'). | |
| # Das verhindert "Cannot import name"-Fehler während der Initialisierung. | |
| try: | |
| import deal_radar_masterplan as drm | |
| HAS_MASTERPLAN = True | |
| except ImportError as e: | |
| # Nur warnen, nicht abstürzen (damit Webserver trotzdem startet) | |
| print(f"Warning: Masterplan-Logik nicht geladen: {e}") | |
| HAS_MASTERPLAN = False | |
| warnings.filterwarnings('ignore', message='Unverified HTTPS request') | |
| # --- PFAD KONFIGURATION --- | |
| if os.path.exists("/data"): | |
| BASE_DIR = "/data" | |
| else: | |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| DB_FILE = os.path.join(BASE_DIR, "radar.db") | |
| # ##### START: LOGGING ##### | |
| class Logger: | |
| def __init__(self, filename="scan.log"): | |
| self.log_path = os.path.join(BASE_DIR, filename) | |
| self.terminal_out = sys.stdout | |
| self.log = open(self.log_path, "a", encoding='utf-8', buffering=1) | |
| def write(self, message): | |
| self.terminal_out.write(message) | |
| try: | |
| self.log.write(message) | |
| self.log.flush() | |
| os.fsync(self.log.fileno()) | |
| except: pass | |
| def flush(self): | |
| self.terminal_out.flush() | |
| try: self.log.flush(); os.fsync(self.log.fileno()) | |
| except: pass | |
| sys.stdout = Logger() | |
| sys.stderr = sys.stdout | |
| # ##### ENDE LOGGING ##### | |
| # --- KONSTANTEN --- | |
| FULL_SCAN_RESULT_KEY = "last_full_scan" | |
| QUICK_SCAN_RESULT_KEY = "last_quick_scan" | |
| CHECKED_DEALS_KEY = "checked_deals" | |
| UNAVAILABLE_TRACKER_KEY = "unavailable_asin_tracker" | |
| ROTATION_STATE_KEY = "scan_pointer" | |
| TS_LAST_MAIN_KEY = "ts_last_main" | |
| TS_LAST_QUICK_KEY = "ts_last_quick" | |
| MYDEALZ_FILE = "mydealz_deals.json" | |
| MISMATCH_FILE = "mismatches.json" | |
| # --- DATENBANK HELPER (STANDALONE) --- | |
| def get_db_connection(): | |
| """Stellt eine eigene Verbindung her, unabhängig vom Masterplan Import""" | |
| try: | |
| conn = sqlite3.connect(DB_FILE, timeout=30) | |
| conn.row_factory = sqlite3.Row | |
| return conn | |
| except Exception as e: | |
| print(f"!! DB Connection Error in Dashboard Engine: {e}") | |
| return None | |
| def db_init(): | |
| print("-> Initialisiere Datenbank-Schema...") | |
| conn = get_db_connection() | |
| if not conn: return | |
| try: | |
| cursor = conn.cursor() | |
| cursor.execute("CREATE TABLE IF NOT EXISTS key_value_store (key TEXT PRIMARY KEY, json_data TEXT)") | |
| cursor.execute("""CREATE TABLE IF NOT EXISTS products (asin TEXT PRIMARY KEY, verified_name TEXT, source_article_url TEXT, source_article_slug TEXT, publication_date TEXT, source_score REAL)""") | |
| cursor.execute("""CREATE TABLE IF NOT EXISTS price_history (id INTEGER PRIMARY KEY AUTOINCREMENT, asin TEXT NOT NULL, date TEXT NOT NULL, price REAL NOT NULL, UNIQUE(asin, date))""") | |
| conn.commit() | |
| except Exception as e: print(f"DB Init Error: {e}") | |
| finally: conn.close() | |
| def db_load_json(key, default_value={}): | |
| conn = get_db_connection() | |
| if not conn: return default_value | |
| try: | |
| cursor = conn.cursor() | |
| cursor.execute("SELECT json_data FROM key_value_store WHERE key = ?", (key,)) | |
| result = cursor.fetchone() | |
| if result and result['json_data']: return json.loads(result['json_data']) | |
| return default_value | |
| except: return default_value | |
| finally: conn.close() | |
| def db_save_json(key, data): | |
| conn = get_db_connection() | |
| if not conn: return | |
| try: | |
| cursor = conn.cursor() | |
| json_data = json.dumps(data, indent=2, ensure_ascii=False) | |
| cursor.execute("INSERT OR REPLACE INTO key_value_store (key, json_data) VALUES (?, ?)", (key, json_data)) | |
| conn.commit() | |
| except Exception as e: print(f"DB Save Error: {e}") | |
| finally: conn.close() | |
| # --- ZEITSTEMPEL --- | |
| def save_scan_timestamp(scan_type): | |
| now_str = datetime.now().strftime('%d.%m.%Y um %H:%M Uhr') | |
| key = TS_LAST_MAIN_KEY if scan_type == "main" else TS_LAST_QUICK_KEY | |
| db_save_json(key, now_str) | |
| def get_amazon_timestamps(): | |
| return { | |
| "main": db_load_json(TS_LAST_MAIN_KEY, "Noch nie"), | |
| "quick": db_load_json(TS_LAST_QUICK_KEY, "Noch nie") | |
| } | |
| def get_mydealz_timestamp(): | |
| fp = os.path.join(BASE_DIR, MYDEALZ_FILE) | |
| if os.path.exists(fp): | |
| ts = os.path.getmtime(fp) | |
| return datetime.fromtimestamp(ts).strftime('%d.%m.%Y um %H:%M Uhr') | |
| return "Noch nie" | |
| # --- DATA HANDLING --- | |
| def load_price_history(): | |
| history = {}; conn = get_db_connection() | |
| if not conn: return {} | |
| try: | |
| cursor = conn.cursor() | |
| cursor.execute("SELECT asin, date, price FROM price_history ORDER BY date ASC"); rows = cursor.fetchall() | |
| for row in rows: | |
| if row['asin'] not in history: history[row['asin']] = [] | |
| history[row['asin']].append({"date": row['date'], "price": row['price']}) | |
| return history | |
| finally: conn.close() | |
| def update_price_history(deals): | |
| today = datetime.now().strftime('%Y-%m-%d'); new_entries = [] | |
| for deal in deals: | |
| if deal.get('final_price'): new_entries.append((deal['asin'], today, deal['final_price'])) | |
| if new_entries: | |
| conn = get_db_connection() | |
| if conn: | |
| try: | |
| cursor = conn.cursor() | |
| cursor.executemany("""INSERT INTO price_history (asin, date, price) VALUES (?, ?, ?) ON CONFLICT(asin, date) DO UPDATE SET price = excluded.price""", new_entries) | |
| conn.commit() | |
| finally: conn.close() | |
| return load_price_history() | |
| def load_master_product_list(): | |
| """Lädt NUR Amazon ASINs (Starten mit B0)""" | |
| conn = get_db_connection() | |
| if not conn: return {} | |
| try: | |
| cursor = conn.cursor() | |
| # FILTER: Nur Amazon IDs laden | |
| cursor.execute("SELECT * FROM products WHERE asin GLOB 'B0*'"); rows = cursor.fetchall() | |
| return {row['asin']: dict(row) for row in rows} | |
| finally: conn.close() | |
| def cleanup_expired_tracked_asins(): | |
| asin_tracker = db_load_json(UNAVAILABLE_TRACKER_KEY, {}) | |
| if not asin_tracker: return | |
| cutoff = datetime.now() - timedelta(days=30) | |
| expired = [a for a, d in asin_tracker.items() if datetime.strptime(d, '%Y-%m-%d') < cutoff] | |
| if expired: | |
| conn = get_db_connection() | |
| if conn: | |
| cursor = conn.cursor() | |
| cursor.executemany("DELETE FROM products WHERE asin = ?", [(a,) for a in expired]); conn.commit(); conn.close() | |
| cleaned = {a: d for a, d in asin_tracker.items() if a not in expired} | |
| db_save_json(UNAVAILABLE_TRACKER_KEY, cleaned) | |
| def save_full_scan_results(deals): db_save_json(FULL_SCAN_RESULT_KEY, deals) | |
| def save_quick_scan_results(deals): db_save_json(QUICK_SCAN_RESULT_KEY, deals) | |
| def load_checked_deals(): return db_load_json(CHECKED_DEALS_KEY, {}) | |
| def save_checked_deals(checked_deals): db_save_json(CHECKED_DEALS_KEY, checked_deals) | |
| def load_full_scan_results(): return db_load_json(FULL_SCAN_RESULT_KEY, None) | |
| def load_quick_scan_results(): return db_load_json(QUICK_SCAN_RESULT_KEY, None) | |
| def save_rotation_state(index): db_save_json(ROTATION_STATE_KEY, index) | |
| def load_rotation_state(): return db_load_json(ROTATION_STATE_KEY, 0) | |
| # --- HELPER: IDEALO SNIPER --- | |
| def _get_smart_idealo_query(amazon_title, slug): | |
| STOP_WORDS = ['test', 'review', 'bericht', 'erfahrung', 'angebot', 'deal', 'rabatt', 'coupon', 'gutschein', 'kaufen', 'preis', 'china', 'gadgets', 'video', 'vorstellung', 'hands-on', 'unboxing', 'saugroboter', 'wischsauger', 'maehroboter', 'rasenmaeher', 'roboter', 'staubsauger', 'akku', 'handstaubsauger', 'kabellos', 'smart', 'watch', 'fitness', 'tracker', '3d', 'lidar', 'laser', 'navigation', 'station', 'absaugstation', 'mit', 'ohne', 'gen', 'generation', 'neuheit', 'release', 'launch'] | |
| if slug and len(slug) > 3: | |
| clean_slug = slug.replace('-', ' ') | |
| words = [w for w in clean_slug.split() if w.lower() not in STOP_WORDS] | |
| if len(words) >= 1: return " ".join(words[:4]).title() | |
| if not amazon_title: return "" | |
| t = amazon_title; t = re.sub(r'\[.*?\]', '', t); t = re.sub(r'\(.*?\)', '', t) | |
| for sep in [' - ', ' | ', ', ', ' – ', ' : ']: | |
| if sep in t: t = t.split(sep)[0]; break | |
| words = [w for w in t.split() if w.lower() not in STOP_WORDS] | |
| return " ".join(words[:4]) | |
| # --- PREIS EXTRACTION --- | |
| PRICE_RE_EURO = re.compile(r'(?:€\s*|)\s*((?:\d{1,3}(?:[.\s]\d{3})*|\d+)(?:[.,]\d{1,2}|(?:\s*[-–])?)?)\s*(?:€|eur|euro)?', re.I) | |
| def _normalize_price_to_float(raw): | |
| if not raw: return None | |
| s = str(raw).replace('\xa0', ' ').replace('EUR', '').replace('eur', '').replace('Euro', '').replace('€', '').strip() | |
| s = re.sub(r'\s+', ' ', s); s = re.sub(r'\s*[-–]\s*$', '', s); s = s.replace(' ', '') | |
| if ',' in s and '.' in s: s = s.replace('.', '').replace(',', '.') | |
| elif ',' in s and '.' not in s: s = s.replace(',', '.') | |
| else: s = s.replace('.', '') | |
| try: return float(s) | |
| except: return None | |
| def get_cg_article_price(slug_or_html, product_name=None, current_amazon_price=None): | |
| # Fallback-Wrapper für Masterplan-Funktion | |
| if HAS_MASTERPLAN: | |
| # Hier nutzen wir das Modul-Objekt 'drm' statt direkt importierte Funktion | |
| return _get_cg_article_price_logic(slug_or_html, current_amazon_price) | |
| return None | |
| def _get_cg_article_price_logic(slug_or_html, current_amazon_price): | |
| # Hier kopieren wir die Logik der Preisfindung, damit sie autark ist | |
| # oder wir rufen drm.get_article_data_from_api auf | |
| BAD_PRICE_WORDS = re.compile(r'(uvp|statt|vorher|durchgestrichen|strikethrough|unverbindliche)', re.I) | |
| PROMO_HINTS_RE = re.compile(r'\b(jetzt|nur|für|heute|deal|angebot|zum angebot|reduziert)\b', re.I) | |
| FOREIGN_SHOPS = re.compile(r'(geekbuying|banggood|proshop|aliexpress|cafago|dhgate|edwaybuy|tomtop|zbanx|lightinthebox)', re.I) | |
| def _is_plausible_local(val, ref): | |
| if val is None or val < 3 or val > 10000: return False | |
| if ref is None: return True | |
| return (0.35 * ref) <= val <= (3.0 * ref) | |
| def _has_strike_or_badcontext(node): | |
| if node.find('del'): return True | |
| txt = (node.get_text(" ", strip=True) or '') | |
| if BAD_PRICE_WORDS.search(txt) and not PROMO_HINTS_RE.search(txt): return True | |
| return False | |
| def _is_foreign_context(node): | |
| txt = (node.get_text(" ", strip=True) or '') | |
| return bool(FOREIGN_SHOPS.search(txt)) | |
| def _score(candidate_price, distance_level, ctx_text, ref, source=""): | |
| proximity_weight = {0: 1.0, 1: 0.85, 2: 0.7, 3: 0.55}.get(distance_level, 0.6) | |
| if isinstance(ref, (int, float)) and ref > 0: | |
| rel = abs(candidate_price - ref) / ref; near = max(0.2, 1.0 - rel) | |
| else: near = 0.6 | |
| return proximity_weight * near | |
| def _load_html(s): | |
| if '<' in str(s) and '</' in str(s): return s | |
| try: | |
| # Aufruf über drm (sicher) | |
| d = drm.get_article_data_from_api(str(s).strip('/')) | |
| return d['content']['rendered'] if d else '' | |
| except: return '' | |
| html = _load_html(slug_or_html) | |
| if not html: return None | |
| soup = BeautifulSoup(html, 'html.parser') | |
| candidates = [] | |
| for a in soup.find_all('a', href=True): | |
| text = (a.get_text(" ", strip=True) or '').lower() | |
| if 'amazon' not in a['href'] and 'amazon' not in text: continue | |
| for m in PRICE_RE_EURO.finditer(text): | |
| val = _normalize_price_to_float(m.group(1)) | |
| if _is_plausible_local(val, current_amazon_price): | |
| candidates.append((val, _score(val, 0, text, current_amazon_price))) | |
| if not candidates: return None | |
| candidates.sort(key=lambda x: x[1], reverse=True) | |
| return round(float(candidates[0][0]), 2) | |
| # --- ANALYSE & SORTIERUNG --- | |
| def analyze_and_sort_deals(deals, history): | |
| """Leichte Sortierung VOR dem Scan""" | |
| analyzed_deals = [] | |
| today_str = datetime.now().strftime('%Y-%m-%d') | |
| for deal in deals: | |
| if deal.get('final_price') is None: continue | |
| deal.update({'sort_priority': 9}) | |
| if deal['asin'] in history and isinstance(history.get(deal['asin']), list): | |
| prices_before_today = [p for p in history[deal['asin']] if p.get('date') != today_str and p.get('price', 0) > 0] | |
| if prices_before_today: | |
| current_price = deal.get('final_price', 0) | |
| all_time_low = min(p['price'] for p in prices_before_today) | |
| if current_price < all_time_low: deal['sort_priority'] = 1 | |
| elif current_price == all_time_low: deal['sort_priority'] = 2 | |
| analyzed_deals.append(deal) | |
| analyzed_deals.sort(key=lambda x: x.get('sort_priority', 99)) | |
| return analyzed_deals | |
| def analyze_and_sort_deals_deep(deals, history, fast_resort=False): | |
| """Tiefe Analyse NACH dem Scan""" | |
| analyzed_deals = [] | |
| today_str = datetime.now().strftime('%Y-%m-%d') | |
| checked_deals_data = load_checked_deals() | |
| deals_to_uncheck = [] | |
| cg_prices = [None] * len(deals) | |
| if not fast_resort and HAS_MASTERPLAN: | |
| print("-> [Analyse] Hole Artikel-Preise (Parallel)...") | |
| tasks = [{"slug": d.get('source_article_slug'), "name": d.get('verified_name'), "price": d.get('final_price', 0)} for d in deals] | |
| with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor: | |
| cg_prices = list(executor.map(lambda t: get_cg_article_price(t["slug"], t["name"], t["price"]), tasks)) | |
| for i, deal in enumerate(deals): | |
| if deal.get('final_price') is None: continue | |
| deal.setdefault('is_checked_off', False); deal.setdefault('sort_priority', 9) | |
| current_price = deal.get('final_price', 0) | |
| if deal['asin'] in checked_deals_data: | |
| check_info = checked_deals_data[deal['asin']] | |
| checked_at = datetime.fromisoformat(check_info['checked_at']) | |
| price_at_check = check_info['price_at_check'] | |
| if current_price < (price_at_check * 0.95): deals_to_uncheck.append(deal['asin']) | |
| elif datetime.now() > checked_at + timedelta(days=28): deals_to_uncheck.append(deal['asin']) | |
| else: | |
| deal['sort_priority'] = 999; deal['is_checked_off'] = True | |
| deal['analysis_text'] = f"Abgehakt {checked_at.strftime('%d.%m.')}" | |
| else: deal['is_checked_off'] = False | |
| if deal['is_checked_off']: analyzed_deals.append(deal); continue | |
| deal.update({'trend_icon': '⚪️', 'trend_title': 'Neu', 'trend_color_class': 'icon-new', 'savings_percent': 'Neu', 'savings_color_class': '', 'analysis_text': 'Keine Historie', 'reference_price': 0, 'reference_price_source': 'none'}) | |
| # CG Price integration | |
| cg_price = cg_prices[i] if (not fast_resort and cg_prices) else None | |
| if cg_price and cg_price > 0: | |
| deal.update({'reference_price_source': 'article', 'reference_price': cg_price}) | |
| if current_price < cg_price: deal.update({'trend_icon': '▼', 'trend_color_class': 'arrow-down'}) | |
| elif current_price > cg_price: deal.update({'trend_icon': '▲', 'trend_color_class': 'arrow-up'}) | |
| if current_price < (cg_price * 0.95): deal.update({'analysis_text': f'🔥 Top vs. Artikel ({cg_price:.0f}€)', 'sort_priority': 0}) | |
| else: deal['analysis_text'] = f"Artikel: {cg_price:.2f}€" | |
| if cg_price > 0: deal['savings_percent'] = f"{((current_price / cg_price) - 1) * 100:.1f}%" | |
| if deal['asin'] in history: | |
| hist = history[deal['asin']] | |
| prices_before = [p for p in hist if p['date'] != today_str] | |
| if prices_before: | |
| last_price = prices_before[-1]['price'] | |
| all_time_low = min(p['price'] for p in prices_before) | |
| if deal['reference_price'] == 0: | |
| deal['reference_price'] = last_price; deal['reference_price_source'] = 'history' | |
| if current_price < last_price: deal.update({'trend_icon': '▼', 'trend_color_class': 'arrow-down'}) | |
| elif current_price > last_price: deal.update({'trend_icon': '▲', 'trend_color_class': 'arrow-up'}) | |
| else: deal.update({'trend_icon': '-', 'trend_color_class': 'icon-stable'}) | |
| if last_price > 0: deal['savings_percent'] = f"{((current_price / last_price) - 1) * 100:.1f}%" | |
| if deal['sort_priority'] > 0: | |
| if current_price < all_time_low: deal.update({'analysis_text': '🔥 All-Time-Low!', 'sort_priority': 1}) | |
| elif current_price == all_time_low: deal.update({'analysis_text': '🔥 Bestpreis gehalten', 'sort_priority': 2}) | |
| try: deal['savings_numeric'] = float(deal.get('savings_percent', '0').replace('%', '')) | |
| except: deal['savings_numeric'] = 0.0 | |
| analyzed_deals.append(deal) | |
| if deals_to_uncheck: | |
| for asin in deals_to_uncheck: | |
| if asin in checked_deals_data: del checked_deals_data[asin] | |
| save_checked_deals(checked_deals_data) | |
| analyzed_deals.sort(key=lambda x: (x.get('is_checked_off', False), x.get('sort_priority', 99), x.get('savings_numeric', 0))) | |
| return analyzed_deals | |
| def select_products_for_hotlist_scan(all_deals_last_scan, history): | |
| print("-> [Phönix 3.1] Smart-Targeting (Strict Efficiency)...") | |
| master_list = load_master_product_list() | |
| checked_deals = load_checked_deals() # WICHTIG: Abgehakte laden | |
| # Limits für den Quick-Scan (damit er 'Quick' bleibt) | |
| TARGET_COUNT = 90 | |
| CAP_FRESH = 30 | |
| CAP_VOLATILE = 30 | |
| # Der Rest (mind. 30 Slots) ist für Rotation reserviert | |
| batch = [] | |
| seen_asins = set() | |
| # Blacklist Keywords (Müll rausfiltern) | |
| IGNORE_KEYWORDS = ["baby", "plüsch", "kuscheltier", "netzkabel", "stromkabel", "kaltgerätestecker", "verlängerungskabel", "tamper", "kaffeezubehör", "kaffeefilter", "vicloon", "deleycon", "schutzfolie", "panzerglas", "hülle", "case", "schrauben", "dübel", "werkzeugkoffer"] | |
| def is_valid_candidate(item): | |
| asin = item['asin'] | |
| # 1. Dubletten-Check | |
| if asin in seen_asins: return False | |
| # 2. Abgehakt-Check (Das ist Prio C!) | |
| # Wenn abgehakt -> NICHT im Quick-Scan. Der Main-Scan kümmert sich um Reaktivierung. | |
| if asin in checked_deals: return False | |
| # 3. Keyword-Check | |
| name = (item.get('verified_name') or "").lower() | |
| if any(bad in name for bad in IGNORE_KEYWORDS): return False | |
| return True | |
| def add_to_batch(item): | |
| if len(batch) >= TARGET_COUNT: return False | |
| batch.append(item) | |
| seen_asins.add(item['asin']) | |
| return True | |
| # Volatilitäts-Rechner (Robust gegen DB-Fehler) | |
| def get_volatility_score(asin): | |
| if not history or asin not in history: return 0 | |
| try: | |
| entries = history[asin] | |
| if not entries or len(entries) < 3: return 3 # Zweifel für den Angeklagten (neu = interessant) | |
| # Prüfe Varianz der letzten 10 Preise | |
| prices = [e['price'] for e in entries[-10:] if e['price'] > 0] | |
| if not prices: return 0 | |
| # Simpler Score: Anzahl der Preisänderungen | |
| changes = 0 | |
| for k in range(1, len(prices)): | |
| if abs(prices[k] - prices[k-1]) > 0.5: changes += 1 | |
| return changes | |
| except: return 0 | |
| all_products = list(master_list.values()) | |
| # --- BUCKET 1: FRESHNESS (Max 30) --- | |
| # Alles was jünger als 10 Tage ist | |
| cutoff_fresh = (datetime.now() - timedelta(days=10)).strftime('%Y-%m-%d') | |
| fresh_candidates = [p for p in all_products if str(p.get('publication_date') or '1970') >= cutoff_fresh] | |
| # Sortiere Fresh nach Datum (neueste zuerst) | |
| fresh_candidates.sort(key=lambda x: str(x.get('publication_date')), reverse=True) | |
| count_fresh = 0 | |
| for item in fresh_candidates: | |
| if count_fresh >= CAP_FRESH: break | |
| if is_valid_candidate(item): | |
| if add_to_batch(item): count_fresh += 1 | |
| print(f" -> Bucket 1 (Fresh): {count_fresh} Items") | |
| # --- BUCKET 2: VOLATILITY (Max 30) --- | |
| # Finde Produkte, die oft den Preis ändern | |
| volatile_candidates = [] | |
| for p in all_products: | |
| if p['asin'] not in seen_asins and is_valid_candidate(p): | |
| score = get_volatility_score(p['asin']) | |
| if score >= 2: # Mindestens 2 Änderungen in letzter Zeit | |
| volatile_candidates.append((score, p)) | |
| # Sortiere nach Score (höchste Volatilität zuerst) | |
| volatile_candidates.sort(key=lambda x: x[0], reverse=True) | |
| count_vol = 0 | |
| for score, item in volatile_candidates: | |
| if count_vol >= CAP_VOLATILE: break | |
| if add_to_batch(item): count_vol += 1 | |
| print(f" -> Bucket 2 (Volatile): {count_vol} Items") | |
| # --- BUCKET 3: ROTATION (Auffüllen bis voll) --- | |
| # Klassische Rotation durch den Restbestand | |
| all_sorted_date = sorted(all_products, key=lambda x: str(x.get('publication_date') or '1970'), reverse=True) | |
| start_idx = load_rotation_state() | |
| if start_idx >= len(all_sorted_date): start_idx = 0 | |
| curr_idx = start_idx | |
| loops = 0 | |
| # Wir loopen maximal 1x durch die ganze Liste | |
| while len(batch) < TARGET_COUNT and loops < len(all_sorted_date): | |
| item = all_sorted_date[curr_idx] | |
| if is_valid_candidate(item): | |
| add_to_batch(item) | |
| curr_idx += 1 | |
| if curr_idx >= len(all_sorted_date): curr_idx = 0 | |
| loops += 1 | |
| save_rotation_state(curr_idx) | |
| print(f"-> [Smart Select] {len(batch)} Produkte final. (Rotation ab Index {start_idx})") | |
| return batch | |
| def filter_deals_by_age(deals, max_age_days=730): | |
| cutoff = datetime.now() - timedelta(days=max_age_days); filtered = [] | |
| for d in deals: | |
| pub = d.get('publication_date') | |
| if not pub: filtered.append(d); continue | |
| try: | |
| if datetime.fromisoformat(pub.replace('Z', '+00:00')).replace(tzinfo=None) >= cutoff: filtered.append(d) | |
| except: filtered.append(d) | |
| return filtered | |
| # --- DASHBOARD RENDERING (RESTORED FULL) --- | |
| def render_html_layout(page_content, scan_type, theme_color, active_module, status_html="", extra_head_content=""): | |
| title = "CG Preis-Radar" | |
| tabs = f""" | |
| <a href="/" class="nav-tab {'active' if active_module == 'amazon' else ''}">Amazon</a> | |
| <a href="/ali" class="nav-tab {'active' if active_module == 'ali' else ''}">AliExpress</a> | |
| <a href="/mydealz" class="nav-tab {'active' if active_module == 'mydealz' else ''}">Mydealz</a> | |
| """ | |
| return f"""<!DOCTYPE html><html lang="de"><head><meta charset="UTF-8"><title>{title}</title>{extra_head_content}<style> | |
| body{{font-family:-apple-system,sans-serif;background:#f4f7f6;margin:0;padding:20px;color:#333}} | |
| .container{{max-width:98%;margin:auto;background:#fff;box-shadow:0 0 20px rgba(0,0,0,0.1);border-radius:10px;overflow:hidden}} | |
| header{{background:{theme_color};color:#fff;padding:15px 25px;display:flex;justify-content:space-between;align-items:center}} | |
| .header-left {{ display: flex; flex-direction: column; gap: 10px; }} | |
| .header-top-row {{ display: flex; align-items: baseline; gap: 15px; }} | |
| .header-title h1 {{ margin: 0; font-size: 1.8em; }} | |
| .status-info {{ font-size: 0.85em; opacity: 0.9; font-weight: 400; }} | |
| .nav-tab{{color:#fff;text-decoration:none;padding:8px 15px;border-radius:5px;background:rgba(255,255,255,0.1);transition:0.2s}} | |
| .nav-tab:hover{{background:rgba(255,255,255,0.25)}}.nav-tab.active{{background:rgba(0,0,0,0.3);font-weight:bold}} | |
| .content-wrapper{{padding:20px}} | |
| .actions-bar{{display:flex;gap:10px;margin-bottom:20px}} | |
| .button{{padding:10px 15px;color:#fff;text-decoration:none;border-radius:5px;border:none;cursor:pointer}} | |
| .button-main{{background:#27ae60}}.button-secondary{{background:#3498db}}.button-meta{{background:#95a5a6}} | |
| .dropdown {{ position: relative; display: inline-block; }}.dropdown-content {{ display: none; position: absolute; background-color: #f9f9f9; min-width: 180px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; border-radius: 5px; overflow: hidden;}}.dropdown-content a {{ color: black !important; padding: 12px 16px; text-decoration: none; display: block; }}.dropdown-content a:hover {{ background-color: #f1f1f1; }}.dropdown:hover .dropdown-content {{ display: block; }} | |
| table{{width:100%;border-collapse:collapse;margin-top:10px;table-layout: fixed;}} | |
| th,td{{padding:10px;border-bottom:1px solid #ddd;text-align:left;vertical-align:middle;word-wrap:break-word;overflow:hidden;}} | |
| th{{background:#e8eff5;cursor:pointer;user-select:none;font-size:0.9em}} | |
| th:hover{{background:#dfe6ed}} | |
| th:nth-child(1) {{ width: 4%; }} | |
| th:nth-child(2) {{ width: 4%; }} | |
| th:nth-child(3) {{ width: 32%; }} | |
| th:nth-child(4) {{ width: 8%; }} | |
| th:nth-child(5) {{ width: 10%; }} | |
| th:nth-child(6) {{ width: 7%; }} | |
| th:nth-child(7) {{ width: 7%; }} | |
| th:nth-child(8) {{ width: 7%; }} | |
| th:nth-child(9) {{ width: 11%; }} | |
| th:nth-child(10){{ width: 10%; }} | |
| .check-off-link{{font-size:0.8em;color:#7f8c8d;text-decoration:none}} | |
| .best-price-row{{background:#fff8e1}}.checked-off-row{{opacity:0.5;background:#f9f9f9;font-style:italic}} | |
| .arrow-down{{color:#27ae60}}.arrow-up{{color:#e74c3c}} | |
| .savings-green {{ color: #27ae60; font-weight: bold; }} | |
| .savings-red {{ color: #e74c3c; font-weight: bold; }} | |
| .savings-neutral {{ color: #7f8c8d; }} | |
| .unavailable {{ color: #e74c3c; font-weight: bold; font-style: italic; }} | |
| .status-cell {{ font-size: 1.5em; text-align: center; font-weight: bold; }} | |
| .graph-icon {{ cursor: pointer; font-size: 1.5em; color: #3498db; text-decoration: none; }} | |
| /* NEUE MICRO-BUTTONS */ | |
| .micro-btn {{ display: inline-block; padding: 2px 6px; font-size: 0.75em; font-weight: bold; border-radius: 3px; text-decoration: none; margin-right: 4px; font-family: monospace; }} | |
| .btn-keepa {{ background: #444; color: #fff; border-bottom: 2px solid #00a8e1; }} | |
| .btn-idealo {{ background: #003a7e; color: #fff; border-bottom: 2px solid #f96302; }} | |
| .btn-idealo:hover {{ background: #002d63; }} | |
| </style></head><body><div class="container"><header> | |
| <div class="header-left"><div class="header-top-row"><div class="header-title"><h1>{title}</h1></div><div class="status-info">{status_html}</div></div><nav>{tabs}</nav></div> | |
| <div class="header-logo"><img src="/static/cg_logo.png" alt="Logo" style="max-height:50px;"></div></header> | |
| <div class="content-wrapper"><h2>{scan_type}</h2>{page_content}</div></div></body></html>""" | |
| def render_dashboard_html(deals, scan_type, is_full_report=False): | |
| ts = get_amazon_timestamps() | |
| status_html = f"Main: <strong>{ts['main']}</strong> | Quick: <strong>{ts['quick']}</strong>" | |
| link = '<a href="/" class="button button-secondary">Zurück</a>' if is_full_report else '<a href="/full_report" class="button button-secondary">Archiv</a>' | |
| backup_html = """ | |
| <div style="margin-top: 5px; font-size: 0.85em; color: #666; text-align: right;"> | |
| 💾 <b>Backup:</b> | |
| <a href="/admin/download/checked_deals.json" title="Liste der abgehakten Artikel">Abgehakt</a> | | |
| <a href="/admin/download/unavailable_asin_tracker.json" title="Liste der toten Links">Blacklist</a> | | |
| <a href="/admin/download/mismatches.json" title="Liste der gemeldeten Fehler" style="color:#e74c3c; font-weight:bold;">⚠️ Fehler-Log</a> | | |
| <a href="/admin/download/radar.db" title="Komplette Datenbank">Datenbank</a> | |
| </div> | |
| """ | |
| actions = f""" | |
| <div class="actions-bar"> | |
| <div class="dropdown"> | |
| <button class="button button-main">Scans & Aktionen ▼</button> | |
| <div class="dropdown-content"> | |
| <a href="/start/quick">Quick-Scan starten</a> | |
| <a href="/start/main">Haupt-Scan starten</a> | |
| <a href="/start/mydealz_scan">Mydealz aktualisieren</a> | |
| <a href="/add_asin">ASIN hinzufügen</a> | |
| <hr style="margin:5px 0;border:0;border-top:1px solid #eee;"> | |
| <a href="/admin/update_cookies">🍪 Cookie Refresh</a> | |
| <a href="/admin/dev_upload">⚡ Dev Upload</a> | |
| </div> | |
| </div> | |
| {link} | |
| <div style="margin-left:auto"></div> | |
| <a href="/logs/scan.log" target="_blank" class="button button-meta">Logs</a> | |
| </div> | |
| {backup_html} | |
| """ | |
| js = """<script>function sortTable(n,isNum){var t=document.getElementById("deal-table"),r,sw,i,x,y,s,dir="asc",cnt=0;sw=true;while(sw){sw=false;r=t.rows;for(i=1;i<(r.length-1);i++){s=false;x=r[i].getElementsByTagName("TD")[n];y=r[i+1].getElementsByTagName("TD")[n];var xV=x.getAttribute('data-sort-value')||x.textContent.toLowerCase();var yV=y.getAttribute('data-sort-value')||y.textContent.toLowerCase();if(isNum){xV=parseFloat(xV);yV=parseFloat(yV);}if(dir=="asc"){if(xV>yV){s=true;break;}}else{if(xV<yV){s=true;break;}}}if(s){r[i].parentNode.insertBefore(r[i+1],r[i]);sw=true;cnt++;}else{if(cnt==0&&dir=="asc"){dir="desc";sw=true;}}}}</script>""" | |
| # Safe Rendering | |
| try: | |
| rows = generate_table_rows(deals) | |
| except Exception as e: | |
| rows = f"<tr><td colspan='10' style='color:red'>Rendering Error: {e}</td></tr>" | |
| table = f"""<table id="deal-table"><thead><tr><th onclick="sortTable(0,false)">#</th><th onclick="sortTable(1,true)">Trend</th><th onclick="sortTable(2,false)">Produkt</th><th onclick="sortTable(3,true)">Preis</th><th onclick="sortTable(4,false)">Coupon</th><th onclick="sortTable(5,true)">Endpreis</th><th onclick="sortTable(6,true)">CG-Preis</th><th onclick="sortTable(7,true)">Ersparnis</th><th onclick="sortTable(8,false)">Analyse</th><th onclick="sortTable(9,false)">Artikel</th></tr></thead><tbody>{rows}</tbody></table>""" | |
| return render_html_layout(actions + table, scan_type, "#00A8E1", "amazon", status_html, js) | |
| def render_mydealz_html(deals, checked_urls): | |
| ts = get_mydealz_timestamp() | |
| status_html = f"Letztes Update: <strong>{ts}</strong>" | |
| backup_html = """ | |
| <div style="margin-top: 5px; font-size: 0.85em; color: #666; text-align: right;"> | |
| 💾 <b>Backup:</b> | |
| <a href="/admin/download/mydealz_checked.json">Abgehakt</a> | | |
| <a href="/admin/download/mydealz_deals.json">Liste</a> | | |
| <a href="/admin/update_mydealz_cookies">🍪 Cookies</a> | |
| </div> | |
| """ | |
| actions = f"""<div class="actions-bar"><a href="/start/mydealz_scan" class="button button-main">Update Mydealz</a><div style="margin-left:auto"></div><a href="/logs/scan.log" target="_blank" class="button button-meta">Logs</a></div>{backup_html}""" | |
| deals.sort(key=lambda d: d.get('link','') in checked_urls) | |
| js = """<script>function sortTable(n,isNum){var t=document.getElementById("mydealz-table"),r,sw,i,x,y,s,dir="asc",cnt=0;sw=true;while(sw){sw=false;r=t.rows;for(i=1;i<(r.length-1);i++){s=false;x=r[i].getElementsByTagName("TD")[n];y=r[i+1].getElementsByTagName("TD")[n];var xV=x.getAttribute('data-val')||x.textContent.toLowerCase();var yV=y.getAttribute('data-val')||y.textContent.toLowerCase();if(isNum){xV=parseFloat(xV);yV=parseFloat(yV);}if(dir=="asc"){if(xV>yV){s=true;break;}}else{if(xV<yV){s=true;break;}}}if(s){r[i].parentNode.insertBefore(r[i+1],r[i]);sw=true;cnt++;}else{if(cnt==0&&dir=="asc"){dir="desc";sw=true;}}}}</script>""" | |
| rows = "" | |
| for i, d in enumerate(deals, 1): | |
| is_chk = d.get('link') in checked_urls | |
| b64 = base64.urlsafe_b64encode(d.get('link','').encode()).decode() | |
| link = f"<a href='/mydealz/{'reactivate' if is_chk else 'check_off'}/{b64}'>{'[Reaktivieren]' if is_chk else '[Abhaken]'}</a>" | |
| temp = d.get('temperature','0°'); temp_val = 0 | |
| try: temp_val = int(temp.replace('°','').replace('.','')) | |
| except: pass | |
| rows += f"""<tr class="{'checked-off-row' if is_chk else ''}"><td data-val="{i}">{i}<br><small>{link}</small></td><td data-val="{temp_val}" style="color:{'#e74c3c' if temp_val>500 else ''}">{temp}</td><td>{d.get('title')}</td><td>{d.get('price')}</td><td>{d.get('shop')}</td><td><a href="{d.get('link')}" target="_blank">Link</a></td></tr>""" | |
| table = f"""<table id="mydealz-table"><thead><tr><th onclick="sortTable(0,true)">#</th><th onclick="sortTable(1,true)">Temp</th><th onclick="sortTable(2,false)">Titel</th><th onclick="sortTable(3,false)">Preis</th><th onclick="sortTable(4,false)">Shop</th><th>Link</th></tr></thead><tbody>{rows}</tbody></table>""" | |
| return render_html_layout(actions + table, "Mydealz", "#87c540", "mydealz", status_html, js) | |
| def generate_table_rows(deals): | |
| # Lade Liste der gemeldeten Fehler für Visual Feedback | |
| reported_map = {} | |
| base_dir = "/data" if os.path.exists("/data") else os.path.dirname(os.path.abspath(__file__)) | |
| mismatch_path = os.path.join(base_dir, MISMATCH_FILE) | |
| if os.path.exists(mismatch_path): | |
| try: | |
| raw_data = json.load(open(mismatch_path)) | |
| for item in raw_data: | |
| asin = item.get('asin') | |
| e_type = item.get('error_type', 'product_mismatch') | |
| if asin not in reported_map: reported_map[asin] = [] | |
| reported_map[asin].append(e_type) | |
| except: pass | |
| rows = [] | |
| for index, deal in enumerate(deals, 1): | |
| # FIX: Safe .get() Access | |
| asin = deal.get('asin', 'N/A') | |
| full_name = deal.get('verified_name', 'N/A') | |
| # Filter (Safe) | |
| if "404" in full_name or "Nicht gefunden" in full_name or "Redirect" in full_name: continue | |
| if len(full_name) > 55: full_name = full_name[:55] + '...' | |
| pub_date = "unbekannt" | |
| if deal.get('publication_date'): | |
| try: pub_date = datetime.fromisoformat(deal['publication_date'].replace('Z', '+00:00')).strftime('%b %Y') | |
| except: pass | |
| bsr_val = deal.get('bsr') | |
| bsr_info = f"<br><span style='font-size:0.85em;color:#888'>BSR: #{bsr_val:,}</span>".replace(',', '.') if bsr_val and bsr_val != 999999 else "" | |
| info = f"<div style='font-size:0.85em;color:#666;margin-top:4px;'>ASIN: {asin} | {pub_date}{bsr_info}</div>" | |
| p_raw = deal.get('price', 0); c_raw = deal.get('coupon_details', 'N/A') | |
| try: p_float = float(p_raw) | |
| except: p_float = 0.0 | |
| is_unavail = (p_float <= 0.01) or (c_raw == "Nicht verfügbar") | |
| if is_unavail: continue | |
| price_h = f"{p_float:.2f}€" | |
| s_price = p_float | |
| c_val = 0.0 | |
| if c_raw != "Kein Coupon" and c_raw: | |
| if m := re.search(r'([\d.,]+)€', str(c_raw)): | |
| try: c_val = float(m.group(1).replace('.','').replace(',','.')) | |
| except: pass | |
| c_h = str(c_raw).replace("Checkbox-Coupon (€):", "Coupon:") | |
| else: c_h = "-" | |
| s_coup = c_val | |
| final = deal.get('final_price',0) | |
| end_h = f"<strong>{final:.2f}€</strong>"; s_final = final | |
| sav = deal.get('savings_percent','0'); sav_h = sav; s_sav = 0; sav_cls = "savings-neutral" | |
| if sav != 'Neu' and sav: | |
| try: | |
| s_sav = float(str(sav).replace('%','')) | |
| if s_sav < -0.1: sav_cls = "savings-green" | |
| elif s_sav > 0.1: sav_cls = "savings-red" | |
| except: pass | |
| ref = deal.get('reference_price', 0); ref_h = f"{ref:.2f}€" | |
| if deal.get('reference_price_source') == 'history': ref_h = f"<em style='color:#999' title='Historie'>{ref:.2f}€</em>" | |
| cls = "checked-off-row" if deal.get('is_checked_off') else ("best-price-row" if deal.get('sort_priority', 9) <= 3 else "") | |
| act = f"<a href='/reactivate/{asin}' class='check-off-link'>[Reaktivieren]</a>" if deal.get('is_checked_off') else f"<a href='/check_off/{asin}' class='check-off-link'>[Abhaken]</a>" | |
| ana = deal.get('analysis_text','') or "-" | |
| clean_title = _get_smart_idealo_query(deal.get('verified_name', ''), deal.get('source_article_slug', '')) | |
| idealo_link = f"https://www.idealo.de/preisvergleich/MainSearchProductCategory.html?q={clean_title}" if clean_title else f"https://www.idealo.de/preisvergleich/MainSearchProductCategory.html?q={asin}" | |
| keepa_link = f"https://keepa.com/#!product/3-{asin}" | |
| ana_h = f""" | |
| <div style='line-height:1.2'>{ana}</div> | |
| <div style='margin-top:5px;'> | |
| 📈 : | |
| <a href='{keepa_link}' class='micro-btn btn-keepa' target='_blank' title='Keepa Chart'>K</a> | |
| <a href='{idealo_link}' class='micro-btn btn-idealo' target='_blank' title='Idealo: {clean_title}'>I</a> | |
| </div> | |
| """ | |
| slug = deal.get('source_article_slug', ''); art_n = slug.replace('-', ' ').title()[:15] + "..." if slug else "Artikel" | |
| reports = reported_map.get(asin, []) | |
| if 'product_mismatch' in reports: btn_prod = "<span style='color:#27ae60;font-size:0.7em;'>✅ Produkt gemeldet</span>" | |
| else: btn_prod = f"<a href='/report_mismatch/{asin}' style='color:#e74c3c;font-size:0.75em;text-decoration:none;' title='Falsches Produkt'>⚠️ Produkt falsch?</a>" | |
| if 'price_error' in reports: btn_price = "<span style='color:#27ae60;font-size:0.7em;'>✅ Preis gemeldet</span>" | |
| else: btn_price = f"<a href='/report_price/{asin}' style='color:#e67e22;font-size:0.75em;text-decoration:none;' title='Falscher Preis'>💸 Preis falsch?</a>" | |
| report_area = f"<div style='margin-top:8px;border-top:1px solid #eee;padding-top:4px;display:flex;flex-direction:column;gap:3px;'>{btn_prod}{btn_price}</div>" | |
| rows.append(f"""<tr class="{cls}"><td data-sort-value="{index}">{index}<br>{act}</td><td class="status-cell" data-sort-value="{deal.get('sort_priority',99)}"><span class="{deal.get('trend_color_class','')}">{deal.get('trend_icon','-')}</span></td><td><a href="https://amazon.de/dp/{asin}" target="_blank" style="font-weight:600;text-decoration:none;color:#2c3e50;">{full_name}</a>{info}</td><td data-sort-value="{s_price}">{price_h}</td><td data-sort-value="{s_coup}" style="font-size:0.9em">{c_h}</td><td data-sort-value="{s_final}">{end_h}</td><td data-sort-value="{ref}">{ref_h}</td><td class="{sav_cls}" data-sort-value="{s_sav}">{sav_h}</td><td data-sort-value="{999 if deal.get('is_checked_off') else deal.get('sort_priority',99)}">{ana_h}</td><td><a href="{deal.get('source_article_url','#')}" target="_blank" style="font-size:0.9em">{art_n}</a>{report_area}</td></tr>""") | |
| return "".join(rows) | |
| if __name__ == '__main__': | |
| db_init(); cleanup_expired_tracked_asins(); start_time = time.time() | |
| if "--rebuild-master-list" in sys.argv: | |
| print("--- REBUILD ---"); conn = get_db_connection(); conn.execute("DELETE FROM products"); conn.commit(); conn.close() | |
| # FIX: Sicherer Aufruf über Modul-Objekt drm | |
| if HAS_MASTERPLAN: drm.update_master_product_list(); sys.exit() | |
| else: print("!! Masterplan Modul fehlt. Abbruch."); sys.exit() | |
| if "--quick" in sys.argv: | |
| print(f"\n--- QUICK SCAN START ({datetime.now().strftime('%H:%M:%S')}) ---") | |
| if not HAS_MASTERPLAN: print("!! Masterplan Modul fehlt. Scan nicht möglich."); sys.exit() | |
| last = load_full_scan_results() | |
| if not last: print("!! Kein Full-Scan."); sys.exit() | |
| rel = filter_deals_by_age(last, 730); hist = load_price_history() | |
| pre = analyze_and_sort_deals(rel, hist); hot = select_products_for_hotlist_scan(pre, hist) | |
| # Aufruf über Modul-Alias drm | |
| live, _ = drm.check_prices_of_master_list(hot) | |
| if live: hist = update_price_history(live) | |
| fin = analyze_and_sort_deals_deep(live or [], hist) | |
| save_quick_scan_results(fin); save_scan_timestamp("quick") | |
| elif "--main" in sys.argv or len(sys.argv) == 1: | |
| print(f"\n--- MAIN SCAN START ({datetime.now().strftime('%H:%M:%S')}) ---") | |
| if not HAS_MASTERPLAN: print("!! Masterplan Modul fehlt. Scan nicht möglich."); sys.exit() | |
| drm.update_master_product_list(); master = load_master_product_list() | |
| scan = filter_deals_by_age(list(master.values()), 730) | |
| live, success = drm.check_prices_of_master_list(scan); hist = load_price_history() | |
| if live: hist = update_price_history(live) | |
| fin = analyze_and_sort_deals_deep(live, hist) | |
| if success: save_full_scan_results(fin); drm.save_current_scan_time(); save_scan_timestamp("main") | |
| else: save_full_scan_results(fin) | |
| print(f"\n=== Ende nach {timedelta(seconds=int(time.time()-start_time))} ===") |