File size: 11,588 Bytes
e3f5d52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse, FileResponse
from pydantic import BaseModel
from typing import List, Optional, Dict, Any
import uvicorn
import asyncio
import json
import os
from datetime import datetime
import logging

# Import your scrapers
from app3 import PhoneDBScraper, GSMArenaScraperAlternative

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Create FastAPI app
app = FastAPI(
    title="Phone Specifications API",
    description="API for scraping phone specifications from PhoneDB and GSMArena",
    version="1.0.0"
)

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # In production, specify allowed origins
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Mount static files for frontend
if os.path.exists("static"):
    app.mount("/static", StaticFiles(directory="static"), name="static")

# Pydantic models
class PhoneSearchRequest(BaseModel):
    phone_name: str
    source: str = "gsmarena"  # "phonedb" or "gsmarena"

class MultiplePhoneSearchRequest(BaseModel):
    phone_names: List[str]
    source: str = "gsmarena"

class PhoneSpecification(BaseModel):
    name: str
    brand: str
    images: List[str]
    specifications: Dict[str, Any]
    source_url: str

class ApiResponse(BaseModel):
    success: bool
    message: str
    data: Optional[Any] = None
    timestamp: str = datetime.now().isoformat()

# Global scrapers
phonedb_scraper = None
gsmarena_scraper = None

@app.on_event("startup")
async def startup_event():
    """Initialize scrapers on startup"""
    global phonedb_scraper, gsmarena_scraper
    try:
        phonedb_scraper = PhoneDBScraper()
        gsmarena_scraper = GSMArenaScraperAlternative()
        logger.info("Scrapers initialized successfully")
    except Exception as e:
        logger.error(f"Error initializing scrapers: {e}")

# Routes
@app.get("/", response_class=HTMLResponse)
async def read_root():
    """Serve the main HTML page"""
    try:
        with open("templates/index.html", "r", encoding="utf-8") as f:
            return HTMLResponse(content=f.read())
    except FileNotFoundError:
        return HTMLResponse(content="""
        <html>
            <head><title>Phone Specs API</title></head>
            <body>
                <h1>Phone Specifications API</h1>
                <p>API is running! Visit <a href="/docs">/docs</a> for API documentation.</p>
            </body>
        </html>
        """)

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return ApiResponse(
        success=True,
        message="API is healthy",
        data={"status": "running", "scrapers": {"phonedb": phonedb_scraper is not None, "gsmarena": gsmarena_scraper is not None}}
    )

@app.post("/api/search", response_model=ApiResponse)
async def search_phone(request: PhoneSearchRequest):
    """Search for a single phone"""
    try:
        logger.info(f"Searching for phone: {request.phone_name} using {request.source}")
        
        # Choose scraper based on source
        if request.source.lower() == "phonedb" and phonedb_scraper:
            scraper = phonedb_scraper
        elif request.source.lower() == "gsmarena" and gsmarena_scraper:
            scraper = gsmarena_scraper
        else:
            # Default to GSMArena if available
            if gsmarena_scraper:
                scraper = gsmarena_scraper
            elif phonedb_scraper:
                scraper = phonedb_scraper
            else:
                raise HTTPException(status_code=503, detail="No scrapers available")
        
        # Run scraping in background to avoid blocking
        loop = asyncio.get_event_loop()
        result = await loop.run_in_executor(
            None, 
            scraper.scrape_phone_by_name, 
            request.phone_name
        )
        
        if result:
            return ApiResponse(
                success=True,
                message=f"Successfully found specifications for {result['name']}",
                data=result
            )
        else:
            return ApiResponse(
                success=False,
                message=f"No results found for {request.phone_name}",
                data=None
            )
            
    except Exception as e:
        logger.error(f"Error searching for phone {request.phone_name}: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/search/multiple", response_model=ApiResponse)
async def search_multiple_phones(request: MultiplePhoneSearchRequest):
    """Search for multiple phones"""
    try:
        logger.info(f"Searching for {len(request.phone_names)} phones using {request.source}")
        
        # Choose scraper
        if request.source.lower() == "phonedb" and phonedb_scraper:
            scraper = phonedb_scraper
        elif request.source.lower() == "gsmarena" and gsmarena_scraper:
            scraper = gsmarena_scraper
        else:
            if gsmarena_scraper:
                scraper = gsmarena_scraper
            elif phonedb_scraper:
                scraper = phonedb_scraper
            else:
                raise HTTPException(status_code=503, detail="No scrapers available")
        
        # Run scraping in background
        loop = asyncio.get_event_loop()
        results = await loop.run_in_executor(
            None,
            scraper.scrape_multiple_phones,
            request.phone_names
        )
        
        success_count = len(results) if results else 0
        total_count = len(request.phone_names)
        
        return ApiResponse(
            success=success_count > 0,
            message=f"Successfully scraped {success_count}/{total_count} phones",
            data={
                "phones": results,
                "success_count": success_count,
                "total_count": total_count
            }
        )
        
    except Exception as e:
        logger.error(f"Error searching for multiple phones: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/api/sources")
async def get_available_sources():
    """Get available scraping sources"""
    sources = []
    
    if phonedb_scraper:
        sources.append({
            "id": "phonedb",
            "name": "PhoneDB",
            "description": "PhoneDB.net database",
            "available": True
        })
    
    if gsmarena_scraper:
        sources.append({
            "id": "gsmarena", 
            "name": "GSMArena",
            "description": "GSMArena.com database",
            "available": True
        })
    
    return ApiResponse(
        success=True,
        message="Available sources retrieved",
        data=sources
    )

@app.get("/api/export/{phone_name}")
async def export_phone_data(phone_name: str, source: str = "gsmarena"):
    """Export phone data as JSON file"""
    try:
        # Choose scraper
        if source.lower() == "phonedb" and phonedb_scraper:
            scraper = phonedb_scraper
        else:
            scraper = gsmarena_scraper
        
        if not scraper:
            raise HTTPException(status_code=503, detail="Scraper not available")
        
        # Get phone data
        loop = asyncio.get_event_loop()
        result = await loop.run_in_executor(
            None,
            scraper.scrape_phone_by_name,
            phone_name
        )
        
        if not result:
            raise HTTPException(status_code=404, detail="Phone not found")
        
        # Create temporary file
        filename = f"{phone_name.replace(' ', '_')}_specs.json"
        filepath = f"/tmp/{filename}"
        
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(result, f, indent=2, ensure_ascii=False)
        
        return FileResponse(
            filepath,
            media_type='application/json',
            filename=filename
        )
        
    except Exception as e:
        logger.error(f"Error exporting phone data: {e}")
        raise HTTPException(status_code=500, detail=str(e))

# Background tasks for long-running scraping jobs
background_jobs = {}

@app.post("/api/scrape/background")
async def start_background_scraping(request: MultiplePhoneSearchRequest, background_tasks: BackgroundTasks):
    """Start background scraping job for multiple phones"""
    job_id = f"job_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
    
    # Initialize job status
    background_jobs[job_id] = {
        "status": "started",
        "progress": 0,
        "total": len(request.phone_names),
        "results": [],
        "started_at": datetime.now().isoformat()
    }
    
    # Add background task
    background_tasks.add_task(
        run_background_scraping,
        job_id,
        request.phone_names,
        request.source
    )
    
    return ApiResponse(
        success=True,
        message="Background scraping job started",
        data={"job_id": job_id}
    )

@app.get("/api/scrape/status/{job_id}")
async def get_scraping_status(job_id: str):
    """Get status of background scraping job"""
    if job_id not in background_jobs:
        raise HTTPException(status_code=404, detail="Job not found")
    
    return ApiResponse(
        success=True,
        message="Job status retrieved",
        data=background_jobs[job_id]
    )

async def run_background_scraping(job_id: str, phone_names: List[str], source: str):
    """Run background scraping job"""
    try:
        # Choose scraper
        if source.lower() == "phonedb" and phonedb_scraper:
            scraper = phonedb_scraper
        else:
            scraper = gsmarena_scraper
        
        if not scraper:
            background_jobs[job_id]["status"] = "failed"
            background_jobs[job_id]["error"] = "Scraper not available"
            return
        
        background_jobs[job_id]["status"] = "running"
        results = []
        
        for i, phone_name in enumerate(phone_names):
            try:
                # Update progress
                background_jobs[job_id]["progress"] = i
                background_jobs[job_id]["current_phone"] = phone_name
                
                # Scrape phone
                loop = asyncio.get_event_loop()
                result = await loop.run_in_executor(
                    None,
                    scraper.scrape_phone_by_name,
                    phone_name
                )
                
                if result:
                    results.append(result)
                
                # Add delay between requests
                await asyncio.sleep(2)
                
            except Exception as e:
                logger.error(f"Error scraping {phone_name} in background job: {e}")
                continue
        
        # Update job status
        background_jobs[job_id]["status"] = "completed"
        background_jobs[job_id]["progress"] = len(phone_names)
        background_jobs[job_id]["results"] = results
        background_jobs[job_id]["completed_at"] = datetime.now().isoformat()
        
    except Exception as e:
        background_jobs[job_id]["status"] = "failed"
        background_jobs[job_id]["error"] = str(e)
        logger.error(f"Background job {job_id} failed: {e}")

if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=7860,
        reload=True,
        log_level="info"
    )