--- 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 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! πŸ§ πŸ’Š**