Spaces:
Running on Zero
Running on Zero
File size: 10,361 Bytes
3d9ba5b | 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 | # 🔌 Bilingual Text Summarization REST API
## Developer & Integration Guide for Frontend / Backend Engineers
**API Version**: `1.0.0`
**Base URL**: `http://localhost:8000` (or `http://127.0.0.1:8000`)
**Swagger Interactive Docs**: `http://localhost:8000/docs`
**ReDoc Clean Reference**: `http://localhost:8000/redoc`
**Postman Collection File**: [`api/postman_collection.json`](file:///c:/Users/FadyS/Downloads/sumary%20project/api/postman_collection.json)
**Postman Environment File**: [`api/postman_environment.json`](file:///c:/Users/FadyS/Downloads/sumary%20project/api/postman_environment.json)
---
## 1. Quick Start & Server Launch
### Step 1: Install Dependencies
```bash
pip install -r requirements.txt
# Ensure fastapi, uvicorn, python-multipart are installed
pip install fastapi uvicorn python-multipart
```
### Step 2: Start the FastAPI Server
```bash
python run_api.py
```
*Or directly using Uvicorn:*
```bash
uvicorn api.server:app --host 0.0.0.0 --port 8000 --reload
```
---
## 2. Postman Quick Import
1. Open **Postman**.
2. Click **Import** in the top-left corner.
3. Select or drag-and-drop:
- `api/postman_collection.json`
- `api/postman_environment.json`
4. Select the environment **"Bilingual Summarization API (Local Environment)"** in the top-right environment selector.
5. All requests are ready to run with pre-configured headers, bodies, and automated test assertions!
---
## 3. Endpoints Reference
### 3.1 System & Health
#### `GET /api/v1/health`
Checks server health, GPU/CUDA hardware acceleration, and loaded deep learning checkpoints.
- **Response `200 OK`**:
```json
{
"status": "healthy",
"version": "1.0.0",
"device": "cpu",
"cuda_available": false,
"loaded_checkpoints": {
"seq2seq_arabic": true,
"seq2seq_english": true,
"rich_seq2seq_ar": true,
"rich_seq2seq_en": true
}
}
```
---
#### `GET /api/v1/models`
Returns list of available summarization algorithms, paradigms, and checkpoint states.
- **Response `200 OK`**:
```json
{
"total_models": 5,
"models": [
{
"id": "textrank",
"name": "TextRank",
"paradigm": "extractive",
"supported_languages": ["ar", "en"],
"description": "Graph-based PageRank sentence centrality algorithm computing lexical and TF-IDF similarity graphs."
},
{
"id": "lsa",
"name": "Latent Semantic Analysis (LSA)",
"paradigm": "extractive",
"supported_languages": ["ar", "en"],
"description": "Singular Value Decomposition (SVD) identifying latent semantic concepts."
},
{
"id": "hybrid",
"name": "Hybrid Multi-Feature Scorer",
"paradigm": "extractive",
"supported_languages": ["ar", "en"],
"description": "Composite scorer linearly weighting graph centrality, positional bias, and length penalty."
},
{
"id": "seq2seq",
"name": "Seq2Seq with Bahdanau Attention",
"paradigm": "abstractive",
"supported_languages": ["ar", "en"],
"description": "Deep Bi-GRU Encoder-Decoder network with additive attention and Beam Search.",
"checkpoint_available": true
}
]
}
```
---
### 3.2 NLP Core & Preprocessing
#### `POST /api/v1/detect-language`
Detects language (`ar`, `en`, or `unknown`) and script distribution with confidence score.
- **Request Body**:
```json
{
"text": "اعلنت وكالة ناسا الفضائية عن خطط طموحة للعودة الى سطح القمر."
}
```
- **Response `200 OK`**:
```json
{
"detected_language": "ar",
"language_name": "Arabic",
"confidence": 0.98,
"script_breakdown": {
"arabic": 0.95,
"latin": 0.05,
"other": 0.0
}
}
```
---
#### `POST /api/v1/tokenize`
Performs Arabic normalization (Tashkeel stripping, Alef unification), sentence boundary detection, and tokenization.
- **Request Body**:
```json
{
"text": "الذكاءُ الاصطناعيُّ يُحدِث ثورةً في معالجة اللغات! هل يمكن تلخيص النصوص؟ نعم.",
"lang": "ar",
"remove_stopwords": false,
"stem": false
}
```
- **Response `200 OK`**:
```json
{
"detected_language": "ar",
"sentence_count": 3,
"word_count": 13,
"sentences": [
"الذكاء الاصطناعي يحدث ثورة في معالجة اللغات!",
"هل يمكن تلخيص النصوص؟",
"نعم."
],
"tokens": ["الذكاء", "الاصطناعي", "يحدث", "ثورة", "في", "معالجة", "اللغات", "هل", "يمكن", "تلخيص", "النصوص", "نعم"],
"normalized_text": "الذكاء الاصطناعي يحدث ثورة في معالجة اللغات! هل يمكن تلخيص النصوص؟ نعم."
}
```
---
### 3.3 Text Summarization
#### `POST /api/v1/summarize`
Main summarization endpoint supporting all Extractive and Abstractive algorithms.
- **Request Parameters**:
- `text` (*string, required*): Raw source document text.
- `mode` (*string, default: "extractive"*): `"extractive"`, `"abstractive"`, or `"hybrid"`.
- `method` (*string, default: "textrank"*): `"textrank"`, `"lsa"`, `"hybrid"`, `"seq2seq"`, `"transformer"`.
- `lang` (*string, default: "auto"*): `"auto"`, `"ar"`, or `"en"`.
- `sentences` (*int, default: 3*): Number of target sentences (for extractive).
- `ratio` (*float, optional*): Target compression ratio between `0.05` and `0.95`.
- `beam_width` (*int, default: 3*): Beam search width for Seq2Seq decoding (`1` to `8`).
- `reference_summary` (*string, optional*): Gold-standard reference summary to automatically compute ROUGE & BLEU scores.
- **Example 1: Arabic Abstractive (Seq2Seq)**:
```json
{
"text": "اعلنت وكالة ناسا الفضائية الامريكية عن خطط طموحة للعودة الى سطح القمر في اطار برنامج ارتيميس حيث ستشمل البعثة اول امراة واول شخص من ذوي البشرة الداكنة يمشيان على سطح القمر ومن المقرر ان تنطلق البعثة قبل نهاية عام الفين وخمسة وعشرين.",
"mode": "abstractive",
"method": "seq2seq",
"lang": "ar",
"beam_width": 3,
"reference_summary": "ناسا تعلن خطط العودة للقمر عبر برنامج ارتيميس الذي سيضم اول امراة واول شخص من ذوي البشرة الداكنة قبل نهاية 2025"
}
```
- **Response `200 OK`**:
```json
{
"status": "success",
"detected_language": "ar",
"mode": "abstractive",
"method": "seq2seq",
"summary": "ناسا تعلن خطط العوده للقمر عبر برنامج ارتيميس الذي سيضم اول امراه واول شخص من ذوي البشره الداكنه قبل نهايه 2025",
"latency_ms": 32.4,
"metrics": {
"original_words": 37,
"summary_words": 21,
"compression_ratio": 0.567,
"reduction_percentage": 43.3,
"type_token_ratio": 0.952,
"rouge_1_f1": 0.952,
"rouge_2_f1": 0.850,
"rouge_l_f1": 0.952,
"bleu_1": 0.952,
"bleu_2": 0.850,
"bleu_cumulative": 0.784
},
"selected_indices": null,
"sentence_scores": null,
"note": null
}
```
---
#### `POST /api/v1/summarize/file` (Multipart Form Data)
Accepts uploaded document files (`.pdf`, `.docx`, `.txt`) and returns the generated summary.
- **Request `multipart/form-data`**:
- `file`: Binary file upload (`application/pdf`, `text/plain`, `application/vnd.openxmlformats-officedocument.wordprocessingml.document`).
- `mode`: `"extractive"` / `"abstractive"`.
- `method`: `"hybrid"` / `"textrank"` / `"lsa"` / `"seq2seq"`.
- `lang`: `"auto"` / `"ar"` / `"en"`.
- `sentences`: `3`.
- **cURL Example**:
```bash
curl -X POST "http://localhost:8000/api/v1/summarize/file" \
-H "accept: application/json" \
-F "file=@document.pdf" \
-F "mode=extractive" \
-F "method=hybrid" \
-F "sentences=3"
```
---
### 3.4 Evaluation & Metrics
#### `POST /api/v1/evaluate`
Calculates comprehensive evaluation metrics between an original text, a generated summary, and an optional reference summary.
- **Request Body**:
```json
{
"original_text": "Global semiconductor shortages are easing according to the latest industry report with chip inventories returning to normal.",
"generated_summary": "Semiconductor shortage eases as chip inventories return to normal levels.",
"reference_summary": "Global chip shortage easing with inventories normalizing across industry.",
"lang": "en"
}
```
- **Response `200 OK`**:
```json
{
"language": "en",
"compression_ratio": 0.625,
"reduction_percentage": 37.5,
"original_words": 16,
"summary_words": 10,
"type_token_ratio": 1.0,
"rouge_1": {
"precision": 0.50,
"recall": 0.55,
"f1": 0.526
},
"rouge_2": {
"precision": 0.22,
"recall": 0.25,
"f1": 0.235
},
"rouge_l": {
"precision": 0.50,
"recall": 0.55,
"f1": 0.526
},
"bleu_1": 0.50,
"bleu_2": 0.22,
"bleu_3": 0.12,
"bleu_4": 0.05,
"bleu_cumulative": 0.18
}
```
---
## 4. Frontend Integration Examples
### React / Next.js / Fetch API Example:
```javascript
async function generateSummary(inputText, algorithm = 'seq2seq') {
try {
const response = await fetch('http://localhost:8000/api/v1/summarize', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: inputText,
mode: algorithm === 'seq2seq' ? 'abstractive' : 'extractive',
method: algorithm,
lang: 'auto',
beam_width: 3
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Summary:', data.summary);
console.log('Reduction:', data.metrics.reduction_percentage + '%');
return data;
} catch (error) {
console.error('Failed to generate summary:', error);
}
}
```
### Python Requests Example:
```python
import requests
url = "http://localhost:8000/api/v1/summarize"
payload = {
"text": "شهدت الاسواق العالمية تراجعا حادا في اسعار النفط الخام بعد قرار منظمة اوبك زيادة الانتاج.",
"mode": "extractive",
"method": "textrank",
"sentences": 1
}
res = requests.post(url, json=payload)
print(res.json()["summary"])
```
|