This FastAPI backend ingests hazard-related posts from X (Twitter) and processes them using a hybrid NLP engine to classify hazards, extract keywords, and summarize engagement metrics.
It is designed to support INCOIS (Indian National Centre for Ocean Information Services) for early warning and disaster risk monitoring along India's coasts.
-
Real-time Twitter Data Fetching:
- Hazard-specific keyword filtering (cyclone, flood, tsunami, storm surge, landslide, etc.)
- Location-based filtering (e.g., Chennai, Andhra Pradesh)
- English language posts only
- Excludes retweets for original content
- Configurable time window (default: last 2 hours)
-
Advanced Hazard Classification:
- LLM-based context analysis using
facebook/bart-large-mnlizero-shot classification - Multi-step classification pipeline:
- Context analysis to determine if content is hazard-related
- Specific hazard type identification using keyword matching
- Confidence-based filtering to reduce false positives
- Caching with LRU cache to optimize performance
- Hazard categories: flood, cyclone, tsunami, storm surge, landslide, heavy rain, high waves, ocean hazard
- LLM-based context analysis using
-
Keyword Analysis:
- Per-post keyword frequency extraction
- Aggregated keyword summary across all posts
- Hazard-specific keyword tracking
-
Engagement Metrics:
- Retweet count, reply count, like count, quote count
- Social media impact assessment
-
API Features:
- RESTful API with FastAPI
- Interactive API documentation (Swagger UI)
- Pydantic models for request/response validation
- Error handling and rate limiting considerations
FastAPI_NLP-main/
├── main.py # FastAPI application with endpoints
├── nlp_service.py # Hazard classification + keyword extraction
├── twitter_client.py # Twitter API integration
├── schemas.py # Pydantic models for request/response
├── utils.py # Helper functions (time formatting, query building)
├── config.py # Configuration (API keys, hazard keywords, defaults)
├── requirements.txt # Python dependencies
├── README.md # This file
└── genai/ # Virtual environment (if using venv)
- Python 3.8 or higher
- Twitter API Bearer Token (for accessing Twitter API v2)
git clone <your-repo-url>
cd FastAPI_NLP-main# Create virtual environment
python -m venv genai
# Activate virtual environment
# On Windows:
genai\Scripts\activate
# On Linux/macOS:
source genai/bin/activatepip install -r requirements.txtDependencies included:
fastapi- Web framework for building APIsuvicorn- ASGI server for running FastAPIhttpx- HTTP client for async requestspydantic- Data validation using Python type annotationspython-dotenv- Load environment variables from .env filetransformers- Hugging Face transformers library for NLP modelstorch- PyTorch for deep learning models
Create a .env file in the root directory:
TWITTER_BEARER_TOKEN=your_twitter_bearer_token_hereTo get a Twitter Bearer Token:
- Go to Twitter Developer Portal
- Create a new app or use an existing one
- Generate a Bearer Token in the "Keys and Tokens" section
In config.py, you can customize:
# Hazard-related keywords for filtering
HAZARD_KEYWORDS = [
"ocean hazard", "tsunami", "cyclone", "flood", "storm surge",
"landslide", "heavy rain", "high waves", "swell surge"
]
# Default settings
DEFAULT_MAX_RESULTS = 20 # Maximum tweets to fetch per request
TIME_WINDOW_HOURS = 2 # Time window for tweet search (last 2 hours)# Make sure your virtual environment is activated
# Then run:
python main.pyOr alternatively:
uvicorn main:app --host 0.0.0.0 --port 8000 --reload- API Server:
http://127.0.0.1:8000 - Interactive API Documentation (Swagger UI):
http://127.0.0.1:8000/docs - Alternative API Documentation (ReDoc):
http://127.0.0.1:8000/redoc
For production deployment, use:
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4The system uses a sophisticated multi-step approach for hazard classification:
- Context Analysis: Uses
facebook/bart-large-mnlifor zero-shot classification to determine if content is hazard-related - Specific Hazard Identification: Keyword-based matching for specific hazard types
- Confidence Filtering: Only returns classifications with sufficient confidence (>0.6)
flood- Flooding, water level rise, inundationcyclone- Cyclones, hurricanes, typhoons, stormstsunami- Tsunamis, tidal waves, seismic wavesstorm surge- Storm surges, coastal floodinglandslide- Landslides, mudslides, rock fallsheavy rain- Heavy rainfall, downpours, torrential rainhigh waves- High waves, rough seas, wave heightocean hazard- General ocean hazards, marine hazardsnot_hazard- Content not related to hazardsunknown- Hazard-related but type unclear
GET /fetch_posts
Query Parameters:
| Parameter | Type | Description |
|---|---|---|
| hazard | str | Filter by hazard type (e.g., cyclone, flood) |
| location | str | Filter posts mentioning a location (e.g., Chennai, Andhra Pradesh) |
| max_results | int | Max number of posts to fetch (default 5, max 50) |
GET http://127.0.0.1:8000/fetch_posts?hazard=flood&location=Chennai&max_results=10
{
"query": "(flood) (Chennai) lang:en -is:retweet",
"time_window": "last_2h",
"hazard_filter": "flood",
"location_filter": "Chennai",
"posts": [
{
"id": "1701456789012345",
"text": "Flood waters rising near Chennai due to heavy rain",
"created_at": "2025-09-18T07:40:00Z",
"author_id": "112233",
"conversation_id": "1701456789012345",
"hazard_classification": "flood",
"engagement": {
"retweet_count": 15,
"reply_count": 6,
"like_count": 55,
"quote_count": 2
},
"keyword_frequency": {
"flood": 1,
"rain": 1
},
"direct_replies": []
}
],
"keyword_summary": {
"flood": 1,
"rain": 1
}
}-
query: Actual Twitter API query used. -
time_window: Always last 2 hours. -
hazard_filter,location_filter: Echo of applied filters. -
posts: List of main posts with metadata:hazard_classification→ hazard type ornot_hazardkeyword_frequency→ frequency of hazard-related keywordsengagement→ likes, retweets, replies, quotesdirect_replies→ optional list of replies
-
keyword_summary: Aggregated keyword counts across all posts.
curl "http://127.0.0.1:8000/fetch_posts?hazard=flood&location=Chennai&max_results=5"curl "http://127.0.0.1:8000/fetch_posts?hazard=cyclone&max_results=10"curl "http://127.0.0.1:8000/fetch_posts?location=Andhra%20Pradesh&max_results=15"