Spaces:
Paused
Paused
Download main.py from robservice/mio_vinted_api: direct link, hf CLI and curl.
- Browser
- Download file 8.15 kB
-
https://huggingface.co/spaces/robservice/mio_vinted_api/resolve/main/main.py
- Command line
-
hf download hf://spaces/robservice/mio_vinted_api/main.py
-
curl -L -o main.py https://huggingface.co/spaces/robservice/mio_vinted_api/resolve/main/main.py
8.15 kB
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from vinted_scraper import VintedScraper | |
| import requests | |
| from bs4 import BeautifulSoup | |
| import re | |
| import json | |
| app = FastAPI(title="Collector Price Engine API") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| HEADERS = { | |
| "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", | |
| "Accept-Language": "it-IT,it;q=0.9", | |
| "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", | |
| } | |
| def pulisci_prezzo(testo_prezzo): | |
| try: | |
| testo = testo_prezzo.upper().replace("EUR", "").replace("€", "").replace(" ", "") | |
| testo = testo.replace(".", "").replace(",", ".").strip() | |
| if "A" in testo: | |
| testo = testo.split("A")[0] | |
| numeri = re.findall(r"\d+\.\d+|\d+", testo) | |
| return float(numeri[0]) if numeri else None | |
| except: | |
| return None | |
| def scrapa_ebay(query_url: str, headers: dict, venduti: bool = False) -> list: | |
| """Scraping eBay.it — layout aggiornato (s-card / s-item fallback).""" | |
| prezzi = [] | |
| try: | |
| base = f"https://www.ebay.it/sch/i.html?_nkw={query_url}&_sacat=0" | |
| if venduti: | |
| base += "&LH_Sold=1&LH_Complete=1" | |
| res = requests.get(base, headers=headers, timeout=10) | |
| if res.status_code != 200: | |
| return prezzi | |
| soup = BeautifulSoup(res.text, 'html.parser') | |
| # Layout nuovo: <li class="s-card ..."> con prezzo in span.s-card__price | |
| # Layout vecchio: <li class="s-item ..."> con prezzo in span.s-item__price | |
| items = soup.find_all('li', class_=re.compile(r's-card|s-item')) | |
| for item in items: | |
| titolo = item.find(['div', 'span'], class_=re.compile(r's-card__title|s-item__title')) | |
| prezzo_elem = item.find('span', class_=re.compile(r's-card__price|s-item__price')) | |
| if not prezzo_elem: | |
| continue | |
| if titolo and ("Shop on eBay" in titolo.text or "Annunci sponsorizzati" in titolo.text): | |
| continue | |
| p = pulisci_prezzo(prezzo_elem.text) | |
| if p and p > 0: | |
| prezzi.append(p) | |
| except: | |
| pass | |
| return prezzi | |
| def scrapa_wallapop(query_url: str, headers: dict) -> list: | |
| """Scraping Wallapop tramite API pubblica search (più stabile dello scraping HTML/SPA).""" | |
| prezzi = [] | |
| try: | |
| url_api = ( | |
| "https://api.wallapop.com/api/v3/general/search" | |
| f"?keywords={query_url}&latitude=41.9028&longitude=12.4964&order_by=price_low_to_high" | |
| ) | |
| res = requests.get(url_api, headers={**headers, "X-DeviceOS": "0"}, timeout=10) | |
| if res.status_code == 200: | |
| data = res.json() | |
| for item in data.get("search_objects", [])[:15]: | |
| price = item.get("price") | |
| if price is not None: | |
| p = pulisci_prezzo(str(price)) | |
| if p and p > 0: | |
| prezzi.append(p) | |
| if prezzi: | |
| return prezzi[:10] | |
| except: | |
| pass | |
| # Fallback: pagina HTML (SPA) — cerca __NEXT_DATA__ e campi prezzo annidati | |
| try: | |
| url_w = f"https://it.wallapop.com/app/search?keywords={query_url}" | |
| res_w = requests.get(url_w, headers=headers, timeout=10) | |
| if res_w.status_code != 200: | |
| return prezzi | |
| soup = BeautifulSoup(res_w.text, 'html.parser') | |
| scripts = soup.find_all('script', type='application/json') | |
| for script in scripts: | |
| try: | |
| data = json.loads(script.string or '') | |
| def extract_prices(obj): | |
| if isinstance(obj, dict): | |
| for key in ('price', 'amount', 'cents', 'price_eur'): | |
| if key in obj and isinstance(obj[key], (int, float, str)): | |
| p = pulisci_prezzo(str(obj[key])) | |
| if p and p > 0: | |
| prezzi.append(p) | |
| for v in obj.values(): | |
| extract_prices(v) | |
| elif isinstance(obj, list): | |
| for el in obj: | |
| extract_prices(el) | |
| extract_prices(data) | |
| if prezzi: | |
| break | |
| except: | |
| pass | |
| if not prezzi: | |
| for sel in ['span[class*="price"]', 'span[class*="Price"]', 'b[class*="price"]']: | |
| cards = soup.select(sel) | |
| for card in cards[:10]: | |
| p = pulisci_prezzo(card.text) | |
| if p and p > 0: | |
| prezzi.append(p) | |
| if prezzi: | |
| break | |
| except: | |
| pass | |
| return prezzi[:10] | |
| def home(): | |
| return {"status": "Motore Prezzi Collezionismo Attivo"} | |
| def valuta_collezione(q: str): | |
| if not q: | |
| raise HTTPException(status_code=400, detail="Inserisci l'oggetto da cercare") | |
| headers = HEADERS | |
| prezzi_vinted = [] | |
| prezzi_ebay_attivi = [] | |
| prezzi_ebay_venduti = [] | |
| prezzi_wallapop = [] | |
| query_url = requests.utils.quote(q, safe='') | |
| # 1. VINTED (Attivi) | |
| try: | |
| scraper = VintedScraper("https://vinted.it") | |
| items_vinted = scraper.search({"search_text": q}) | |
| for item in items_vinted[:10]: | |
| prezzi_vinted.append(float(item.price)) | |
| except: | |
| pass | |
| # 2. EBAY Attivi | |
| prezzi_ebay_attivi = scrapa_ebay(query_url, headers, venduti=False) | |
| # 3. EBAY Venduti | |
| prezzi_ebay_venduti = scrapa_ebay(query_url, headers, venduti=True) | |
| # 4. WALLAPOP | |
| prezzi_wallapop = scrapa_wallapop(query_url, headers) | |
| # CALCOLO MEDIE | |
| tutti_attivi = prezzi_vinted + prezzi_ebay_attivi + prezzi_wallapop | |
| media_attivi = round(sum(tutti_attivi) / len(tutti_attivi), 2) if tutti_attivi else 0 | |
| media_venduti = round(sum(prezzi_ebay_venduti) / len(prezzi_ebay_venduti), 2) if prezzi_ebay_venduti else 0 | |
| prezzo_consigliato = media_venduti if media_venduti > 0 else media_attivi | |
| return { | |
| "oggetto_cercato": q, | |
| "medie_prezzo_calcolate": { | |
| "media_mercato_attuale_attivi": f"{media_attivi} €", | |
| "media_storico_venduto_reale": f"{media_venduti} €", | |
| "prezzo_consigliato_consigliato": f"{prezzo_consigliato} €" | |
| }, | |
| "campionamento_dati": { | |
| "annunci_vinted": len(prezzi_vinted), | |
| "annunci_ebay_attivi": len(prezzi_ebay_attivi), | |
| "annunci_ebay_venduti": len(prezzi_ebay_venduti), | |
| "annunci_wallapop": len(prezzi_wallapop) | |
| } | |
| } | |
| def debug_raw(q: str, source: str = "ebay"): | |
| """Endpoint diagnostico: mostra HTML/JSON grezzo ricevuto dalla fonte. | |
| source = ebay | ebay_venduti | wallapop | wallapop_api | |
| """ | |
| query_url = requests.utils.quote(q, safe='') | |
| if source == "ebay": | |
| url = f"https://www.ebay.it/sch/i.html?_nkw={query_url}&_sacat=0" | |
| elif source == "ebay_venduti": | |
| url = f"https://www.ebay.it/sch/i.html?_nkw={query_url}&_sacat=0&LH_Sold=1&LH_Complete=1" | |
| elif source == "wallapop_api": | |
| url = ( | |
| "https://api.wallapop.com/api/v3/general/search" | |
| f"?keywords={query_url}&latitude=41.9028&longitude=12.4964&order_by=price_low_to_high" | |
| ) | |
| elif source == "wallapop": | |
| url = f"https://it.wallapop.com/app/search?keywords={query_url}" | |
| else: | |
| raise HTTPException(status_code=400, detail="source non valido") | |
| try: | |
| res = requests.get(url, headers={**HEADERS, "X-DeviceOS": "0"}, timeout=10) | |
| body = res.text | |
| return { | |
| "url": url, | |
| "status_code": res.status_code, | |
| "content_length": len(body), | |
| "body_preview": body[:5000], | |
| } | |
| except Exception as e: | |
| return {"url": url, "error": str(e)} |