Spaces:
Sleeping
Sleeping
Update app.py
#1
by
Hanan-Alnakhal - opened
app.py
CHANGED
|
@@ -1,234 +1,254 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Lab Report Decoder - Flask Application
|
| 3 |
-
Professional web interface for lab report analysis
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
from
|
| 8 |
-
import
|
| 9 |
-
import
|
| 10 |
-
import
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
app.
|
| 22 |
-
app.config['
|
| 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 |
-
file.
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Lab Report Decoder - Flask Application
|
| 3 |
+
Professional web interface for lab report analysis
|
| 4 |
+
Fixed for Hugging Face Spaces stateless environment
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from flask import Flask, render_template, request, jsonify
|
| 8 |
+
from werkzeug.utils import secure_filename
|
| 9 |
+
import os
|
| 10 |
+
import tempfile
|
| 11 |
+
import secrets
|
| 12 |
+
import json
|
| 13 |
+
import uuid
|
| 14 |
+
from pdf_extractor import LabReportExtractor, LabResult
|
| 15 |
+
from rag_engine import LabReportRAG
|
| 16 |
+
from dotenv import load_dotenv
|
| 17 |
+
|
| 18 |
+
load_dotenv()
|
| 19 |
+
|
| 20 |
+
app = Flask(__name__)
|
| 21 |
+
app.secret_key = os.getenv('SECRET_KEY', secrets.token_hex(16))
|
| 22 |
+
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
|
| 23 |
+
app.config['UPLOAD_FOLDER'] = tempfile.gettempdir()
|
| 24 |
+
|
| 25 |
+
# Initialize RAG system (singleton)
|
| 26 |
+
rag_system = None
|
| 27 |
+
|
| 28 |
+
# In-memory storage for sessions (better than Flask sessions in HF Spaces)
|
| 29 |
+
session_storage = {}
|
| 30 |
+
|
| 31 |
+
def get_rag_system():
|
| 32 |
+
"""Lazy load RAG system"""
|
| 33 |
+
global rag_system
|
| 34 |
+
if rag_system is None:
|
| 35 |
+
print("π Initializing RAG system...")
|
| 36 |
+
rag_system = LabReportRAG()
|
| 37 |
+
print("β
RAG system ready")
|
| 38 |
+
return rag_system
|
| 39 |
+
|
| 40 |
+
@app.route('/')
|
| 41 |
+
def index():
|
| 42 |
+
"""Main page"""
|
| 43 |
+
return render_template('index.html')
|
| 44 |
+
|
| 45 |
+
@app.route('/api/upload', methods=['POST'])
|
| 46 |
+
def upload_file():
|
| 47 |
+
"""Handle PDF upload and extraction"""
|
| 48 |
+
try:
|
| 49 |
+
if 'file' not in request.files:
|
| 50 |
+
return jsonify({'error': 'No file provided'}), 400
|
| 51 |
+
|
| 52 |
+
file = request.files['file']
|
| 53 |
+
|
| 54 |
+
if file.filename == '':
|
| 55 |
+
return jsonify({'error': 'No file selected'}), 400
|
| 56 |
+
|
| 57 |
+
if not file.filename.lower().endswith('.pdf'):
|
| 58 |
+
return jsonify({'error': 'Only PDF files are allowed'}), 400
|
| 59 |
+
|
| 60 |
+
# Save file temporarily
|
| 61 |
+
filename = secure_filename(file.filename)
|
| 62 |
+
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
|
| 63 |
+
file.save(filepath)
|
| 64 |
+
|
| 65 |
+
try:
|
| 66 |
+
# Extract lab results
|
| 67 |
+
print("π Extracting lab results from PDF...")
|
| 68 |
+
extractor = LabReportExtractor()
|
| 69 |
+
results = extractor.extract_from_pdf(filepath)
|
| 70 |
+
|
| 71 |
+
if not results:
|
| 72 |
+
return jsonify({'error': 'No lab results found in PDF. Please make sure your PDF contains a valid lab report with test names, values, and reference ranges.'}), 400
|
| 73 |
+
|
| 74 |
+
print(f"β
Extracted {len(results)} results")
|
| 75 |
+
|
| 76 |
+
# Convert to JSON-serializable format
|
| 77 |
+
results_data = [
|
| 78 |
+
{
|
| 79 |
+
'test_name': r.test_name,
|
| 80 |
+
'value': r.value,
|
| 81 |
+
'unit': r.unit,
|
| 82 |
+
'reference_range': r.reference_range,
|
| 83 |
+
'status': r.status
|
| 84 |
+
}
|
| 85 |
+
for r in results
|
| 86 |
+
]
|
| 87 |
+
|
| 88 |
+
# Generate a unique session ID
|
| 89 |
+
session_id = str(uuid.uuid4())
|
| 90 |
+
|
| 91 |
+
# Store results in memory with session ID
|
| 92 |
+
session_storage[session_id] = {
|
| 93 |
+
'results': results_data,
|
| 94 |
+
'results_objects': results # Store LabResult objects for later use
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
print(f"πΎ Stored results in session: {session_id}")
|
| 98 |
+
|
| 99 |
+
return jsonify({
|
| 100 |
+
'success': True,
|
| 101 |
+
'session_id': session_id,
|
| 102 |
+
'results': results_data,
|
| 103 |
+
'count': len(results_data)
|
| 104 |
+
})
|
| 105 |
+
|
| 106 |
+
finally:
|
| 107 |
+
# Clean up temp file
|
| 108 |
+
if os.path.exists(filepath):
|
| 109 |
+
os.remove(filepath)
|
| 110 |
+
|
| 111 |
+
except Exception as e:
|
| 112 |
+
print(f"β Upload error: {str(e)}")
|
| 113 |
+
return jsonify({'error': str(e)}), 500
|
| 114 |
+
|
| 115 |
+
@app.route('/api/explain', methods=['POST'])
|
| 116 |
+
def explain_results():
|
| 117 |
+
"""Generate explanations for lab results"""
|
| 118 |
+
try:
|
| 119 |
+
data = request.get_json()
|
| 120 |
+
session_id = data.get('session_id')
|
| 121 |
+
|
| 122 |
+
if not session_id or session_id not in session_storage:
|
| 123 |
+
return jsonify({'error': 'Session expired. Please upload your PDF again.'}), 400
|
| 124 |
+
|
| 125 |
+
# Get results from storage
|
| 126 |
+
session_data = session_storage[session_id]
|
| 127 |
+
results = session_data['results_objects']
|
| 128 |
+
|
| 129 |
+
print(f"π§ Generating explanations for {len(results)} results...")
|
| 130 |
+
|
| 131 |
+
# Generate explanations
|
| 132 |
+
rag = get_rag_system()
|
| 133 |
+
explanations = {}
|
| 134 |
+
|
| 135 |
+
for i, result in enumerate(results):
|
| 136 |
+
print(f" Explaining {i+1}/{len(results)}: {result.test_name}...")
|
| 137 |
+
try:
|
| 138 |
+
explanation = rag.explain_result(result)
|
| 139 |
+
explanations[result.test_name] = explanation
|
| 140 |
+
except Exception as e:
|
| 141 |
+
print(f" Error: {str(e)}")
|
| 142 |
+
explanations[result.test_name] = f"Unable to generate explanation: {str(e)}"
|
| 143 |
+
|
| 144 |
+
# Store explanations in session
|
| 145 |
+
session_storage[session_id]['explanations'] = explanations
|
| 146 |
+
|
| 147 |
+
print("β
All explanations generated")
|
| 148 |
+
|
| 149 |
+
return jsonify({
|
| 150 |
+
'success': True,
|
| 151 |
+
'explanations': explanations
|
| 152 |
+
})
|
| 153 |
+
|
| 154 |
+
except Exception as e:
|
| 155 |
+
print(f"β Explanation error: {str(e)}")
|
| 156 |
+
return jsonify({'error': str(e)}), 500
|
| 157 |
+
|
| 158 |
+
@app.route('/api/ask', methods=['POST'])
|
| 159 |
+
def ask_question():
|
| 160 |
+
"""Answer follow-up questions"""
|
| 161 |
+
try:
|
| 162 |
+
data = request.get_json()
|
| 163 |
+
question = data.get('question', '').strip()
|
| 164 |
+
session_id = data.get('session_id')
|
| 165 |
+
|
| 166 |
+
if not question:
|
| 167 |
+
return jsonify({'error': 'No question provided'}), 400
|
| 168 |
+
|
| 169 |
+
if not session_id or session_id not in session_storage:
|
| 170 |
+
return jsonify({'error': 'Session expired. Please upload your PDF again.'}), 400
|
| 171 |
+
|
| 172 |
+
# Get results from storage
|
| 173 |
+
session_data = session_storage[session_id]
|
| 174 |
+
results = session_data['results_objects']
|
| 175 |
+
|
| 176 |
+
print(f"π¬ Answering question: {question}")
|
| 177 |
+
|
| 178 |
+
# Get answer
|
| 179 |
+
rag = get_rag_system()
|
| 180 |
+
answer = rag.answer_followup_question(question, results)
|
| 181 |
+
|
| 182 |
+
print("β
Answer generated")
|
| 183 |
+
|
| 184 |
+
return jsonify({
|
| 185 |
+
'success': True,
|
| 186 |
+
'question': question,
|
| 187 |
+
'answer': answer
|
| 188 |
+
})
|
| 189 |
+
|
| 190 |
+
except Exception as e:
|
| 191 |
+
print(f"β Question error: {str(e)}")
|
| 192 |
+
return jsonify({'error': str(e)}), 500
|
| 193 |
+
|
| 194 |
+
@app.route('/api/summary', methods=['POST'])
|
| 195 |
+
def get_summary():
|
| 196 |
+
"""Generate overall summary"""
|
| 197 |
+
try:
|
| 198 |
+
data = request.get_json()
|
| 199 |
+
session_id = data.get('session_id')
|
| 200 |
+
|
| 201 |
+
if not session_id or session_id not in session_storage:
|
| 202 |
+
return jsonify({'error': 'Session expired. Please upload your PDF again.'}), 400
|
| 203 |
+
|
| 204 |
+
# Get results from storage
|
| 205 |
+
session_data = session_storage[session_id]
|
| 206 |
+
results = session_data['results_objects']
|
| 207 |
+
|
| 208 |
+
print("π Generating summary...")
|
| 209 |
+
|
| 210 |
+
# Generate summary
|
| 211 |
+
rag = get_rag_system()
|
| 212 |
+
summary = rag.generate_summary(results)
|
| 213 |
+
|
| 214 |
+
# Calculate statistics
|
| 215 |
+
stats = {
|
| 216 |
+
'total': len(results),
|
| 217 |
+
'normal': sum(1 for r in results if r.status == 'normal'),
|
| 218 |
+
'high': sum(1 for r in results if r.status == 'high'),
|
| 219 |
+
'low': sum(1 for r in results if r.status == 'low'),
|
| 220 |
+
'unknown': sum(1 for r in results if r.status == 'unknown')
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
print(f"β
Summary generated - Stats: {stats}")
|
| 224 |
+
|
| 225 |
+
return jsonify({
|
| 226 |
+
'success': True,
|
| 227 |
+
'summary': summary,
|
| 228 |
+
'stats': stats
|
| 229 |
+
})
|
| 230 |
+
|
| 231 |
+
except Exception as e:
|
| 232 |
+
print(f"β Summary error: {str(e)}")
|
| 233 |
+
return jsonify({'error': str(e)}), 500
|
| 234 |
+
|
| 235 |
+
@app.route('/api/health', methods=['GET'])
|
| 236 |
+
def health_check():
|
| 237 |
+
"""Health check endpoint"""
|
| 238 |
+
return jsonify({
|
| 239 |
+
'status': 'healthy',
|
| 240 |
+
'active_sessions': len(session_storage)
|
| 241 |
+
})
|
| 242 |
+
|
| 243 |
+
@app.errorhandler(413)
|
| 244 |
+
def request_entity_too_large(error):
|
| 245 |
+
return jsonify({'error': 'File too large. Maximum size is 16MB.'}), 413
|
| 246 |
+
|
| 247 |
+
@app.errorhandler(500)
|
| 248 |
+
def internal_error(error):
|
| 249 |
+
return jsonify({'error': 'Internal server error'}), 500
|
| 250 |
+
|
| 251 |
+
if __name__ == '__main__':
|
| 252 |
+
print("π Starting Lab Report Decoder...")
|
| 253 |
+
print("π Server will be available at http://0.0.0.0:7860")
|
| 254 |
+
app.run(debug=True, host='0.0.0.0', port=7860)
|