File size: 8,027 Bytes
09281fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
365
366
367
368
369
370
371
372
373
374
# Flask API Server for Advanced RAG System

This Flask API server provides REST endpoints for the Advanced RAG System, allowing you to upload documents and process queries programmatically.

## Features

- **Document Upload**: Upload and process various document formats (PDF, TXT, DOCX, HTML, etc.)
- **Query Processing**: Ask questions about uploaded documents
- **OCR Support**: Process scanned documents with OCR
- **System Management**: Check status, validate components, clear data
- **Authentication**: Bearer token authentication
- **Error Handling**: Comprehensive error handling and fallback mechanisms

## API Endpoints

### 1. Health Check
**GET** `/health`

Check if the server is running and healthy.

**Response:**
```json
{
  "status": "healthy",
  "rag_system_initialized": true,
  "ocr_available": true
}
```

### 2. System Status
**GET** `/hackrx/status`

Get detailed system status and statistics.

**Headers:**
```
Authorization: Bearer your_api_key_here
```

**Response:**
```json
{
  "status": "ready",
  "statistics": {
    "vector_database": {
      "total_chunks": 150,
      "unique_sources": 3,
      "file_types": ["pdf", "txt"]
    },
    "audit_trail": {
      "total_entries": 25,
      "successful_queries": 20,
      "failed_queries": 5
    }
  },
  "ocr_available": true
}
```

### 3. Document Upload
**POST** `/hackrx/upload`

Upload and process a document.

**Headers:**
```
Authorization: Bearer your_api_key_here
```

**Form Data:**
- `file`: The document file to upload
- `use_ocr`: (optional) "true" or "false" to enable OCR for PDFs

**Supported File Types:**
- PDF (.pdf)
- Text (.txt)
- Word (.docx)
- HTML (.html, .htm)
- Email (.eml, .msg)
- CSV (.csv)
- JSON (.json)

**Response:**
```json
{
  "success": true,
  "message": "Document processed successfully",
  "chunks_processed": 45,
  "processing_time": 2.34,
  "filename": "document.pdf"
}
```

### 4. Query Processing
**POST** `/hackrx/run`

Process questions about uploaded documents.

**Headers:**
```
Authorization: Bearer your_api_key_here
Content-Type: application/json
```

**Request Body:**
```json
{
  "questions": [
    "What is covered under this policy?",
    "What is the maximum coverage amount?",
    "What documents are required for claims?"
  ]
}
```

**Response:**
```json
{
  "answers": [
    {
      "question": "What is covered under this policy?",
      "answer": "Based on the policy document, the following are covered...",
      "decision": "COVERED",
      "confidence": 0.85,
      "processing_time": 1.23,
      "amount": 50000.0,
      "waiting_period": "30 days",
      "relevant_clauses": ["Section 3.1", "Section 4.2"],
      "conditions": ["Must be hospitalized", "Pre-authorization required"],
      "exclusions": ["Cosmetic procedures", "Experimental treatments"],
      "required_documents": ["Hospital bills", "Medical reports"]
    }
  ]
}
```

### 5. System Validation
**GET** `/hackrx/validate`

Validate all system components.

**Headers:**
```
Authorization: Bearer your_api_key_here
```

**Response:**
```json
{
  "document_processor": true,
  "vector_database": true,
  "query_parser": true,
  "reasoning_engine": true,
  "all_valid": true,
  "errors": []
}
```

### 6. Clear System
**POST** `/hackrx/clear`

Clear all system data and reset the RAG system.

**Headers:**
```
Authorization: Bearer your_api_key_here
```

**Response:**
```json
{
  "success": true,
  "message": "System cleared successfully"
}
```

## Authentication

All endpoints (except `/health`) require Bearer token authentication:

```
Authorization: Bearer your_api_key_here
```

**Default API Key:** `your_api_key_here`

**Note:** Change this in production for security.

## Error Responses

All endpoints return appropriate HTTP status codes:

- `200`: Success
- `400`: Bad Request (missing parameters, invalid data)
- `401`: Unauthorized (missing or invalid Authorization header)
- `403`: Forbidden (invalid API key)
- `500`: Internal Server Error

Error response format:
```json
{
  "error": "Error description"
}
```

## Usage Examples

### Python Example

```python
import requests
import json

# Configuration
BASE_URL = "http://localhost:5000"
API_KEY = "your_api_key_here"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

# 1. Upload a document
with open("document.pdf", "rb") as f:
    files = {"file": f}
    data = {"use_ocr": "false"}
    upload_headers = {"Authorization": f"Bearer {API_KEY}"}
    
    response = requests.post(
        f"{BASE_URL}/hackrx/upload",
        files=files,
        data=data,
        headers=upload_headers
    )
    print("Upload response:", response.json())

# 2. Process queries
questions = [
    "What is covered under this policy?",
    "What is the maximum coverage amount?"
]

payload = {"questions": questions}
response = requests.post(
    f"{BASE_URL}/hackrx/run",
    json=payload,
    headers=HEADERS
)

answers = response.json()["answers"]
for answer in answers:
    print(f"Q: {answer['question']}")
    print(f"A: {answer['answer']}")
    print(f"Decision: {answer['decision']}")
    print(f"Confidence: {answer['confidence']}")
    print("---")
```

### cURL Examples

**Health Check:**
```bash
curl http://localhost:5000/health
```

**System Status:**
```bash
curl -H "Authorization: Bearer your_api_key_here" \
     http://localhost:5000/hackrx/status
```

**Upload Document:**
```bash
curl -X POST \
     -H "Authorization: Bearer your_api_key_here" \
     -F "file=@document.pdf" \
     -F "use_ocr=false" \
     http://localhost:5000/hackrx/upload
```

**Process Queries:**
```bash
curl -X POST \
     -H "Authorization: Bearer your_api_key_here" \
     -H "Content-Type: application/json" \
     -d '{"questions": ["What is covered under this policy?"]}' \
     http://localhost:5000/hackrx/run
```

## Running the Server

1. **Install Dependencies:**
   ```bash
   pip install flask requests
   ```

2. **Start the Server:**
   ```bash
   python app.py
   ```

3. **Test the API:**
   ```bash
   python test_api.py
   ```

## Configuration

### Environment Variables

You can set these environment variables:

- `FLASK_ENV`: Set to `production` for production deployment
- `API_KEY`: Override the default API key
- `PORT`: Override the default port (5000)

### Production Deployment

For production deployment:

1. Change the API key in `app.py`
2. Set `debug=False` in `app.run()`
3. Use a production WSGI server like Gunicorn:
   ```bash
   pip install gunicorn
   gunicorn -w 4 -b 0.0.0.0:5000 app:app
   ```

## Troubleshooting

### Common Issues

1. **RAG System Initialization Failed**
   - Check if all required dependencies are installed
   - Ensure model files are available
   - Check system memory and resources

2. **Document Upload Fails**
   - Verify file format is supported
   - Check file size limits
   - Ensure proper file permissions

3. **Query Processing Errors**
   - Make sure documents are uploaded first
   - Check if the RAG system is properly initialized
   - Verify the question format

4. **Authentication Errors**
   - Ensure the Authorization header is present
   - Verify the API key is correct
   - Check the Bearer token format

### Logs

The server provides detailed logging. Check the console output for:
- RAG system initialization status
- Document processing progress
- Query processing results
- Error messages and stack traces

## Security Considerations

1. **Change the Default API Key**: Update `your_api_key_here` in production
2. **Use HTTPS**: Always use HTTPS in production
3. **Rate Limiting**: Consider implementing rate limiting for production use
4. **Input Validation**: The API includes basic validation, but add more as needed
5. **File Upload Security**: Implement additional file validation for production

## Support

For issues and questions:
1. Check the console logs for error messages
2. Verify all dependencies are installed
3. Test with the provided `test_api.py` script
4. Check the system validation endpoint for component status