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
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
---
title: AI Prescription Assistant
emoji: πŸ’Š
colorFrom: blue
colorTo: green
sdk: docker
pinned: false
app_port: 7860
---

# πŸ§ πŸ’Š AI Prescription Extraction & Smart Health Assistant


A premium, fully-functional web application that uses advanced OCR and NLP to extract structured information from prescription images.

![AI Prescription Assistant](https://img.shields.io/badge/AI-Prescription%20Assistant-blue?style=for-the-badge&logo=brain&logoColor=white)
![Version](https://img.shields.io/badge/version-1.0.0-green?style=for-the-badge)
![License](https://img.shields.io/badge/license-MIT-blue?style=for-the-badge)

## ✨ Features

### πŸ” **Advanced OCR Technology**
- **EasyOCR & Tesseract**: Dual OCR engine support for maximum accuracy
- **Smart Engine Selection**: Automatically chooses the best OCR engine
- **Image Preprocessing**: Advanced image enhancement for better text extraction
- **Handwritten + Printed Text**: Handles both types of prescriptions

### 🧠 **Intelligent NLP Analysis**
- **Medicine Detection**: Identifies medicine names with high accuracy
- **Strength Extraction**: Extracts dosage information (mg, ml, etc.)
- **Frequency Analysis**: Understands dosing patterns (1-0-1, BID, TID, etc.)
- **Duration Detection**: Identifies treatment duration (days, weeks, months)
- **Instructions Parsing**: Extracts special instructions (before/after food, timing)

### 🎨 **Modern Premium UI**
- **Royal Blue Theme**: Professional medical-grade design
- **Drag & Drop Upload**: Intuitive file upload experience
- **Real-time Processing**: Live progress indicators
- **Mobile Responsive**: Works perfectly on all devices
- **Accessibility**: WCAG compliant interface

### πŸ“Š **Smart Features**
- **Confidence Scoring**: AI confidence ratings for each extraction
- **Export Options**: PDF reports and JSON data export
- **Processing History**: Track previous analyses
- **Batch Processing**: Handle multiple prescriptions
- **Real-time Stats**: Live processing statistics

## πŸš€ Quick Start

### Prerequisites
```bash
# Python 3.8 or higher
python --version

# System dependencies (Ubuntu/Debian)
sudo apt update
sudo apt install tesseract-ocr tesseract-ocr-eng python3-dev
```

### Installation
```bash
# Clone or download the project
git clone <repository-url>
cd ai_prescription_app

# Install Python dependencies
pip install -r requirements.txt

# Run the application
python app.py
```

### Alternative: One-Click Setup
```bash
# Make setup script executable
chmod +x setup.sh

# Run automated setup
./setup.sh
```

## πŸ“± Usage

1. **Open the Application**
   - Navigate to `http://localhost:8000`
   - You'll see the modern AI Prescription Assistant interface

2. **Upload Prescription**
   - Drag & drop your prescription image
   - Or click "Browse Files" to select
   - Supports: JPG, PNG, PDF (max 10MB)

3. **Step 1: Extract Text**
   - Click "Extract Text" button
   - Choose OCR engine and enhancement level
   - View raw extracted text with confidence scores

4. **Step 2: AI Analysis**
   - Click "AI Analysis" button
   - Get structured prescription information:
     - Patient name, doctor name, date
     - Medicine list with strength, frequency, duration
     - Special instructions and confidence scores

5. **Export Results**
   - Copy JSON data to clipboard
   - Download professional PDF report
   - Download structured JSON file

## πŸ—οΈ Project Structure

```
ai_prescription_app/
β”œβ”€β”€ πŸ“ backend/                 # Backend API & Processing
β”‚   β”œβ”€β”€ main.py                # FastAPI server
β”‚   β”œβ”€β”€ ocr_engine.py          # OCR processing
β”‚   β”œβ”€β”€ nlp_analyzer.py        # NLP analysis
β”‚   β”œβ”€β”€ processor.py           # Main processor
β”‚   β”œβ”€β”€ pdf_generator.py       # PDF report generation
β”‚   └── utils.py              # Utility functions
β”œβ”€β”€ πŸ“ frontend/               # Frontend (if using React)
β”œβ”€β”€ πŸ“ templates/              # HTML templates
β”‚   └── index.html            # Main web interface
β”œβ”€β”€ πŸ“ static/                 # Static assets
β”‚   β”œβ”€β”€ css/styles.css        # Modern UI styles
β”‚   └── js/app.js             # Frontend logic
β”œβ”€β”€ πŸ“ sample_prescriptions/   # Test images
β”œβ”€β”€ πŸ“ uploads/               # Uploaded files
β”œβ”€β”€ πŸ“ outputs/               # Generated exports
β”œβ”€β”€ app.py                    # Main application runner
β”œβ”€β”€ requirements.txt          # Python dependencies
└── README.md                # This file
```

## πŸ”§ Configuration

### Environment Variables
```bash
# Optional: Set custom configuration
export OCR_ENGINE=smart          # easyocr, tesseract, smart
export MAX_FILE_SIZE_MB=10       # Maximum upload size
export PROCESSING_TIMEOUT=60     # Processing timeout
export USE_GPU=false            # Enable GPU for EasyOCR
```

### Config File
Create `config.json` for advanced settings:
```json
{
  "ocr": {
    "languages": ["en"],
    "confidence_threshold": 0.3,
    "use_gpu": false
  },
  "nlp": {
    "confidence_threshold": 0.5
  },
  "file_handling": {
    "max_file_size_mb": 10,
    "allowed_extensions": [".jpg", ".jpeg", ".png", ".pdf"]
  }
}
```

## πŸ§ͺ API Documentation

### Core Endpoints

#### POST `/api/process`
Process prescription image and extract structured data.

**Request:**
```bash
curl -X POST \
  http://localhost:8000/api/process \
  -F "file=@prescription.jpg" \
  -F "options={\"ocr_engine\":\"smart\"}"
```

**Response:**
```json
{
  "success": true,
  "processing_id": "proc_1234567890",
  "raw_text": "Dr. John Smith\nAmoxicillin 500mg...",
  "prescription_data": {
    "patient_name": "Jane Doe",
    "doctor_name": "Dr. John Smith",
    "medicines": [
      {
        "name": "Amoxicillin",
        "strength": "500mg",
        "frequency": "1-0-1",
        "duration": "7 days",
        "instructions": "after food",
        "confidence_score": 0.92
      }
    ]
  },
  "confidence": {
    "ocr_confidence": 0.87,
    "extraction_confidence": 0.91,
    "overall_confidence": 0.89
  }
}
```

#### GET `/api/export/pdf/{processing_id}`
Download generated PDF report.

#### GET `/api/export/json/{processing_id}`
Download structured JSON data.

### Additional Endpoints
- `GET /api/health` - Health check
- `GET /api/stats/performance` - Processing statistics
- `POST /api/batch-process` - Batch processing
- `GET /api/config` - Current configuration

## 🎯 Extraction Capabilities

### Patient Information
- βœ… **Patient Name**: Pattern matching for name fields
- βœ… **Doctor Name**: Medical professional identification
- βœ… **Prescription Date**: Multiple date format support

### Medicine Analysis
- βœ… **Medicine Names**: 500+ medicine database
- βœ… **Strength**: mg, ml, mcg, units, tablets, capsules
- βœ… **Frequency Patterns**: 
  - Numeric: 1-0-1, 1-1-1, 0-0-1
  - Medical: OD, BD, TID, QID, PRN
  - Descriptive: twice daily, morning, night
- βœ… **Duration**: days, weeks, months, "as needed"
- βœ… **Instructions**: 
  - Food relation: before/after food
  - Timing: morning, night, bedtime
  - Special: with water, shake well, refrigerate

### Confidence Scoring
- **OCR Confidence**: Text extraction reliability
- **Medicine Confidence**: Individual medicine accuracy
- **Overall Confidence**: Combined analysis score

## πŸš€ Deployment Options

### 1. Local Development
```bash
python app.py
# Access: http://localhost:8000
```

### 2. Production with Gunicorn
```bash
pip install gunicorn
gunicorn app:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000
```

### 3. Docker Deployment
```dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "app.py"]
```

### 4. Cloud Deployment

#### Railway
```bash
# Install Railway CLI
npm install -g @railway/cli

# Deploy
railway login
railway init
railway up
```

#### Render
1. Connect GitHub repository
2. Set build command: `pip install -r requirements.txt`
3. Set start command: `python app.py`

#### Heroku
```bash
# Create Procfile
echo "web: python app.py" > Procfile

# Deploy
heroku create your-app-name
git push heroku main
```

## πŸ§ͺ Testing

### Manual Testing
1. Use provided sample prescriptions in `sample_prescriptions/`
2. Test different image qualities and formats
3. Verify extraction accuracy
4. Check export functionality

### Test Prescriptions
- `sample_prescription.jpg` - Standard prescription
- `handwritten_rx.jpg` - Handwritten prescription
- `complex_prescription.pdf` - Multi-medicine prescription

### Performance Testing
```bash
# Load test with multiple files
python test_batch_processing.py
```

## πŸ”’ Security & Compliance

### Data Privacy
- βœ… **No Data Storage**: Images processed and deleted
- βœ… **Temporary Files**: Auto-cleanup after processing
- βœ… **HTTPS Ready**: SSL/TLS support for production
- βœ… **Input Validation**: File type and size restrictions

### Medical Compliance
- ⚠️ **Disclaimer**: Not for medical diagnosis
- βœ… **Accuracy Notice**: Confidence scoring provided
- βœ… **User Warning**: Healthcare professional consultation required

## πŸŽ›οΈ Troubleshooting

### Common Issues

#### 1. OCR Engine Not Found
```bash
# Install Tesseract
sudo apt install tesseract-ocr

# Install EasyOCR dependencies
pip install torch torchvision
```

#### 2. Poor Extraction Accuracy
- Use high-resolution images (min 300 DPI)
- Ensure good lighting and contrast
- Try different enhancement levels
- Use multiple OCR engines for comparison

#### 3. Memory Issues
- Reduce image size before processing
- Use CPU-only mode: `USE_GPU=false`
- Increase system memory limits

#### 4. Processing Timeout
- Increase timeout: `PROCESSING_TIMEOUT=120`
- Use smaller images
- Check system resources

### Debug Mode
```bash
# Enable debug logging
export LOG_LEVEL=DEBUG
python app.py
```

## πŸ“ˆ Performance Optimization

### Image Preprocessing
- βœ… **Automatic Enhancement**: Contrast, sharpness, noise reduction
- βœ… **Adaptive Thresholding**: Better text detection
- βœ… **Multiple Enhancement Levels**: Light, medium, heavy

### Processing Speed
- βœ… **Async Processing**: Non-blocking operations
- βœ… **Batch Processing**: Handle multiple files
- βœ… **Caching**: Reduced redundant processing

### Accuracy Improvements
- βœ… **Dual OCR Engines**: Best result selection
- βœ… **Confidence Thresholds**: Quality filtering
- βœ… **Medical Dictionary**: Enhanced medicine recognition

## πŸ—ΊοΈ Roadmap

### Version 1.1 (Next Release)
- [ ] **Multi-language Support**: Spanish, French, German
- [ ] **Voice Integration**: Audio prescription support
- [ ] **Medicine Database**: Expanded drug information
- [ ] **Drug Interactions**: Warning system
- [ ] **User Authentication**: Account management

### Version 1.2 (Future)
- [ ] **AI Training**: Custom model training
- [ ] **Mobile App**: React Native companion
- [ ] **Cloud Storage**: Optional data persistence
- [ ] **Analytics Dashboard**: Usage insights
- [ ] **API Rate Limiting**: Enterprise features

### Version 2.0 (Advanced)
- [ ] **Computer Vision**: Handwriting analysis
- [ ] **Medical NLP**: Advanced clinical parsing
- [ ] **Integration APIs**: EMR system connections
- [ ] **FHIR Compliance**: Healthcare standards
- [ ] **Real-time Processing**: Live camera feed

## 🀝 Contributing

1. Fork the repository
2. Create feature branch: `git checkout -b feature-name`
3. Commit changes: `git commit -am 'Add feature'`
4. Push branch: `git push origin feature-name`
5. Submit pull request

### Development Setup
```bash
# Install development dependencies
pip install -r requirements-dev.txt

# Run tests
pytest tests/

# Code formatting
black backend/ static/
```

## πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

## ⚠️ Disclaimer

**IMPORTANT MEDICAL DISCLAIMER:**

This AI Prescription Assistant is for informational and educational purposes only. It is not intended to be a substitute for professional medical advice, diagnosis, or treatment. Always seek the advice of qualified healthcare providers with any questions you may have regarding medical conditions or treatments.

The accuracy of text extraction and analysis depends on image quality and OCR technology limitations. Results should always be verified by healthcare professionals before making any medical decisions.

## πŸ“ž Support

- πŸ“§ **Email**: support@prescription-ai.com
- πŸ“± **GitHub Issues**: [Create Issue](https://github.com/your-repo/issues)
- πŸ“š **Documentation**: [Wiki](https://github.com/your-repo/wiki)
- πŸ’¬ **Discord**: [Join Community](https://discord.gg/your-server)

## πŸ™ Acknowledgments

- **EasyOCR Team**: Excellent OCR library
- **Tesseract Community**: Robust OCR engine
- **FastAPI**: Modern web framework
- **ReportLab**: PDF generation library
- **Contributors**: All project contributors

---

Made with ❀️ for the healthcare community

**Happy Analyzing! πŸ§ πŸ’Š**