from __future__ import annotations import csv import html import tempfile from typing import Any, Dict, List, Optional, Tuple import gradio as gr from tool import ( CITIES, DEFAULT_CATEGORY_URL, DEFAULT_PRODUCT_URL, MAX_PAGES, SCRAPE_DO_SIGNUP_URL, ScrapeDoBlinkitTool, ) # ZeroGPU hardware refuses to keep a Space alive unless it finds at least one # @spaces.GPU function at startup. This app is pure HTTP and never touches a GPU, # so the probe below exists only to satisfy that check. It is never called. try: import spaces @spaces.GPU(duration=1) def _zerogpu_probe() -> str: return "ok" except ImportError: pass NO_TOKEN_MD = ( "### Paste your Scrape.do API token above\n\n" f"No token yet? [Create a free account]({SCRAPE_DO_SIGNUP_URL}) — " "1,000 free credits a month, no credit card. Every Blinkit request costs 10 credits." ) CUSTOM = "Custom coordinates" # --------------------------------------------------------------------- helpers def _esc(value: Any) -> str: return html.escape("" if value is None else str(value), quote=True) def _safe_link(url: Any) -> str: url = str(url or "") return url if url.startswith(("http://", "https://")) else "" def _num(value: Any) -> Optional[float]: if isinstance(value, bool): return None try: return float(value) except (TypeError, ValueError): return None def _inr(value: Any) -> str: number = _num(value) if number is None: return "" return f"₹{number:,.0f}" if number == int(number) else f"₹{number:,.2f}" def _fmt_int(value: Any) -> str: number = _num(value) return f"{int(number):,}" if number is not None else _esc(value) def _tool_or_none(token: str) -> Optional[ScrapeDoBlinkitTool]: if not token or not token.strip(): return None return ScrapeDoBlinkitTool(api_token=token.strip()) def _location(city: str, coords: str) -> str: return (coords or "").strip() if city == CUSTOM else city def _write_csv(rows: List[Dict[str, Any]], prefix: str) -> Optional[str]: if not rows: return None fieldnames: List[str] = [] for row in rows: for key in row: if key not in fieldnames: fieldnames.append(key) handle = tempfile.NamedTemporaryFile( mode="w", suffix=".csv", prefix=f"{prefix}-", delete=False, newline="", encoding="utf-8-sig", ) writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for row in rows: writer.writerow({key: row.get(key, "") for key in fieldnames}) handle.close() return handle.name def _error_md(data: Dict[str, Any]) -> str: out = f"**That didn't go through.**\n\n{data.get('errorMessage') or 'Unknown error'}" if data.get("hint"): out += f"\n\n{data['hint']}" return out def _stars(rating: Any, count: Any) -> str: value = _num(rating) if not value: return '
No ratings yet
' count_html = f' ({_fmt_int(count)})' if count not in (None, "") else "" return f'
★ {value:.1f}{count_html}
' def _stock(in_stock: Any, units: Any) -> str: if not in_stock: return 'Out of stock' n = _num(units) label = "50+ in stock" if n is not None and n >= 50 else (f"{int(n)} in stock" if n is not None else "In stock") return f'{label}' BOLT_SVG = ( '' ) # ---------------------------------------------------------- category results def render_category(data: Dict[str, Any]) -> str: cards: List[str] = [] for item in data.get("products") or []: link = _safe_link(item.get("url")) image = _safe_link(item.get("image")) img_html = ( f'" if image else '
' ) name = _esc(item.get("name")) title = ( f'{name}' if link else f'{name}' ) price, mrp = _num(item.get("price_inr")), _num(item.get("mrp_inr")) discount = item.get("discount_pct") or 0 price_html = ( f'
{_esc(_inr(price))}' + (f' {_esc(_inr(mrp))}' if mrp and price is not None and mrp > price else "") + "
" if price is not None else '
No price
' ) cards.append( f'
' + (f'{_esc(discount)}% OFF' if discount else "") + f"{img_html}" f'
{_esc(item.get("pack_size"))}
' f"{title}" f'
{_esc(item.get("brand"))}
' f"{price_html}" f"{_stars(item.get('rating'), item.get('rating_count'))}" f'
{_stock(item.get("in_stock"), item.get("inventory"))}
' "
" ) if not cards: cards.append('
No products came back for this category.
') banner = ( f'
Prices and stock from Blinkit store {_esc(data.get("store_id"))}, ' f'the dark store serving {_esc(data.get("location"))} ({_esc(data.get("latitude"))}, {_esc(data.get("longitude"))})
' ) return f'
{banner}
{"".join(cards)}
' TABLE_HEADERS = ["Product", "Brand", "Pack", "Price ₹", "MRP ₹", "Off %", "In stock", "Units", "Rating", "Ratings"] # ------------------------------------------------------------- product page def render_product(data: Dict[str, Any]) -> str: p = data.get("product") or {} images = [src for src in p.get("images") or [] if _safe_link(src)] main = ( f'" if images else "" ) thumbs = "".join( f'" for src in images[1:6] ) price, mrp = _num(p.get("price_inr")), _num(p.get("mrp_inr")) price_html = ( f'
{_esc(_inr(price))}' + (f' MRP {_esc(_inr(mrp))}' if mrp and price is not None and mrp > price else "") + (f' {_esc(p.get("discount_pct"))}% OFF' if p.get("discount_pct") else "") + "
" if price is not None else '
Not sold at this location right now
' ) facts = [ ("Stock", "In stock" if p.get("in_stock") else "Out of stock"), ("Units", ("50+" if (_num(p.get("inventory")) or 0) >= 50 else _fmt_int(p.get("inventory"))) if p.get("in_stock") else None), ("Pack size", p.get("pack_size")), ("FSSAI licence", p.get("fssai_license")), ("Shelf life", p.get("shelf_life")), ("Country of origin", p.get("country_of_origin")), ("Store", p.get("store_id")), ] facts_html = "".join( f'
{_esc(k)}
{_esc(v)}
' for k, v in facts if v not in (None, "") ) link = _safe_link(p.get("url")) button = ( f'View on Blinkit' if link else "" ) panels = "" for title, key in (("Ingredients", "ingredients"), ("Manufacturer", "manufacturer"), ("Return policy", "return_policy")): if p.get(key): panels += f'
{title}
{_esc(p[key])}
' return ( '
' f'
{main}
{thumbs}
' '
' f'
{_esc(p.get("brand"))}
' f'
{_esc(p.get("name"))}
' f"{price_html}" f'
{facts_html}
{button}' "
" f"{panels}
" ) # ---------------------------------------------------------------- handlers def _picker(choices: List[Tuple[str, str]]) -> Any: return gr.Dropdown(choices=choices, value=None, visible=bool(choices)) def run_category( token: str, url: str, city: str, coords: str, pages: float ) -> Tuple[str, str, List[List[Any]], Dict[str, Any], Optional[str], Any]: tool = _tool_or_none(token) if tool is None: return NO_TOKEN_MD, "", [], {}, None, _picker([]) if not url or not url.strip(): return "Paste a Blinkit category link.", "", [], {}, None, _picker([]) data = tool.category(url, _location(city, coords), int(pages or 1)) if data.get("status") != "success": return _error_md(data), "", [], data, None, _picker([]) rows = data.get("products") or [] oos = sum(1 for r in rows if not r.get("in_stock")) low = sum(1 for r in rows if r.get("in_stock") and (r.get("inventory") or 0) < 5) on_sale = sum(1 for r in rows if (r.get("discount_pct") or 0) > 0) deepest = max((r.get("discount_pct") or 0 for r in rows), default=0) parts = [f"**{len(rows)}** products", f"**{oos}** out of stock", f"**{low}** with fewer than 5 units", f"**{on_sale}** below MRP"] if deepest: parts.append(f"deepest discount **{deepest}%**") summary = " · ".join(parts) total = data.get("total_count") summary += ( f"\n\nRead {data.get('pages_read')} page(s)" + (f" of a category with {_fmt_int(total)} products at this location" if total else "") + f" · {data.get('credits_used')} credits used" + (" · more pages available" if data.get("has_more") else "") ) table = [ [ (r.get("name") or "")[:80], r.get("brand"), r.get("pack_size"), r.get("price_inr"), r.get("mrp_inr"), r.get("discount_pct"), "yes" if r.get("in_stock") else "no", r.get("inventory"), r.get("rating"), r.get("rating_count"), ] for r in rows ] choices = [ (f"{str(r.get('name') or '')[:60]} {r.get('pack_size') or ''} — {_inr(r.get('price_inr')) or 'no price'}", r["url"]) for r in rows if r.get("url") ] return summary, render_category(data), table, data, _write_csv(rows, "blinkit-category"), _picker(choices) def send_to_product(picked: Optional[str], current: str) -> Tuple[str, str]: if not picked: return current, "" return picked, "Sent. Open the **Product details** tab and press the button." def run_product(token: str, url: str, city: str, coords: str) -> Tuple[str, str, Dict[str, Any], Optional[str]]: tool = _tool_or_none(token) if tool is None: return NO_TOKEN_MD, "", {}, None if not url or not url.strip(): return "Paste a Blinkit product link.", "", {}, None data = tool.product(url, _location(city, coords)) if data.get("status") != "success": return _error_md(data), "", data, None product = dict(data.get("product") or {}) product["images"] = " | ".join(product.get("images") or []) product.pop("attributes", None) attrs = (data.get("product") or {}).get("attributes") or {} note = f"{data.get('credits_used')} credits used · {len(attrs)} attributes in the raw JSON below." return note, render_product(data), data, _write_csv([product], "blinkit-product") # ----------------------------------------------------------------------- UI STYLE = """ """ HERO = f"""

{BOLT_SVG.format(size=28)} Blinkit Scraper

Prices, MRP and units in stock for every product in a Blinkit category, for the dark store that serves your address. Pick a city or enter coordinates: assortment, stock and even the number of products change from store to store. Open any product for its FSSAI licence, shelf life and ingredients.

Blinkit answers scripts with a Cloudflare 403. This Space fetches the pages through Scrape.do with residential proxies in India and follows Blinkit's own listing API page by page.

Get a free API token →
""" CREDIT_NOTE = """
Every request is 10 Scrape.do credits (residential proxies in India). Page 1 of a category holds 30 products; every further page is one call to Blinkit's listing API and holds 15. Three pages (60 products) cost 30 credits, a product page 10. The free 1,000 credits a month cover about 100 requests.
""" FOOTER_MD = f""" --- ### Use it as a smolagents Tool ```python from smolagents import CodeAgent, InferenceClientModel from tool import ScrapeDoBlinkitTool agent = CodeAgent( tools=[ScrapeDoBlinkitTool(api_token="YOUR_SCRAPEDO_TOKEN")], model=InferenceClientModel(), ) agent.run("Which chips are low on stock in Mumbai? {DEFAULT_CATEGORY_URL}") ``` Or set `SCRAPE_DO_API_TOKEN` in the environment and instantiate with no arguments. Prefer plain Python? The same scraper is open source: `pip install blinkit-scraper` ([GitHub](https://github.com/bugrahansss/blinkit-scraper)) · No-code: [Apify actor](https://apify.com/scrapedo/blinkit-scraper) [Scrape.do](https://scrape.do/?utm_source=huggingface&utm_medium=blinkit-scraper) · [Documentation](https://scrape.do/documentation/) · [Sign up free]({SCRAPE_DO_SIGNUP_URL}) """ def build_demo() -> gr.Blocks: with gr.Blocks(title="Blinkit Scraper — Scrape.do") as demo: gr.HTML(STYLE) gr.HTML(HERO) api_token = gr.Textbox( label="Scrape.do API token", placeholder="Paste your token here", type="password", info="Free tier: 1,000 credits a month. 10 credits per Blinkit request.", ) with gr.Row(): city = gr.Dropdown(choices=list(CITIES) + [CUSTOM], value="Gurugram", label="Delivery location", info="Gurugram is Blinkit's own default.") coords = gr.Textbox(label="Custom coordinates (lat, lon)", placeholder="12.9352, 77.6245", info="Used when the location is set to Custom coordinates.") gr.HTML(CREDIT_NOTE) with gr.Tabs(): with gr.Tab("Category listings"): cat_url = gr.Textbox( label="Blinkit category link", value=DEFAULT_CATEGORY_URL, info="Open a category on blinkit.com and copy the link; it contains /cn/ and /cid/.", ) pages = gr.Slider(minimum=1, maximum=MAX_PAGES, step=1, value=2, label="Pages (30 products, then 15 per page; 10 credits each)") cat_btn = gr.Button("Scrape category", variant="primary") cat_summary = gr.Markdown() cat_view = gr.HTML() cat_table = gr.Dataframe(headers=TABLE_HEADERS, wrap=True, label="Products") cat_csv = gr.File(label="Download products as CSV") pick = gr.Dropdown(label="Open one of these products in the Product details tab", choices=[], value=None, visible=False) pick_note = gr.Markdown() with gr.Accordion("Raw JSON response", open=False): cat_json = gr.JSON() with gr.Tab("Product details"): prod_url = gr.Textbox(label="Blinkit product link", value=DEFAULT_PRODUCT_URL, info="A link containing /prn/ and /prid/") prod_btn = gr.Button("Get product details", variant="primary") prod_summary = gr.Markdown() prod_view = gr.HTML() prod_csv = gr.File(label="Download as CSV") with gr.Accordion("Raw JSON response", open=False): prod_json = gr.JSON() cat_inputs = [api_token, cat_url, city, coords, pages] cat_outputs = [cat_summary, cat_view, cat_table, cat_json, cat_csv, pick] cat_btn.click(fn=run_category, inputs=cat_inputs, outputs=cat_outputs) cat_url.submit(fn=run_category, inputs=cat_inputs, outputs=cat_outputs) pick.change(fn=send_to_product, inputs=[pick, prod_url], outputs=[prod_url, pick_note]) prod_inputs = [api_token, prod_url, city, coords] prod_outputs = [prod_summary, prod_view, prod_json, prod_csv] prod_btn.click(fn=run_product, inputs=prod_inputs, outputs=prod_outputs) prod_url.submit(fn=run_product, inputs=prod_inputs, outputs=prod_outputs) gr.Markdown(FOOTER_MD) return demo # Hugging Face Spaces launches the module-level `demo` object rather than # calling launch() itself, so build it at import time. demo = build_demo() def _network_probe() -> None: """Log once at startup whether api.scrape.do is reachable from this Space (a bad token costs nothing).""" import time as _t import requests as _r started = _t.time() try: resp = _r.get("https://api.scrape.do/", params={"token": "probe", "url": "https://blinkit.com/"}, timeout=(10, 30)) print(f"[probe] api.scrape.do HTTP {resp.status_code} in {_t.time() - started:.1f}s", flush=True) except Exception as exc: # noqa: BLE001 print(f"[probe] api.scrape.do unreachable after {_t.time() - started:.1f}s: {exc}", flush=True) if __name__ == "__main__": import threading threading.Thread(target=_network_probe, daemon=True).start() demo.queue(default_concurrency_limit=4).launch(ssr_mode=False)