Paradigmsniff's picture
Update app.py
ae359a3 verified
Raw History Blame Contribute Delete
6.24 kB
import gradio as gr
from transformers import CLIPProcessor, CLIPModel
from PIL import Image
import torch
import faiss
import pickle
import requests
import json
from datetime import datetime
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
index = faiss.read_index("partvision_index.faiss")
skus = pickle.load(open("partvision_sku_mapping.pkl", "rb"))
CWR_ID = "MPB_NDI3OTk5NDI3OTk5MTI4"
CWR_URL = "https://cwrdistribution.com/feeds/productdownload.php"
cart = {}
def get_cwr_data(skus_list):
if not skus_list:
return {}
skus_str = ",".join([str(s) for s in skus_list])
url = f"{CWR_URL}?id={CWR_ID}&version=3&format=json&fields=sku,price,qty,brand,name&skus={skus_str}"
try:
r = requests.get(url, timeout=12)
if r.status_code != 200:
return {}
data = r.json()
result = {}
for item in data:
if isinstance(item, dict) and "sku" in item:
sku = item["sku"]
price_str = item.get("price", "0")
try:
price = f"${float(price_str):.2f}"
except:
price = "N/A"
result[sku] = {
"price": price,
"qty": item.get("qty", "?"),
"brand": item.get("brand", "β€”"),
"name": item.get("name", "β€”")
}
return result
except Exception as e:
print(f"CWR error: {e}")
return {}
def identify(image):
if image is None:
return [], render_cart()
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
query = model.get_image_features(**inputs)
query /= query.norm(dim=-1, keepdim=True)
D, I = index.search(query.cpu().numpy(), 10)
top_skus = []
for i in I[0]:
if i == -1 or i >= len(skus):
continue
raw = skus[i]
top_skus.append(str(raw) if not isinstance(raw, dict) else raw.get("sku", str(i)))
data = get_cwr_data(top_skus)
rows = []
for rank, sku in enumerate(top_skus, 1):
info = data.get(sku, {"brand": "β€”", "name": "β€”", "price": "N/A", "qty": "?"})
conf = round(float(1 - D[0][rank-1]), 3) if rank <= len(D[0]) else 0
rows.append([
f"{conf:.1%}",
sku,
info["brand"],
info["name"],
info["price"],
info["qty"],
f"<button onclick=\"addToCart('{sku}')\" style='background:#ff3366;color:white;border:none;padding:8px 16px;border-radius:6px;cursor:pointer;font-weight:bold'>Add to Cart</button>"
])
return rows, render_cart()
def add_to_cart(sku):
global cart
data = get_cwr_data([sku])
if sku in data:
if sku not in cart:
cart[sku] = data[sku]
cart[sku]["qty"] = 0
cart[sku]["qty"] += 1
return render_cart()
def render_cart():
if not cart:
return "<div style='text-align:center;padding:3rem;color:#94a3b8;font-size:1.2rem'>Cart empty β€” add parts above</div>"
total = 0
rows = ""
for sku, item in cart.items():
price = float(str(item.get("price", "0")).replace("$", "")) if "$" in str(item.get("price", "")) else 0
subtotal = price * item["qty"]
total += subtotal
rows += f"""
<tr>
<td style='padding:12px'>{item["qty"]}Γ—</td>
<td style='padding:12px'>{sku}</td>
<td style='padding:12px'>{item.get("brand", "β€”")}</td>
<td style='padding:12px'>{item.get("price", "N/A")}</td>
<td style='padding:12px'>${subtotal:.2f}</td>
</tr>
"""
return f"""
<div style='background:#1e293b;padding:2rem;border-radius:16px;margin:2rem 0'>
<h3 style='margin:0 0 1rem 0;color:#ff3366;text-align:center'>πŸ›’ Cart β€” ${total:.2f}</h3>
<table style='width:100%;border-collapse:collapse'>
<tr style='background:#ff3366;color:white'><th>Qty</th><th>SKU</th><th>Brand</th><th>Price</th><th>Subtotal</th></tr>
{rows}
</table>
<div style='text-align:center;margin-top:1.5rem'>
<button style='background:#10b981;color:white;padding:1rem 2rem;border:none;border-radius:12px;font-size:1.1rem;cursor:pointer' onclick="window.location.href='/file=PicSea_BOM.csv'">Export BOM + Buy Links</button>
</div>
</div>
"""
def export_bom():
if not cart:
return None
lines = ["Qty,SKU,Brand,Price,Link"]
for sku, item in cart.items():
link = f"https://www.westmarine.com/search?Ntt={sku}&tag=picsea20"
lines.append(f"{item.get('qty',1)},{sku},{item.get('brand','')},{item.get('price','')},{link}")
csv = "\n".join(lines)
return gr.File(value=csv.encode(), file_name=f"PicSea_BOM_{datetime.now():%Y%m%d_%H%M}.csv")
with gr.Blocks() as app:
gr.HTML("""
<style>
body { background: linear-gradient(135deg, #0f172a, #1e293b); color: white; font-family: system-ui; }
h1 { text-align: center; color: #ff3366; font-size: 3rem; margin: 2rem 0; }
table { background: #1e293b; border-radius: 16px; overflow: hidden; }
th { background: #ff3366; padding: 1.5rem; }
td { padding: 1.2rem; }
button { background: #ff3366; color: white; border: none; padding: 0.8rem 1.6rem; border-radius: 8px; font-weight: bold; cursor: pointer; }
</style>
<h1>PicSea</h1>
<p style="text-align:center;font-size:1.8rem;color:#94a3b8">Live CWR pricing Β· Real cart Β· Real money</p>
""")
img = gr.Image(type="pil", label="Upload part photo", height=600)
results = gr.Dataframe(headers=["Confidence", "SKU", "Brand", "Name", "Price", "Stock", ""])
cart_display = gr.HTML(render_cart())
img.change(identify, img, [results, cart_display])
gr.Button("Export BOM + Affiliate Links", variant="primary").click(export_bom, outputs=gr.File())
gr.HTML("""
<script>
function addToCart(sku) {
fetch('/api/predict', {method: 'POST', body: JSON.stringify({data: [sku]})})
.then(() => location.reload());
}
</script>
""")
app.launch()