File size: 11,205 Bytes
49e67a8
 
 
 
 
 
 
 
 
 
f4d6026
49e67a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4d6026
 
 
49e67a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0663fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49e67a8
 
 
 
 
 
 
 
 
 
 
 
 
 
f4d6026
49e67a8
 
 
 
 
f4d6026
 
 
 
 
 
 
 
49e67a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4d6026
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49e67a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4d6026
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
from fastapi import FastAPI, BackgroundTasks, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional
import json
import logging
from datetime import datetime
from email.utils import parsedate_to_datetime

# Import our modules
from scraper import fetch_hazard_tweets, fetch_custom_tweets, get_available_hazards, get_available_locations
from classifier import classify_tweets
from pg_db import init_db, upsert_hazardous_tweet

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

# Initialize FastAPI app
app = FastAPI(
    title="Ocean Hazard Detection API",
    description="API for detecting ocean hazards from social media posts",
    version="1.0.0"
)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Configure this properly for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize database
try:
    init_db()
    logger.info("Database initialized successfully")
except Exception as e:
    logger.warning(f"Database initialization failed: {e}. API will work without database persistence.")

# Pydantic models
class TweetAnalysisRequest(BaseModel):
    limit: int = 20
    query: Optional[str] = None
    hazard_type: Optional[str] = None
    location: Optional[str] = None
    days_back: int = 1

class TweetAnalysisResponse(BaseModel):
    total_tweets: int
    hazardous_tweets: int
    results: List[dict]
    processing_time: float

class HealthResponse(BaseModel):
    status: str
    message: str
    timestamp: str

# Health check endpoint
@app.get("/", response_model=HealthResponse)
def health_check():
    """Health check endpoint"""
    return HealthResponse(
        status="healthy",
        message="Ocean Hazard Detection API is running",
        timestamp=datetime.utcnow().isoformat()
    )

@app.get("/health", response_model=HealthResponse)
def health():
    """Alternative health check endpoint"""
    return health_check()

@app.post("/warmup")
async def warmup_models():
    """Pre-load all models to reduce first request time"""
    try:
        logger.info("Starting model warmup...")
        
        # Pre-load all models
        from classifier import get_classifier
        from ner import get_ner_pipeline
        from sentiment import get_emotion_classifier
        from translate import get_translator
        
        classifier = get_classifier()
        ner = get_ner_pipeline()
        emotion_clf = get_emotion_classifier()
        translator = get_translator()
        
        # Test with sample data
        test_text = "Test tweet for model warmup"
        classifier(test_text, ["test", "not test"])
        if ner:
            ner(test_text)
        emotion_clf(test_text)
        translator(test_text)
        
        logger.info("Model warmup completed successfully")
        return {"status": "success", "message": "All models loaded and ready"}
        
    except Exception as e:
        logger.error(f"Model warmup failed: {str(e)}")
        return {"status": "error", "message": str(e)}

# Main analysis endpoint
@app.post("/analyze", response_model=TweetAnalysisResponse)
async def analyze_tweets(request: TweetAnalysisRequest):
    """
    Analyze tweets for ocean hazards
    
    - **limit**: Number of tweets to analyze (1-50)
    - **query**: Custom search query (optional)
    """
    start_time = datetime.utcnow()
    
    try:
        logger.info(f"Starting analysis with limit: {request.limit}")
        
        # Fetch tweets based on search type
        if request.query:
            # Use custom query if provided
            from scraper import search_tweets, extract_tweets
            result = search_tweets(request.query, limit=request.limit)
            tweets = extract_tweets(result)
        elif request.hazard_type or request.location:
            # Use keyword-based search
            tweets = fetch_custom_tweets(
                hazard_type=request.hazard_type,
                location=request.location,
                limit=request.limit,
                days_back=request.days_back
            )
        else:
            # Use default hazard query
            tweets = fetch_hazard_tweets(limit=request.limit)
        
        logger.info(f"Fetched {len(tweets)} tweets")
        
        # Classify tweets
        results = classify_tweets(tweets)
        logger.info(f"Classified {len(results)} tweets")
        
        # Store hazardous tweets in database
        hazardous_count = 0
        try:
            for r in results:
                if r.get('hazardous') == 1:
                    hazardous_count += 1
                    hazards = (r.get('ner') or {}).get('hazards') or []
                    hazard_type = ", ".join(hazards) if hazards else "unknown"
                    locs = (r.get('ner') or {}).get('locations') or []
                    if not locs and r.get('location'):
                        locs = [r['location']]
                    location = ", ".join(locs) if locs else "unknown"
                    sentiment = r.get('sentiment') or {"label": "unknown", "score": 0.0}
                    created_at = r.get('created_at') or ""
                    tweet_date = ""
                    tweet_time = ""
                    if created_at:
                        dt = None
                        try:
                            dt = parsedate_to_datetime(created_at)
                        except Exception:
                            dt = None
                        if dt is None and 'T' in created_at:
                            try:
                                iso = created_at.replace('Z', '+00:00')
                                dt = datetime.fromisoformat(iso)
                            except Exception:
                                dt = None
                        if dt is not None:
                            tweet_date = dt.date().isoformat()
                            tweet_time = dt.time().strftime('%H:%M:%S')
                    upsert_hazardous_tweet(
                        tweet_url=r.get('tweet_url') or "",
                        hazard_type=hazard_type,
                        location=location,
                        sentiment_label=sentiment.get('label', 'unknown'),
                        sentiment_score=float(sentiment.get('score', 0.0)),
                        tweet_date=tweet_date,
                        tweet_time=tweet_time,
                    )
            logger.info(f"Stored {hazardous_count} hazardous tweets in database")
        except Exception as db_error:
            logger.warning(f"Database storage failed: {db_error}. Results will not be persisted.")
        
        # Calculate processing time
        processing_time = (datetime.utcnow() - start_time).total_seconds()
        
        return TweetAnalysisResponse(
            total_tweets=len(results),
            hazardous_tweets=hazardous_count,
            results=results,
            processing_time=processing_time
        )
        
    except Exception as e:
        logger.error(f"Analysis failed: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

# Get stored hazardous tweets
@app.get("/hazardous-tweets")
async def get_hazardous_tweets(limit: int = 100, offset: int = 0):
    """
    Get stored hazardous tweets from database
    
    - **limit**: Maximum number of tweets to return (default: 100)
    - **offset**: Number of tweets to skip (default: 0)
    """
    try:
        from pg_db import get_conn
        
        with get_conn() as conn:
            with conn.cursor() as cur:
                cur.execute("""
                    SELECT tweet_url, hazard_type, location, sentiment_label, 
                           sentiment_score, tweet_date, tweet_time, inserted_at
                    FROM hazardous_tweets 
                    ORDER BY inserted_at DESC 
                    LIMIT %s OFFSET %s
                """, (limit, offset))
                
                columns = [desc[0] for desc in cur.description]
                results = [dict(zip(columns, row)) for row in cur.fetchall()]
                
                return {
                    "tweets": results,
                    "count": len(results),
                    "limit": limit,
                    "offset": offset
                }
                
    except Exception as e:
        logger.error(f"Failed to fetch hazardous tweets: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

# Get available keywords
@app.get("/keywords/hazards")
async def get_hazard_keywords():
    """Get available hazard types for keyword search"""
    return {
        "hazards": get_available_hazards(),
        "count": len(get_available_hazards())
    }

@app.get("/keywords/locations")
async def get_location_keywords():
    """Get available locations for keyword search"""
    return {
        "locations": get_available_locations(),
        "count": len(get_available_locations())
    }

# Get statistics
@app.get("/stats")
async def get_stats():
    """Get analysis statistics"""
    try:
        from pg_db import get_conn
        
        with get_conn() as conn:
            with conn.cursor() as cur:
                # Total hazardous tweets
                cur.execute("SELECT COUNT(*) FROM hazardous_tweets")
                total_hazardous = cur.fetchone()[0]
                
                # By hazard type
                cur.execute("""
                    SELECT hazard_type, COUNT(*) as count 
                    FROM hazardous_tweets 
                    GROUP BY hazard_type 
                    ORDER BY count DESC
                """)
                hazard_types = [{"type": row[0], "count": row[1]} for row in cur.fetchall()]
                
                # By location
                cur.execute("""
                    SELECT location, COUNT(*) as count 
                    FROM hazardous_tweets 
                    WHERE location != 'unknown'
                    GROUP BY location 
                    ORDER BY count DESC
                    LIMIT 10
                """)
                locations = [{"location": row[0], "count": row[1]} for row in cur.fetchall()]
                
                # By sentiment
                cur.execute("""
                    SELECT sentiment_label, COUNT(*) as count 
                    FROM hazardous_tweets 
                    GROUP BY sentiment_label 
                    ORDER BY count DESC
                """)
                sentiments = [{"sentiment": row[0], "count": row[1]} for row in cur.fetchall()]
                
                return {
                    "total_hazardous_tweets": total_hazardous,
                    "hazard_types": hazard_types,
                    "top_locations": locations,
                    "sentiment_distribution": sentiments
                }
                
    except Exception as e:
        logger.error(f"Failed to fetch statistics: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

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