File size: 11,483 Bytes
718c4ae
83dd3e1
 
 
 
718c4ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e49379
 
 
718c4ae
4e49379
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
718c4ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e49379
761b1f2
4e49379
 
 
 
 
 
 
761b1f2
4e49379
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
718c4ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# app.py
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from fastapi import FastAPI, UploadFile, Form, File
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import torch
from PIL import Image
import io
from model import AuctionAuthenticityModel
from torchvision import transforms
import numpy as np


app = FastAPI(
    title="Antique Auction Authenticity API",
    description="AI model do oceny autentyczności aukcji antyków",
    version="1.0.0"
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

DEVICE = torch.device('cpu')
MODEL_PATH = '../weights/auction_model.pt'

model = None
transform = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize(
        mean=[0.485, 0.456, 0.406],
        std=[0.229, 0.224, 0.225]
    )
])

@app.on_event("startup")
async def load_model():
    global model
    print("🚀 Ładowanie modelu...")
    model = AuctionAuthenticityModel(num_classes=3, device=DEVICE).to(DEVICE)
    if os.path.exists(MODEL_PATH):
        model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
        print(f"✓ Model załadowany z {MODEL_PATH}")
    else:
        print("⚠️  Brak wag - pretrained")
    model.eval()
    print("✓ Model gotowy")

@app.post("/predict")
async def predict(
    image: UploadFile = File(...),
    title: str = Form(...),
    description: str = Form(...)
):
    try:
        img_data = await image.read()
        img = Image.open(io.BytesIO(img_data)).convert('RGB')
        img_tensor = transform(img).unsqueeze(0).to(DEVICE)
        text = f"{title} {description}"
        
        with torch.no_grad():
            logits = model(img_tensor, [text])
            probs = torch.softmax(logits, dim=1)[0]
        
        orig_prob = float(probs[0])  # label 0
        scam_prob = float(probs[1])  # label 1
        repl_prob = float(probs[2])  # label 2
        
        probs_dict = {
            "ORIGINAL": orig_prob,
            "SCAM": scam_prob,
            "REPLICA": repl_prob
        }
        best_label = max(probs_dict, key=probs_dict.get)
        best_prob = probs_dict[best_label]
        
        # Niepewny: max prob < 0.6 LUB margin < 0.15
        sorted_probs = sorted(probs_dict.values(), reverse=True)
        margin = sorted_probs[0] - sorted_probs[1]
        
        if best_prob < 0.6 or margin < 0.15:
            verdict = "UNCERTAIN"
        else:
            verdict = best_label
        
        return JSONResponse({
            "status": "success",
            "original_probability": round(orig_prob, 3),
            "scam_probability": round(scam_prob, 3),
            "replica_probability": round(repl_prob, 3),
            "verdict": verdict,
            "confidence": round(best_prob, 3),
            "margin": round(margin, 3),
            "message": f"Aukcja ma {best_prob*100:.1f}% pewności: {verdict}"
        })
    except Exception as e:
        return JSONResponse(
            {"status": "error", "error": str(e)},
            status_code=400
        )

@app.post("/predict_ensemble")
async def predict_ensemble(
    images: list[UploadFile] = File(...),  # wiele plików!
    title: str = Form(...),
    description: str = Form(...)
):
    predictions = []
    
    for i, img_file in enumerate(images):
        img_data = await img_file.read()
        img = Image.open(io.BytesIO(img_data)).convert('RGB')
        img_tensor = transform(img).unsqueeze(0).to(DEVICE)
        text = f"{title} {description}"
        
        with torch.no_grad():
            logits = model(img_tensor, [text])
            probs = torch.softmax(logits, dim=1)[0].cpu().numpy()
            predictions.append(probs)
    
    # Średnia z wszystkich zdjęć
    avg_probs = np.mean(predictions, axis=0)
    
    orig_prob = float(avg_probs[0])
    scam_prob = float(avg_probs[1])
    repl_prob = float(avg_probs[2])
    
    probs_dict = {"ORIGINAL": orig_prob, "SCAM": scam_prob, "REPLICA": repl_prob}
    best_label = max(probs_dict, key=probs_dict.get)
    best_prob = probs_dict[best_label]
    
    sorted_probs = sorted(probs_dict.values(), reverse=True)
    margin = sorted_probs[0] - sorted_probs[1]
    
    if best_prob < 0.6 or margin < 0.15:
        verdict = "UNCERTAIN"
    else:
        verdict = best_label
    
    return JSONResponse({
        "status": "success",
        "image_count": len(images),
        "original_probability": round(orig_prob, 3),
        "scam_probability": round(scam_prob, 3),
        "replica_probability": round(repl_prob, 3),
        "verdict": verdict,
        "confidence": round(best_prob, 3),
        "margin": round(margin, 3),
        "per_image_probs": [p.tolist() for p in predictions]  # dla debug
    })

@app.post("/validate_url")
async def validate_url(
    url: str = Form(...),
    max_images: int = Form(3)
):
    try:
        import numpy as np
        from io import BytesIO
        import requests
        
        max_images = max(1, min(max_images, 10))
        
        # 1. Scraper
        if "allegro.pl" in url:
            from web_scraper_allegro import scrape_allegro_offer
            auction = scrape_allegro_offer(url)
        elif "olx.pl" in url:
            from web_scraper_olx import scrape_olx_offer
            auction = scrape_olx_offer(url)
        elif "ebay." in url:
            from web_scraper_ebay import scrape_ebay_offer
            auction = scrape_ebay_offer(url)
        else:
            return JSONResponse({"error": "Unsupported platform"}, status_code=400)
        
        print(f"🔍 DEBUG: Auction data: {auction}")
        print(f"🔍 DEBUG: Image URLs: {auction.get('image_urls', [])}")
        
        if not auction.get("image_urls"):
            # Try fetching page HTML as an additional debug aid (may differ from JS-rendered content)
            try:
                headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
                page_resp = requests.get(url, headers=headers, timeout=10)
                page_preview = page_resp.text[:2000]
                page_status = page_resp.status_code
            except Exception as e:
                page_preview = None
                page_status = str(e)

            return JSONResponse({
                "error": "No images found",
                "debug": {
                    "url": url,
                    "auction_data": auction,
                    "has_image_urls_key": "image_urls" in auction,
                    "image_urls_value": auction.get("image_urls"),
                    "page_status": page_status,
                    "page_html_preview": page_preview
                }
            }, status_code=400)
        
        # 2. Ile zdjęć
        total_available = len(auction["image_urls"])
        images_to_use = min(max_images, total_available)
        
        # 3. Model BEZ HTTP (bezpośrednio!)
        img_probs = []
        text = auction["title"] + " " + auction["description"]
        
        for i, img_url in enumerate(auction["image_urls"][:images_to_use]):
            print(f"📸 {i+1}/{images_to_use}")
            
            img_resp = requests.get(img_url, timeout=15)
            img_resp.raise_for_status()
            
            img = Image.open(BytesIO(img_resp.content)).convert('RGB')
            img_tensor = transform(img).unsqueeze(0).to(DEVICE)
            
            with torch.no_grad():
                logits = model(img_tensor, [text])
                probs = torch.softmax(logits, dim=1)[0]
                
            img_probs.append({
                "original_probability": float(probs[0]),
                "scam_probability": float(probs[1]),
                "replica_probability": float(probs[2])
            })
        
        # 4. Średnia
        avg_orig = np.mean([p["original_probability"] for p in img_probs])
        avg_scam = np.mean([p["scam_probability"] for p in img_probs])
        avg_repl = np.mean([p["replica_probability"] for p in img_probs])
        
        probs_dict = {"ORIGINAL": avg_orig, "SCAM": avg_scam, "REPLICA": avg_repl}
        best_label = max(probs_dict, key=probs_dict.get)
        best_prob = float(probs_dict[best_label])
        
        sorted_probs = sorted(probs_dict.values(), reverse=True)
        margin = float(sorted_probs[0] - sorted_probs[1])
        
        if best_prob < 0.6 or margin < 0.15:
            verdict = "UNCERTAIN"
        else:
            verdict = best_label
        
        return {
            "status": "success",
            "url": url,
            "title": auction["title"][:100] + "...",
            "platform": auction["platform"],
            "total_images_available": total_available,
            "requested_max_images": max_images,
            "image_count_used": images_to_use,
            "original_probability": round(avg_orig, 3),
            "scam_probability": round(avg_scam, 3),
            "replica_probability": round(avg_repl, 3),
            "verdict": verdict,
            "confidence": round(best_prob, 3),
            "margin": round(margin, 3)
        }
    
    except Exception as e:
        import traceback
        return JSONResponse({
            "status": "error", 
            "error": str(e),
            "traceback": traceback.format_exc()
        }, status_code=500)


@app.post("/debug_scrape")
async def debug_scrape(url: str = Form(...), headless: bool = Form(True)):
    """Run scraper for a URL and return the raw auction dict and a small HTML preview.
    This endpoint is for debugging only."""
    try:
        import requests
        # Choose scraper
        if "allegro.pl" in url:
            from web_scraper_allegro import scrape_allegro_offer
            auction = scrape_allegro_offer(url, headless=headless)
        elif "olx.pl" in url:
            from web_scraper_olx import scrape_olx_offer
            auction = scrape_olx_offer(url)
        elif "ebay." in url:
            from web_scraper_ebay import scrape_ebay_offer
            auction = scrape_ebay_offer(url)
        else:
            return JSONResponse({"error": "Unsupported platform"}, status_code=400)

        # Try a simple GET to capture non-JS HTML
        try:
            headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
            page_resp = requests.get(url, headers=headers, timeout=10)
            page_preview = page_resp.text[:2000]
            page_status = page_resp.status_code
        except Exception as e:
            page_preview = None
            page_status = str(e)

        return JSONResponse({
            "status": "ok",
            "auction": auction,
            "page_status": page_status,
            "page_html_preview": page_preview
        })

    except Exception as e:
        import traceback
        return JSONResponse({"status": "error", "error": str(e), "traceback": traceback.format_exc()}, status_code=500)


@app.get("/health")
def health():
    return {"status": "ok", "message": "API running"}

@app.get("/")
def root():
    return {
        "name": "Antique Auction Authenticity API",
        "version": "1.0.0",
        "endpoints": {
            "POST /predict": "Oceń aukcję",
            "GET /health": "Health check"
        }
    }

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host='0.0.0.0', port=7860)