Cryped-Official's picture
Create app.py
0f7cb10 verified
Raw History Blame Contribute Delete
22.1 kB
import os
import time
import re
import socket
import io
import threading
import logging
import concurrent.futures
import asyncio
from urllib.parse import urlparse
from contextlib import asynccontextmanager
import requests
import aiohttp
import pandas as pd
import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from huggingface_hub import HfApi
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(threadName)s - %(levelname)s - %(message)s'
)
# --- IN-MEMORY DATA STORE ---
store = {
"active_proxies": {}, # proxy_string -> proxy dict
"candidate_proxies": {}, # proxy_string -> candidate dict
"domain_stats": {}, # (proxy, domain) -> stats dict
"request_logs": [], # list of log dicts (capped at 10,000)
"blacklist": set(), # proxy strings never to retry
}
# Using RLock to prevent deadlocks when calculate_score is called within a locked block
store_lock = threading.RLock()
# --- HUGGING FACE PERSISTENCE ---
HF_TOKEN = os.environ.get("HF_TOKEN")
REPO_ID = os.environ.get("HF_DATASET_REPO")
api = HfApi(token=HF_TOKEN) if HF_TOKEN else None
def restore_from_hf():
if not api or not REPO_ID:
logging.info("HF_TOKEN or HF_DATASET_REPO not set. Skipping restore.")
return
try:
for filename, target_key, key_field in [
("active_proxies.parquet", "active_proxies", "proxy"),
("candidate_proxies.parquet", "candidate_proxies", "proxy"),
("request_logs.parquet", "request_logs", None),
]:
try:
path = api.hf_hub_download(
repo_id=REPO_ID,
filename=filename,
repo_type="dataset"
)
df = pd.read_parquet(path)
with store_lock:
if key_field:
store[target_key] = {
row[key_field]: row.to_dict()
for _, row in df.iterrows()
}
else:
store[target_key] = df.to_dict(orient="records")
except Exception as e:
logging.warning(f"Could not restore {filename}: {e}")
# Restore domain_stats
try:
path = api.hf_hub_download(repo_id=REPO_ID, filename="domain_stats.parquet", repo_type="dataset")
df = pd.read_parquet(path)
with store_lock:
for _, row in df.iterrows():
d = row.to_dict()
key = (d.pop("proxy"), d.pop("domain"))
store["domain_stats"][key] = d
except Exception as e:
logging.warning(f"Could not restore domain_stats.parquet: {e}")
logging.info("Successfully restored state from Hugging Face Dataset Bucket.")
except Exception as e:
logging.info(f"HF restore failed (likely first run): {e}")
def sync_to_hf():
if not api or not REPO_ID:
return
with store_lock:
proxies_df = pd.DataFrame(list(store["active_proxies"].values()))
candidates_df = pd.DataFrame(list(store["candidate_proxies"].values()))
domain_df = pd.DataFrame([
{"proxy": k[0], "domain": k[1], **v}
for k, v in store["domain_stats"].items()
])
logs_df = pd.DataFrame(store["request_logs"][-5000:])
for df, filename in [
(proxies_df, "active_proxies.parquet"),
(candidates_df, "candidate_proxies.parquet"),
(domain_df, "domain_stats.parquet"),
(logs_df, "request_logs.parquet"),
]:
if df.empty:
continue
buf = io.BytesIO()
df.to_parquet(buf, index=False)
buf.seek(0)
try:
api.upload_file(
path_or_fileobj=buf,
path_in_repo=filename,
repo_id=REPO_ID,
repo_type="dataset"
)
except Exception as e:
logging.error(f"Failed to upload {filename} to HF: {e}")
# --- SCORING LOGIC ---
def calculate_score(proxy_data, domain=None):
success_rate = proxy_data.get("success_rate", 0)
uptime = proxy_data.get("uptime", 0)
latency = proxy_data.get("latency", 9999)
latency_score = max(0, 100 - (latency / 50))
domain_score = 50
if domain:
key = (proxy_data["proxy"], domain)
with store_lock:
if key in store["domain_stats"]:
domain_score = store["domain_stats"][key]["success_rate"] * 100
score = (
success_rate * 100 * 0.40 +
uptime * 100 * 0.30 +
latency_score * 0.20 +
domain_score * 0.10
)
return round(score, 2)
# --- SERVICE 1: PROXY SCRAPER ---
PROXY_SOURCES = [
("https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/http.txt", "http"),
("https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/socks5.txt", "socks5"),
("https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/socks4.txt", "socks4"),
("https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/http.txt", "http"),
("https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/https.txt", "https"),
("https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/socks4.txt", "socks4"),
("https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/socks5.txt", "socks5"),
("https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/http.txt", "http"),
("https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/socks4.txt", "socks4"),
("https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/socks5.txt", "socks5"),
("https://raw.githubusercontent.com/clarketm/proxy-list/master/proxy-list-raw.txt", "http"),
("https://raw.githubusercontent.com/sunny9577/proxy-scraper/master/proxies.txt", "http"),
("https://api.proxyscrape.com/v2/?request=getproxies&protocol=http", "http"),
("https://api.proxyscrape.com/v2/?request=getproxies&protocol=socks4", "socks4"),
("https://api.proxyscrape.com/v2/?request=getproxies&protocol=socks5", "socks5"),
]
def add_candidate(proxy_str, source, protocol):
with store_lock:
if proxy_str in store["blacklist"]: return
if proxy_str in store["active_proxies"]: return
if proxy_str in store["candidate_proxies"]: return
store["candidate_proxies"][proxy_str] = {
"proxy": proxy_str,
"source": source,
"protocol": protocol,
"found_at": time.time()
}
def scraper_loop():
while True:
try:
for url, protocol in PROXY_SOURCES:
try:
resp = requests.get(url, timeout=15)
lines = resp.text.split('\n')
for line in lines:
line = line.strip()
if re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{2,5}$', line):
add_candidate(line, url.split('/')[-1], protocol)
except Exception as e:
logging.error(f"Scraper source error {url}: {e}")
logging.info("Scraper cycle complete. Sleeping for 10 minutes.")
time.sleep(600)
except Exception as e:
logging.error(f"Scraper loop error: {e}")
time.sleep(60)
# --- SERVICE 2 & 4: VALIDATORS ---
def validate_single_proxy(proxy_str, candidate):
ip, port_str = proxy_str.split(':')
port = int(port_str)
# Step 1: TCP Connect
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
sock.connect((ip, port))
sock.close()
except:
return None, True # TCP failed, blacklist
proxy_url = f"http://{proxy_str}"
proxies_dict = {"http": proxy_url, "https": proxy_url}
# Step 2: HTTP Request & Latency
start_time = time.time()
try:
resp = requests.get("http://httpbin.org/ip", proxies=proxies_dict, timeout=8)
http_latency = (time.time() - start_time) * 1000
ip_data = resp.json()
except:
return None, False
# Step 3: HTTPS Request
try:
requests.get("https://httpbin.org/ip", proxies=proxies_dict, timeout=8)
supports_https = True
except:
supports_https = False
# Step 4: IP Verification
origin_ip = ip_data.get("origin", "").split(",")[0].strip()
is_transparent = (origin_ip == ip)
# Step 6: Anonymity Classification
anonymity = "Unknown"
try:
headers_resp = requests.get("http://httpbin.org/headers", proxies=proxies_dict, timeout=8)
headers = headers_resp.json().get("headers", {})
if "X-Forwarded-For" in headers:
anonymity = "Transparent" if is_transparent else "Anonymous"
else:
anonymity = "Elite"
except:
pass
proxy_dict = {
"proxy": proxy_str,
"protocol": candidate.get("protocol", "http"),
"country": "Unknown",
"asn": "Unknown",
"latency": http_latency,
"score": 0.0,
"status": "ACTIVE",
"success_rate": 1.0,
"uptime": 1.0,
"last_checked": time.time(),
"recent_results": [1.0],
"total_successes": 1,
"total_checks": 1,
"consecutive_fails": 0,
"supports_https": supports_https,
"anonymity": anonymity
}
proxy_dict["score"] = calculate_score(proxy_dict)
return proxy_dict, False
def validator_new_loop():
while True:
try:
with store_lock:
batch = list(store["candidate_proxies"].items())[:50]
for k, _ in batch:
del store["candidate_proxies"][k]
if not batch:
time.sleep(5)
continue
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
future_to_proxy = {}
for proxy_str, candidate in batch:
future = executor.submit(validate_single_proxy, proxy_str, candidate)
future_to_proxy[future] = proxy_str
for future in concurrent.futures.as_completed(future_to_proxy):
proxy_str = future_to_proxy[future]
try:
result, should_blacklist = future.result()
if result:
with store_lock:
store["active_proxies"][result["proxy"]] = result
elif should_blacklist:
with store_lock:
store["blacklist"].add(proxy_str)
except Exception as e:
logging.error(f"Validation future error for {proxy_str}: {e}")
except Exception as e:
logging.error(f"Validator new loop error: {e}")
time.sleep(5)
def validator_existing_loop():
while True:
try:
time.sleep(180) # 3 minutes
with store_lock:
active = [p for p in store["active_proxies"].values() if p["status"] != "BLACKLISTED"]
active.sort(key=lambda x: x["last_checked"])
batch = active[:100]
if not batch:
continue
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
future_to_proxy = {}
for p in batch:
future = executor.submit(validate_single_proxy, p["proxy"], p)
future_to_proxy[future] = p["proxy"]
for future in concurrent.futures.as_completed(future_to_proxy):
proxy_str = future_to_proxy[future]
try:
result, should_blacklist = future.result()
with store_lock:
if proxy_str not in store["active_proxies"]:
continue
current = store["active_proxies"][proxy_str]
if result:
current["status"] = "ACTIVE"
current["latency"] = 0.7 * current["latency"] + 0.3 * result["latency"]
current["recent_results"].append(1.0)
if len(current["recent_results"]) > 20:
current["recent_results"] = current["recent_results"][-20:]
current["success_rate"] = sum(current["recent_results"]) / len(current["recent_results"])
current["total_successes"] += 1
current["total_checks"] += 1
current["consecutive_fails"] = 0
current["last_checked"] = time.time()
current["score"] = calculate_score(current)
else:
current["recent_results"].append(0.0)
if len(current["recent_results"]) > 20:
current["recent_results"] = current["recent_results"][-20:]
current["success_rate"] = sum(current["recent_results"]) / len(current["recent_results"])
current["total_checks"] += 1
current["consecutive_fails"] += 1
current["last_checked"] = time.time()
if current["consecutive_fails"] >= 2:
current["status"] = "DEAD"
del store["active_proxies"][proxy_str]
elif (current["total_checks"] - current["total_successes"]) >= 3 and current["total_successes"] == 0:
store["blacklist"].add(proxy_str)
del store["active_proxies"][proxy_str]
else:
current["status"] = "SUSPECT"
current["score"] = calculate_score(current)
except Exception as e:
logging.error(f"Validator 2 future error for {proxy_str}: {e}")
except Exception as e:
logging.error(f"Validator existing loop error: {e}")
# --- SERVICE 5: REQUEST ROUTER + PROXY API ---
STAGGER_DELAYS = [0, 1, 3, 5, 7]
def select_proxies_for_domain(domain, n=10):
with store_lock:
active = [
p for p in store["active_proxies"].values()
if p["status"] == "ACTIVE"
]
scored = sorted(active, key=lambda p: calculate_score(p, domain), reverse=True)
return scored[:n]
async def hedged_request(url, proxies, method, headers, body, proxy_timeout, domain):
queue = asyncio.Queue(maxsize=1)
tasks = []
async def attempt(proxy_dict, delay):
await asyncio.sleep(delay)
if not queue.empty(): return
proxy_url = f"http://{proxy_dict['proxy']}"
session = aiohttp.ClientSession()
try:
resp = await session.request(
method, url, headers=headers, data=body,
proxy=proxy_url, timeout=aiohttp.ClientTimeout(total=proxy_timeout)
)
if not queue.empty():
await session.close()
return
await queue.put((session, resp, proxy_dict))
except Exception:
await session.close()
for i, proxy in enumerate(proxies):
delay = STAGGER_DELAYS[i] if i < len(STAGGER_DELAYS) else STAGGER_DELAYS[-1]
task = asyncio.create_task(attempt(proxy, delay, queue))
tasks.append(task)
while queue.empty() and not all(t.done() for t in tasks):
await asyncio.sleep(0.1)
for t in tasks:
if not t.done():
t.cancel()
if not queue.empty():
session, resp, proxy_dict = queue.get_nowait()
async def stream_gen():
success = False
start_time = time.time()
try:
async for chunk in resp.content.iter_any():
yield chunk
success = True
finally:
latency = (time.time() - start_time) * 1000
await resp.release()
await session.close()
with store_lock:
log_entry = {
"timestamp": time.time(),
"proxy": proxy_dict["proxy"],
"domain": domain,
"success": success,
"latency": latency
}
store["request_logs"].append(log_entry)
if len(store["request_logs"]) > 10000:
store["request_logs"] = store["request_logs"][-10000:]
key = (proxy_dict["proxy"], domain)
if key not in store["domain_stats"]:
store["domain_stats"][key] = {
"proxy": proxy_dict["proxy"],
"domain": domain,
"success_count": 0,
"failure_count": 0,
"success_rate": 0.0
}
stats = store["domain_stats"][key]
if success:
stats["success_count"] += 1
else:
stats["failure_count"] += 1
total = stats["success_count"] + stats["failure_count"]
stats["success_rate"] = stats["success_count"] / total if total > 0 else 0.0
proxy_dict["score"] = calculate_score(proxy_dict, domain)
return StreamingResponse(stream_gen(), media_type=resp.headers.get("Content-Type", "application/octet-stream"))
else:
raise HTTPException(status_code=503, detail="All proxies failed")
app = FastAPI()
class FetchRequest(BaseModel):
url: str
method: str = "GET"
headers: dict = {}
body: str = None
proxy_timeout: int = 10
total_timeout: int = 30
max_retries: int = 3
preferred_country: str = None
parallel_fallback: bool = True
@app.post("/fetch")
async def fetch(req: FetchRequest):
parsed = urlparse(req.url)
domain = parsed.netloc
proxies = select_proxies_for_domain(domain, n=10)
if req.preferred_country:
country_proxies = [p for p in proxies if p.get("country") == req.preferred_country]
other_proxies = [p for p in proxies if p.get("country") != req.preferred_country]
proxies = country_proxies + other_proxies
if not proxies:
raise HTTPException(status_code=503, detail="No active proxies available")
return await hedged_request(
req.url, proxies, req.method, req.headers, req.body, req.proxy_timeout, domain
)
@app.get("/stats")
async def get_stats():
with store_lock:
active_count = len(store["active_proxies"])
candidate_count = len(store["candidate_proxies"])
blacklist_count = len(store["blacklist"])
top_proxies = sorted(
store["active_proxies"].values(),
key=lambda x: x["score"],
reverse=True
)[:10]
return {
"active_proxies": active_count,
"candidate_queue": candidate_count,
"blacklisted": blacklist_count,
"top_proxies": top_proxies,
"last_hf_sync": getattr(hf_sync_loop, "last_sync", None)
}
@app.get("/health")
async def get_health():
return {
"scraper": scraper_thread.is_alive() if 'scraper_thread' in globals() else False,
"validator_new": validator_new_thread.is_alive() if 'validator_new_thread' in globals() else False,
"validator_existing": validator_existing_thread.is_alive() if 'validator_existing_thread' in globals() else False,
"hf_sync": hf_sync_thread.is_alive() if 'hf_sync_thread' in globals() else False,
"fastapi": True
}
# --- BACKGROUND THREAD REFERENCES ---
scraper_thread = None
validator_new_thread = None
validator_existing_thread = None
hf_sync_thread = None
def hf_sync_loop():
while True:
try:
time.sleep(300) # 5 minutes
sync_to_hf()
hf_sync_loop.last_sync = time.strftime("%Y-%m-%dT%H:%M:%S")
except Exception as e:
logging.error(f"HF sync loop error: {e}")
# --- STARTUP SEQUENCE ---
@asynccontextmanager
async def lifespan(app: FastAPI):
global scraper_thread, validator_new_thread, validator_existing_thread, hf_sync_thread
restore_from_hf()
scraper_thread = threading.Thread(target=scraper_loop, daemon=True, name="Scraper")
validator_new_thread = threading.Thread(target=validator_new_loop, daemon=True, name="ValidatorNew")
validator_existing_thread = threading.Thread(target=validator_existing_loop, daemon=True, name="ValidatorExisting")
hf_sync_thread = threading.Thread(target=hf_sync_loop, daemon=True, name="HFSync")
scraper_thread.start()
validator_new_thread.start()
validator_existing_thread.start()
hf_sync_thread.start()
logging.info("All background services started.")
yield
app = FastAPI(lifespan=lifespan)
if __name__ == "__main__":
uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=False)