Spaces:
Sleeping
Sleeping
Upload app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"""app.py β Fenix Inventory Tracker Β· FastAPI backendServes the React frontend (index.html) and exposes /api/scrape."""from __future__ import annotations
import osimport timeimport randomfrom pathlib import Path
from fastapi import FastAPI, HTTPExceptionfrom fastapi.responses import FileResponse, JSONResponsefrom fastapi.staticfiles import StaticFilesfrom pydantic import BaseModel
from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeout
# βββ Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββAPI_KEYWORD = "v3?app_id=730"CNY_TO_USD = 0.14USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",]
# βββ FastAPI app ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββapp = FastAPI(title="Fenix Inventory API")
# Serve static assets (phoenix image, etc.) from /staticif Path("static").exists(): app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/")def serve_index(): return FileResponse("index.html")
@app.get("/Fenix_red_and_orange.png")def serve_logo(): return FileResponse("Fenix_red_and_orange.png", media_type="image/png")
# βββ Scraping helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _cny_usd(val) -> float: return float(val) * CNY_TO_USD if val else 0.0
def _tag(tags: list[str], prefix: str, strip: str = "") -> str: for t in tags: if t.startswith(prefix + "#"): raw = t.split("#", 1)[-1] return raw.replace(strip, "").replace("_", " ").title() return "Unknown"
def _parse(api_data: dict) -> list[dict]: items_list, classinfos = [], {} block = api_data.get("data", api_data) if isinstance(block, dict): inv = block.get("inventory", {}) if isinstance(inv, dict): items_list = inv.get("assets", []) classinfos = inv.get("classinfos", {}) else: items_list = block.get("inventory", block.get("list", [])) classinfos = block.get("classinfos", {}) elif isinstance(block, list): items_list = block classinfos = api_data.get("classinfos", {})
out = [] for item in items_list: aid = str(item.get("assetId", "")) if not aid or aid == "None": continue info = classinfos.get(str(item.get("classinfoKey", "")), {}) tags = info.get("tags", []) name = info.get("marketHashName") or info.get("hashName") or f"Unknown ({item.get('classinfoKey','?')})" price = _cny_usd(item.get("evaluatePrice")) rarity = _tag(tags, "Rarity", "Rarity_") or "Normal" quality = _tag(tags, "Quality", "Quality_") or "Normal" wtype = _tag(tags, "Type", "Type_") itype = "StatTrak" if "StatTrakβ’" in name else "Souvenir" if "Souvenir" in name else "Normal" is_knife = "Knife" in wtype or any(k in name for k in ("β
","Karambit","Butterfly","M9 Bayonet")) is_glove = "Glove" in wtype or "Gloves" in name out.append({"assetId":aid,"name":name,"price":price,"rarity":rarity, "quality":quality,"type":itype,"weaponType":wtype, "isKnife":is_knife,"isGlove":is_glove}) return out
def _fetch(url: str) -> dict | None: for attempt in range(3): try: with sync_playwright() as p: browser = p.chromium.launch(headless=True, args=[ "--disable-blink-features=AutomationControlled", "--disable-dev-shm-usage","--no-sandbox", ]) ctx = browser.new_context(user_agent=random.choice(USER_AGENTS), viewport={"width":1920,"height":1080},locale="en-US") page = ctx.new_page() page.add_init_script(""" Object.defineProperty(navigator,'webdriver',{get:()=>undefined}); Object.defineProperty(navigator,'languages',{get:()=>['en-US','en']}); Object.defineProperty(navigator,'plugins',{get:()=>[1,2,3,4]}); """) page.route("**/*.{png,jpg,jpeg,gif,svg,webp,woff,woff2}", lambda r: r.abort())
captured = None def on_response(resp): nonlocal captured if API_KEYWORD in resp.url and resp.request.method != "OPTIONS": try: if resp.status == 200: captured = resp.json() except Exception: pass page.on("response", on_response)
page.goto(url, wait_until="domcontentloaded", timeout=60_000) page.mouse.move(random.randint(200,900), random.randint(200,700)) page.evaluate("window.scrollTo(0,document.body.scrollHeight)")
for _ in range(30): if captured: break page.wait_for_timeout(500) browser.close() if captured: return captured raise RuntimeError("API response not received") except PlaywrightTimeout: pass except Exception as e: print(f"Attempt {attempt+1} error: {e}") time.sleep(2) return None
# βββ API endpoint βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class ScrapeRequest(BaseModel): steam_url: str
@app.post("/api/scrape")def scrape(req: ScrapeRequest): if "steamcommunity.com" not in req.steam_url: raise HTTPException(400, "Invalid Steam URL") steamdt_url = f"https://www.steamdt.com/en/inventory/inventory?search={req.steam_url}" raw = _fetch(steamdt_url) if not raw: raise HTTPException(502, "Failed to fetch inventory data from SteamDT") items = _parse(raw) if not items: raise HTTPException(404, "No items found in inventory") return JSONResponse({"items": items, "count": len(items)})app.pyAdded+156