Download ali_engine.py from cg-preis/radar: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/spaces/cg-preis/radar/resolve/main/ali_engine.py
- Command line
-
hf download hf://spaces/cg-preis/radar/ali_engine.py
-
curl -L -o ali_engine.py https://huggingface.co/spaces/cg-preis/radar/resolve/main/ali_engine.py
11 kB
| # Datei: ali_engine.py | |
| # VERSION: Phönix 9.1 (Stealth Batching & Human Mimesis) | |
| import os | |
| import sys | |
| import time | |
| import json | |
| import re | |
| import random | |
| import subprocess | |
| import argparse | |
| import sqlite3 | |
| import requests | |
| import concurrent.futures | |
| from datetime import datetime, timedelta | |
| from urllib.parse import unquote, urlparse, parse_qs | |
| # Selenium | |
| import undetected_chromedriver as uc | |
| from selenium.webdriver.common.by import By | |
| from selenium.webdriver.common.action_chains import ActionChains | |
| from selenium.webdriver.support.ui import WebDriverWait | |
| from selenium.webdriver.support import expected_conditions as EC | |
| # --- CONFIG --- | |
| IS_CLOUD_ENV = os.environ.get("IS_DOCKER") and os.path.exists("/data") | |
| BASE_DIR = "/data" if IS_CLOUD_ENV else os.path.dirname(os.path.abspath(__file__)) | |
| DB_FILE = os.path.join(BASE_DIR, "radar.db") | |
| COOKIES_FILE = "ali_cookies.json" | |
| # Files | |
| ALI_FULL_SCAN_FILE = "ali_full_scan.json" | |
| ALI_QUICK_SCAN_FILE = "ali_quick_scan.json" | |
| LOG_FILE = "scan.log" | |
| # --- LOGGING --- | |
| class Logger: | |
| def __init__(self): | |
| self.terminal = sys.stdout | |
| self.log = open(os.path.join(BASE_DIR, LOG_FILE), "a", encoding='utf-8', buffering=1) | |
| def write(self, message): | |
| self.terminal.write(message) | |
| try: self.log.write(message); self.log.flush(); os.fsync(self.log.fileno()) | |
| except: pass | |
| def flush(self): self.terminal.flush() | |
| sys.stdout = Logger() | |
| sys.stderr = sys.stdout | |
| # --- DB HELPERS --- | |
| def get_db_connection(): | |
| conn = sqlite3.connect(DB_FILE) | |
| conn.row_factory = sqlite3.Row | |
| return conn | |
| def update_price_history(ali_id, price): | |
| if price <= 0: return | |
| conn = get_db_connection(); c = conn.cursor() | |
| try: | |
| c.execute("INSERT INTO price_history (asin, date, price) VALUES (?, ?, ?) ON CONFLICT(asin, date) DO UPDATE SET price = excluded.price", (ali_id, datetime.now().strftime('%Y-%m-%d'), price)) | |
| conn.commit() | |
| except: pass | |
| conn.close() | |
| def get_ali_items_from_db(days_back=90): | |
| conn = get_db_connection(); c = conn.cursor() | |
| # Nur valide Ali-IDs (1005... und 16 Zeichen) | |
| query = "SELECT * FROM products WHERE asin GLOB '1005[0-9]*' AND length(asin) = 16" | |
| if days_back <= 300: | |
| query += f" AND publication_date >= date('now','-{days_back} days')" | |
| query += " ORDER BY publication_date DESC" | |
| c.execute(query); rows = c.fetchall(); conn.close() | |
| return [dict(r) for r in rows] | |
| # --- BROWSER MANAGEMENT --- | |
| def kill_browser_processes(): | |
| """Räumt alte Prozesse auf, um Handle-Fehler zu vermeiden""" | |
| if IS_CLOUD_ENV: | |
| subprocess.run("pkill -9 -f chrome", shell=True) | |
| subprocess.run("pkill -9 -f Xvfb", shell=True) | |
| else: | |
| # Windows Kill | |
| os.system("taskkill /f /im chrome.exe >nul 2>&1") | |
| os.system("taskkill /f /im chromedriver.exe >nul 2>&1") | |
| def start_browser(): | |
| # Zuerst aufräumen | |
| # kill_browser_processes() # Vorsicht: Nicht bei jedem Batch, sonst killt er sich selbst? | |
| # Nein, wir rufen start_browser nur am Anfang eines Batches auf. | |
| if IS_CLOUD_ENV: | |
| try: | |
| subprocess.Popen(["Xvfb", ":99", "-screen", "0", "1920x1080x24", "-ac"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) | |
| os.environ["DISPLAY"] = ":99" | |
| time.sleep(2) | |
| except: pass | |
| options = uc.ChromeOptions() | |
| options.add_argument("--no-sandbox") | |
| options.add_argument("--disable-dev-shm-usage") | |
| options.add_argument("--lang=de-DE") | |
| options.add_argument("--window-size=1600,1000") | |
| options.add_argument("--disable-blink-features=AutomationControlled") | |
| options.add_argument("--disable-infobars") | |
| options.page_load_strategy = 'normal' # Warten bis Seite geladen (wichtig für JS) | |
| try: return uc.Chrome(options=options) | |
| except: return None | |
| def inject_cookies(driver): | |
| fp = os.path.join(BASE_DIR, COOKIES_FILE) | |
| if not os.path.exists(fp): | |
| print(" ⚠️ Keine Cookies. Preise evtl. falsch (Neukunden).") | |
| return False | |
| try: | |
| driver.get("https://www.aliexpress.com/404"); time.sleep(1.5) | |
| with open(fp, 'r') as f: cookies = json.load(f) | |
| for c in cookies: | |
| if ".aliexpress" in c.get('domain',''): | |
| if 'expiry' not in c and 'expirationDate' in c: c['expiry'] = int(c['expirationDate']) | |
| if 'sameSite' in c: del c['sameSite'] | |
| try: driver.add_cookie(c) | |
| except: pass | |
| driver.refresh(); time.sleep(2) | |
| return True | |
| except: return False | |
| # --- HUMAN MIMESIS --- | |
| def simulate_human_behavior(driver): | |
| """Simuliert Scrollen und Mausbewegungen""" | |
| try: | |
| # 1. Zufällig scrollen (Page Down / Scroll Wheel Simulation) | |
| scroll_amount = random.randint(300, 700) | |
| driver.execute_script(f"window.scrollBy(0, {scroll_amount});") | |
| time.sleep(random.uniform(0.5, 1.5)) | |
| # 2. Kurze Mausbewegung (falls möglich) | |
| try: | |
| action = ActionChains(driver) | |
| action.move_by_offset(random.randint(10, 50), random.randint(10, 50)).perform() | |
| except: pass | |
| # 3. Kleines Stück zurück oder weiter scrollen | |
| driver.execute_script(f"window.scrollBy(0, {random.randint(-100, 200)});") | |
| time.sleep(random.uniform(0.5, 1.0)) | |
| except: pass | |
| # --- EXTRACTOR --- | |
| def extract_ali_data(driver, ali_id, context_data=None): | |
| # Sauberer Link ohne Tracking-Müll, aber mit Währungs-Parametern | |
| url = f"https://www.aliexpress.com/item/{ali_id}.html?gatewayAdapt=glo2deu&shipTo=DE¤cy=EUR" | |
| try: | |
| driver.get(url) | |
| # Human Behavior (WICHTIG gegen Slider!) | |
| simulate_human_behavior(driver) | |
| # Slider Check | |
| if "unusual traffic" in driver.page_source.lower(): | |
| print(" ⚠️ Slider entdeckt (Trotz Stealth).") | |
| return {"id": ali_id, "status": "Slider Block", "live_price": 0} | |
| except: | |
| return {"id": ali_id, "status": "Crash", "live_price": 0} | |
| res = {"id": ali_id, "live_price": 0.0, "status": "Check", "image": "", "url": url, "timestamp": datetime.now().strftime('%d.%m. %H:%M')} | |
| if context_data: res.update(context_data) | |
| if "Page Not Found" in driver.title or "404" in driver.title: | |
| res["status"] = "404" | |
| return res | |
| # 1. Bild (OG Meta) | |
| try: | |
| og_img = driver.find_element(By.CSS_SELECTOR, 'meta[property="og:image"]') | |
| if og_img: res['image'] = og_img.get_attribute('content') | |
| except: pass | |
| # 2. Preis (Forensik-Selector) | |
| found_price = 0.0 | |
| try: | |
| # Selektor-Liste aus Forensik-Labor | |
| els = driver.find_elements(By.CSS_SELECTOR, "[class*='price-default--current'], [class*='product-price-current'], [class*='price--currentPriceText']") | |
| for el in els: | |
| if el.is_displayed(): | |
| txt = re.sub(r'[^\d.,]', '', el.text.replace('€','').replace('EUR','').strip()) | |
| if ',' in txt and '.' in txt: txt = txt.replace('.', '').replace(',', '.') | |
| elif ',' in txt: txt = txt.replace(',', '.') | |
| if txt: | |
| try: found_price = float(txt); break | |
| except: pass | |
| except: pass | |
| # Fallback Regex | |
| if found_price == 0: | |
| src = driver.page_source | |
| m = re.search(r'currentPrice"\s*:\s*([\d.]+)', src) | |
| if m: found_price = float(m.group(1)) | |
| res['live_price'] = found_price | |
| if res['live_price'] > 0: | |
| res['status'] = "Active" | |
| update_price_history(ali_id, res['live_price']) | |
| else: | |
| res['status'] = "No Price" | |
| print(f" -> {ali_id} | {res['live_price']}€ | Img: {'✅' if res['image'] else '❌'}") | |
| return res | |
| # --- BATCH RUNNER --- | |
| def run_db_scan(mode="quick"): | |
| days = 90 if mode == "quick" else 365 | |
| items = get_ali_items_from_db(days) | |
| if not items: print("-> DB Leer / Keine validen IDs."); return | |
| # --- LOGIK: SORTIERUNG FÜR QUICK SCAN --- | |
| # 1. Die allerneuesten (letzte 7 Tage) kommen ZUERST (Hype-Potential) | |
| # 2. Der Rest wird gemischt (Rotation) | |
| cutoff = datetime.now() - timedelta(days=7) | |
| new_items = [i for i in items if i['publication_date'] >= cutoff.strftime('%Y-%m-%d')] | |
| old_items = [i for i in items if i['publication_date'] < cutoff.strftime('%Y-%m-%d')] | |
| random.shuffle(old_items) | |
| sorted_items = new_items + old_items # Neue zuerst! | |
| print(f"=== DB SCAN ({len(items)} Items | Mode: {mode}) ===") | |
| print(f" -> Priorität: {len(new_items)} neue Artikel zuerst.") | |
| # --- BATCHING --- | |
| BATCH_SIZE = 15 | |
| total_processed = 0 | |
| all_results = [] | |
| # Vorherige Ergebnisse laden, um nicht alles zu verlieren | |
| target_file = ALI_FULL_SCAN_FILE if mode == "main" else ALI_QUICK_SCAN_FILE | |
| if os.path.exists(os.path.join(BASE_DIR, target_file)): | |
| try: all_results = json.load(open(os.path.join(BASE_DIR, target_file))) | |
| except: pass | |
| # Items in Chunks unterteilen | |
| for i in range(0, len(sorted_items), BATCH_SIZE): | |
| batch = sorted_items[i : i + BATCH_SIZE] | |
| print(f"\n🚀 Starte Batch {i//BATCH_SIZE + 1} ({len(batch)} Items)...") | |
| # Browser Start | |
| kill_browser_processes() | |
| driver = start_browser() | |
| if not driver: | |
| print("!! Browser-Fehler. Warte 30s..."); time.sleep(30); continue | |
| inject_cookies(driver) | |
| batch_results = [] | |
| for item in batch: | |
| res = extract_ali_data(driver, item['asin'], item) | |
| batch_results.append(res) | |
| # Anti-Spam Pause zwischen Artikeln | |
| time.sleep(random.uniform(2, 4)) | |
| # Notbremse bei Slider Block | |
| if res['status'] == "Slider Block": | |
| print(" 🛑 Batch abgebrochen wegen Slider.") | |
| break | |
| driver.quit() | |
| # Ergebnisse mergen & speichern | |
| # Wir aktualisieren die alten Ergebnisse mit den neuen | |
| result_map = {r['id']: r for r in all_results} | |
| for r in batch_results: result_map[r['id']] = r | |
| all_results = list(result_map.values()) | |
| with open(os.path.join(BASE_DIR, target_file), 'w') as f: | |
| json.dump(all_results, f, indent=2) | |
| total_processed += len(batch_results) | |
| print(f"✅ Batch fertig. Gespeichert. Pause 10s...") | |
| time.sleep(10) # Cooldown für IP/Fingerprint | |
| print(f"\n=== Scan beendet ({total_processed} Items) ===") | |
| if __name__ == '__main__': | |
| if "--main" in sys.argv: run_db_scan("main") | |
| elif "--quick" in sys.argv: run_db_scan("quick") |