FULL PARSE KIT v1: 287 sources, 3-step fetch fallback, AI extraction, discovery+promote self-growth, gh_scan, TG feed, dashboard
This commit is contained in:
@@ -0,0 +1,381 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""FULL PARSE KIT — главный парсер.
|
||||
|
||||
128+ источников (форумы, пасты, TG-веб, RSS, JSON-API) -> scrape с
|
||||
3-ступенчатым фолбэком (plain HTTP -> free proxy pool -> Firecrawl) ->
|
||||
AI-экстракция (любой OpenAI-compatible endpoint) -> дедуп -> output/findings.jsonl
|
||||
|
||||
Запуск:
|
||||
python parse.py # все источники
|
||||
python parse.py --limit 5 # первые 5 (тест)
|
||||
python parse.py --topic combo # только тема
|
||||
|
||||
Конфиг: config.json (ai_url, ai_model) + data/creds.json (ai_key) или env AI_KEY.
|
||||
Firecrawl: env FIRECRAWL_API_KEY (можно несколько через запятую) — опционально.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
BASE = Path(__file__).resolve().parent
|
||||
OUTPUT_DIR = BASE / "output"
|
||||
OUTPUT_DIR.mkdir(exist_ok=True)
|
||||
STATE_FILE = BASE / "data" / "state.json"
|
||||
STATE_FILE.parent.mkdir(exist_ok=True)
|
||||
|
||||
|
||||
def _load_json(path: Path, default):
|
||||
if path.exists():
|
||||
try:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
return default
|
||||
return default
|
||||
|
||||
|
||||
CFG = _load_json(BASE / "config.json", {})
|
||||
CREDS = _load_json(BASE / "data" / "creds.json", {})
|
||||
AI_URL = os.environ.get("AI_URL") or CFG.get("ai_url") or CREDS.get("ai_url") or "http://127.0.0.1:8000/v1/chat/completions"
|
||||
AI_MODEL = os.environ.get("AI_MODEL") or CFG.get("ai_model") or "gpt-4o-mini"
|
||||
AI_KEY = os.environ.get("AI_KEY") or CREDS.get("ai_key") or CFG.get("ai_key") or ""
|
||||
|
||||
SOURCES = _load_json(BASE / "sources.json", [])
|
||||
_extra = _load_json(BASE / "sources_extra.json", [])
|
||||
_have = {s["id"] for s in SOURCES}
|
||||
SOURCES.extend([s for s in _extra if s.get("id") not in _have and s.get("url")])
|
||||
|
||||
EXTRACT_PROMPT = """Extract ALL noteworthy items from this forum/feed page: Telegram software/tools/services, FREEBIES and giveaways (free API credits, free AI subscriptions, free VPS/domains/emails/proxies/keys, trial offers), combos/configs/leaks/dumps, proxies, accounts, VPN, traffic/affiliate services, cracking tools.
|
||||
Return a JSON array of objects with these fields:
|
||||
- name: item/topic name
|
||||
- description: what it is/offers (1 line)
|
||||
- price: if mentioned (free/paid/price range)
|
||||
- type: one of [spammer, scraper, inviter, autoreg, userbot, combo, configs, proxy, carding, traffic, freebie, ai-credits, vpn, accounts, leak, tool, other]
|
||||
- url: link if available
|
||||
- author: username of poster/seller
|
||||
- date: when posted
|
||||
Return ONLY valid JSON array, no other text. If nothing noteworthy, return []."""
|
||||
|
||||
|
||||
def load_state():
|
||||
return _load_json(STATE_FILE, {"last_run": None, "scraped": {}, "findings": [], "seen": {}})
|
||||
|
||||
|
||||
def save_state(state):
|
||||
payload = json.dumps(state, ensure_ascii=False, indent=2)
|
||||
tmp = STATE_FILE.with_suffix(".json.tmp")
|
||||
for attempt in range(5):
|
||||
try:
|
||||
tmp.write_text(payload, encoding="utf-8")
|
||||
os.replace(tmp, STATE_FILE)
|
||||
return
|
||||
except OSError as e:
|
||||
if attempt == 4:
|
||||
print(f"[state] SAVE FAILED after 5 attempts: {e}", flush=True)
|
||||
return
|
||||
time.sleep(2 * (attempt + 1))
|
||||
|
||||
|
||||
# ── Firecrawl (обход Cloudflare/DDoS-Guard) ──
|
||||
|
||||
def _firecrawl_keys():
|
||||
keys = []
|
||||
ks = os.environ.get("FIRECRAWL_API_KEY") or os.environ.get("FIRECRAWL_KEYS") or CREDS.get("firecrawl_keys") or ""
|
||||
if ks:
|
||||
keys.extend(x.strip() for x in ks.split(",") if x.strip())
|
||||
return keys
|
||||
|
||||
|
||||
def _scrape_firecrawl(url: str):
|
||||
"""keyless v2 (rate-limit per-IP) -> keyed v1 (ротация)."""
|
||||
try:
|
||||
r = requests.post(
|
||||
"https://api.firecrawl.dev/v2/scrape",
|
||||
headers={"Content-Type": "application/json", "X-Origin": "mcp-fastmcp"},
|
||||
json={"url": url, "formats": ["markdown"], "onlyMainContent": True},
|
||||
timeout=120,
|
||||
)
|
||||
if r.status_code == 200:
|
||||
data = r.json()
|
||||
md = ""
|
||||
if isinstance(data.get("data"), dict):
|
||||
md = data["data"].get("markdown") or ""
|
||||
elif isinstance(data.get("data"), list) and data["data"]:
|
||||
md = data["data"][0].get("markdown") or ""
|
||||
if len(md) > 500:
|
||||
return md[:80000]
|
||||
except Exception as e:
|
||||
print(f" Firecrawl keyless error: {e}", flush=True)
|
||||
for key in _firecrawl_keys():
|
||||
try:
|
||||
r = requests.post(
|
||||
"https://api.firecrawl.dev/v1/scrape",
|
||||
headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"},
|
||||
json={"url": url, "formats": ["markdown"], "onlyMainContent": True},
|
||||
timeout=120,
|
||||
)
|
||||
if r.status_code == 200:
|
||||
md = (r.json().get("data") or {}).get("markdown") or ""
|
||||
if len(md) > 500:
|
||||
return md[:80000]
|
||||
continue
|
||||
if r.status_code in (401, 402, 403, 429):
|
||||
continue
|
||||
except Exception as e:
|
||||
print(f" Firecrawl error: {e}", flush=True)
|
||||
return None
|
||||
|
||||
|
||||
# ── прокси-пул (бесплатные HTTP) ──
|
||||
|
||||
_PROXY_FILE = BASE / "data" / "proxies_live.txt"
|
||||
|
||||
|
||||
def _proxy_pool(n: int = 5):
|
||||
import random
|
||||
proxies = []
|
||||
fresh = _PROXY_FILE.exists() and (time.time() - _PROXY_FILE.stat().st_mtime < 21600)
|
||||
if fresh:
|
||||
proxies = [l.strip() for l in _PROXY_FILE.read_text().splitlines() if l.strip().startswith("http")]
|
||||
if not proxies:
|
||||
for src_url in [
|
||||
"https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=8000&country=all&ssl=all&anonymity=all",
|
||||
"https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/http.txt",
|
||||
]:
|
||||
try:
|
||||
r = requests.get(src_url, timeout=20)
|
||||
for line in r.text.splitlines():
|
||||
line = line.strip()
|
||||
if re.match(r"^\d+\.\d+\.\d+\.\d+:\d+$", line):
|
||||
proxies.append("http://" + line)
|
||||
if len(proxies) > 80:
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if proxies:
|
||||
try:
|
||||
_PROXY_FILE.write_text("\n".join(proxies[:120]))
|
||||
except Exception:
|
||||
pass
|
||||
random.shuffle(proxies)
|
||||
return proxies[:n]
|
||||
|
||||
|
||||
def scrape_with_fallback(url: str):
|
||||
"""plain HTTP -> free proxy pool -> Firecrawl."""
|
||||
ua = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
|
||||
"Accept": "text/html,application/xhtml+xml,application/json;q=0.9",
|
||||
"Accept-Language": "en-US,en;q=0.9,ru;q=0.8",
|
||||
}
|
||||
try:
|
||||
r = requests.get(url, headers=ua, timeout=25)
|
||||
if r.status_code == 200 and len(r.text) > 1200:
|
||||
return r.text[:80000]
|
||||
print(f" HTTP {r.status_code}", flush=True)
|
||||
except Exception as e:
|
||||
print(f" HTTP error: {str(e)[:60]}", flush=True)
|
||||
for px in _proxy_pool(5):
|
||||
try:
|
||||
r = requests.get(url, headers=ua, timeout=25, proxies={"http": px, "https": px})
|
||||
if r.status_code == 200 and len(r.text) > 1200:
|
||||
print(f" via proxy {px}", flush=True)
|
||||
return r.text[:80000]
|
||||
except Exception:
|
||||
continue
|
||||
return _scrape_firecrawl(url)
|
||||
|
||||
|
||||
# ── AI-экстракция ──
|
||||
|
||||
def extract_with_ai(markdown: str):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if AI_KEY:
|
||||
headers["Authorization"] = "Bearer " + AI_KEY
|
||||
models = [AI_MODEL, "qwen-plus", "qwen-turbo"] if AI_MODEL not in ("qwen-plus", "qwen-turbo") else [AI_MODEL]
|
||||
for mdl in models:
|
||||
for attempt in range(2):
|
||||
try:
|
||||
r = requests.post(
|
||||
AI_URL,
|
||||
headers=headers,
|
||||
json={
|
||||
"model": mdl,
|
||||
"messages": [
|
||||
{"role": "system", "content": EXTRACT_PROMPT},
|
||||
{"role": "user", "content": markdown[:8000]},
|
||||
],
|
||||
"max_tokens": 4000,
|
||||
"temperature": 0.1,
|
||||
},
|
||||
timeout=180,
|
||||
)
|
||||
if r.status_code == 200:
|
||||
content = r.json()["choices"][0]["message"]["content"].strip()
|
||||
if content.startswith("```"):
|
||||
content = content.split("\n", 1)[1].rsplit("\n", 1)[0]
|
||||
if not content.startswith("["):
|
||||
m = re.search(r"\[.*\]", content, re.DOTALL)
|
||||
if m:
|
||||
content = m.group(0)
|
||||
return json.loads(content)
|
||||
print(f"AI {mdl} HTTP {r.status_code}", flush=True)
|
||||
if r.status_code in (401, 403):
|
||||
print("AI: нет доступа (проверь ключ/endpoint в dashboard)", flush=True)
|
||||
return []
|
||||
except Exception as e:
|
||||
print(f"AI {mdl} error: {str(e)[:60]}", flush=True)
|
||||
time.sleep(1.5)
|
||||
return []
|
||||
|
||||
|
||||
def _deep_threads(markdown: str, limit: int = 3) -> str:
|
||||
"""Для RSS: добираем тела свежих тредов."""
|
||||
if "<item>" not in markdown[:3000] and "<rss" not in markdown[:500]:
|
||||
return markdown
|
||||
links = re.findall(r"<link>\s*(https?://[^<]+?)\s*</link>", markdown)
|
||||
links = [l for l in links if not l.rstrip("/").endswith((".php", ".xml"))][1:limit + 1]
|
||||
extra = []
|
||||
for l in links:
|
||||
try:
|
||||
r = requests.get(l, headers={"User-Agent": "Mozilla/5.0"}, timeout=15)
|
||||
if r.status_code == 200 and len(r.text) > 2000:
|
||||
body = re.sub(r"<script.*?</script>|<style.*?</style>", " ", r.text, flags=re.DOTALL)
|
||||
body = re.sub(r"<[^>]+>", " ", body)
|
||||
body = re.sub(r"\s+", " ", body).strip()
|
||||
extra.append(f"\n\n=== THREAD {l} ===\n{body[:3500]}")
|
||||
except Exception:
|
||||
continue
|
||||
return markdown + "".join(extra)
|
||||
|
||||
|
||||
DISCOVERY_STATE = BASE / "data" / "discovery_state.json"
|
||||
|
||||
|
||||
def _harvest_candidates(markdown: str, findings: list):
|
||||
"""Self-growth: URL из находок -> discovery_state (promote.py проверит)."""
|
||||
try:
|
||||
st = _load_json(DISCOVERY_STATE, {"found": []})
|
||||
have = {s.get("url", "").lower() for s in st.get("found", [])} | {s["url"].lower() for s in SOURCES}
|
||||
added = 0
|
||||
for f in findings:
|
||||
u = (f.get("url") or "").strip().split("?")[0]
|
||||
if not u.startswith("http"):
|
||||
continue
|
||||
dom = re.sub(r"^www\.", "", u.split("/")[2].lower())
|
||||
if u.lower() in have or "t.me" in dom or "github" in dom:
|
||||
continue
|
||||
if any(k in dom for k in ["forum", "crack", "card", "leak", "hack", "null", "dump", "dark", "breach", "combo"]):
|
||||
st.setdefault("found", []).append({"url": u, "name": dom, "via": "parser-feedback"})
|
||||
have.add(u.lower())
|
||||
added += 1
|
||||
if added:
|
||||
tmp = DISCOVERY_STATE.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(st, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
os.replace(tmp, DISCOVERY_STATE)
|
||||
print(f" feedback: +{added} candidates -> discovery_state", flush=True)
|
||||
except Exception as e:
|
||||
print(f" feedback error: {str(e)[:60]}", flush=True)
|
||||
|
||||
|
||||
def _finding_key(f: dict) -> str:
|
||||
return hashlib.md5(f"{f.get('name','')}|{f.get('url','')}".lower().encode()).hexdigest()
|
||||
|
||||
|
||||
def process_source(src: dict, state: dict):
|
||||
sid = src["id"]
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
print(f"\n{'='*50}\n[{sid}] {src['url']}", flush=True)
|
||||
|
||||
markdown = scrape_with_fallback(src["url"])
|
||||
if not markdown:
|
||||
print(f"[{sid}] SKIP - no content", flush=True)
|
||||
return
|
||||
|
||||
content_hash = hashlib.sha256(markdown.encode()).hexdigest()
|
||||
prev_hash = state["scraped"].get(sid, {}).get("hash", "")
|
||||
if content_hash == prev_hash:
|
||||
print(f"[{sid}] SKIP - unchanged", flush=True)
|
||||
return
|
||||
|
||||
markdown = _deep_threads(markdown)
|
||||
findings = extract_with_ai(markdown)
|
||||
if not findings:
|
||||
print(f"[{sid}] SKIP - no AI findings", flush=True)
|
||||
return
|
||||
|
||||
seen = state.setdefault("seen", {})
|
||||
fresh = []
|
||||
for f in findings:
|
||||
k = _finding_key(f)
|
||||
if k not in seen:
|
||||
seen[k] = now[:10]
|
||||
fresh.append(f)
|
||||
if not fresh:
|
||||
state["scraped"][sid] = {"hash": content_hash, "at": now, "count": 0}
|
||||
print(f"[{sid}] SKIP - all {len(findings)} findings already seen", flush=True)
|
||||
return
|
||||
findings = fresh
|
||||
|
||||
raw_path = OUTPUT_DIR / f"{sid}_{now[:10]}.md"
|
||||
raw_path.write_text(markdown, encoding="utf-8")
|
||||
|
||||
for f in findings:
|
||||
f["source"] = sid
|
||||
f["source_url"] = src["url"]
|
||||
f["scraped_at"] = now
|
||||
|
||||
state["scraped"][sid] = {"hash": content_hash, "at": now, "count": len(findings)}
|
||||
state["findings"].extend(findings)
|
||||
state["last_run"] = now
|
||||
|
||||
with open(OUTPUT_DIR / "findings.jsonl", "a", encoding="utf-8") as f:
|
||||
for finding in findings:
|
||||
f.write(json.dumps(finding, ensure_ascii=False) + "\n")
|
||||
|
||||
print(f"[{sid}] +{len(findings)} findings", flush=True)
|
||||
_harvest_candidates(markdown, findings)
|
||||
|
||||
|
||||
def main():
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
srcs = SOURCES
|
||||
if "--limit" in sys.argv:
|
||||
srcs = srcs[:int(sys.argv[sys.argv.index("--limit") + 1])]
|
||||
if "--topic" in sys.argv:
|
||||
t = sys.argv[sys.argv.index("--topic") + 1].lower()
|
||||
srcs = [s for s in srcs if t in (s.get("topic") or "").lower()]
|
||||
|
||||
state = load_state()
|
||||
print(f"STATE: {len(state['scraped'])} sources tracked, {len(state['findings'])} findings, "
|
||||
f"{len(state.get('seen', {}))} dedupe keys", flush=True)
|
||||
print(f"SOURCES: {len(srcs)} | AI: {AI_URL} ({AI_MODEL})", flush=True)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=8) as ex:
|
||||
futs = {ex.submit(process_source, src, state): src for src in srcs}
|
||||
for fut in as_completed(futs):
|
||||
src = futs[fut]
|
||||
try:
|
||||
fut.result()
|
||||
except Exception as e:
|
||||
print(f"[{src['id']}] ERROR: {e}", flush=True)
|
||||
save_state(state)
|
||||
|
||||
print(f"\nDONE. {len(state['findings'])} total findings in {OUTPUT_DIR}", flush=True)
|
||||
save_state(state)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user