Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -28,13 +28,112 @@ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
|
|
| 28 |
from reportlab.lib.enums import TA_LEFT, TA_JUSTIFY
|
| 29 |
from reportlab.pdfgen import canvas
|
| 30 |
|
| 31 |
-
# Configure logging
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
logging.basicConfig(
|
| 33 |
level=logging.INFO,
|
| 34 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 35 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
logger = logging.getLogger(__name__)
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
# Validate dependencies on startup
|
| 39 |
def validate_dependencies():
|
| 40 |
"""Validate that all required dependencies are available"""
|
|
@@ -641,11 +740,217 @@ async def root():
|
|
| 641 |
|
| 642 |
@app.get("/health")
|
| 643 |
async def health():
|
| 644 |
-
"""
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 649 |
|
| 650 |
|
| 651 |
@app.post("/humanize", response_model=ParaphraseResponse)
|
|
@@ -798,21 +1103,212 @@ async def humanize_document(
|
|
| 798 |
Returns:
|
| 799 |
Processed document in requested format
|
| 800 |
"""
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 804 |
|
| 805 |
request_start_time = time.time()
|
| 806 |
-
logger.info(f"📄 Document processing request: file={file.filename}, "
|
| 807 |
-
f"style={style}, format={output_format}")
|
| 808 |
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 814 |
|
| 815 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 816 |
try:
|
| 817 |
if filename.endswith(".txt"):
|
| 818 |
text = content.decode('utf-8')
|
|
|
|
| 28 |
from reportlab.lib.enums import TA_LEFT, TA_JUSTIFY
|
| 29 |
from reportlab.pdfgen import canvas
|
| 30 |
|
| 31 |
+
# Configure enhanced logging with structured format
|
| 32 |
+
import uuid
|
| 33 |
+
from datetime import datetime
|
| 34 |
+
|
| 35 |
+
class StructuredFormatter(logging.Formatter):
|
| 36 |
+
"""Custom formatter for structured logging"""
|
| 37 |
+
|
| 38 |
+
def format(self, record):
|
| 39 |
+
# Create structured log entry
|
| 40 |
+
log_entry = {
|
| 41 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 42 |
+
"level": record.levelname,
|
| 43 |
+
"component": record.name,
|
| 44 |
+
"message": record.getMessage(),
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
# Add request ID if available
|
| 48 |
+
if hasattr(record, 'request_id'):
|
| 49 |
+
log_entry["request_id"] = record.request_id
|
| 50 |
+
|
| 51 |
+
# Add extra context if available
|
| 52 |
+
if hasattr(record, 'context'):
|
| 53 |
+
log_entry["context"] = record.context
|
| 54 |
+
|
| 55 |
+
# Add error details if it's an error
|
| 56 |
+
if record.levelno >= logging.ERROR and record.exc_info:
|
| 57 |
+
log_entry["error_type"] = record.exc_info[0].__name__ if record.exc_info[0] else None
|
| 58 |
+
log_entry["stack_trace"] = self.formatException(record.exc_info) if record.exc_info else None
|
| 59 |
+
|
| 60 |
+
return json.dumps(log_entry)
|
| 61 |
+
|
| 62 |
+
# Configure logging with structured format
|
| 63 |
logging.basicConfig(
|
| 64 |
level=logging.INFO,
|
| 65 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 66 |
)
|
| 67 |
+
|
| 68 |
+
# Create structured logger for API requests
|
| 69 |
+
structured_handler = logging.StreamHandler()
|
| 70 |
+
structured_handler.setFormatter(StructuredFormatter())
|
| 71 |
+
api_logger = logging.getLogger("api_requests")
|
| 72 |
+
api_logger.addHandler(structured_handler)
|
| 73 |
+
api_logger.setLevel(logging.INFO)
|
| 74 |
+
|
| 75 |
logger = logging.getLogger(__name__)
|
| 76 |
|
| 77 |
+
# Error tracking utilities
|
| 78 |
+
class ErrorTracker:
|
| 79 |
+
"""Track and log errors with context"""
|
| 80 |
+
|
| 81 |
+
@staticmethod
|
| 82 |
+
def log_request(request_data: dict, request_id: str = None) -> str:
|
| 83 |
+
"""Log incoming request with unique ID"""
|
| 84 |
+
if not request_id:
|
| 85 |
+
request_id = str(uuid.uuid4())[:8]
|
| 86 |
+
|
| 87 |
+
api_logger.info(
|
| 88 |
+
"Incoming request",
|
| 89 |
+
extra={
|
| 90 |
+
"request_id": request_id,
|
| 91 |
+
"context": {
|
| 92 |
+
"endpoint": request_data.get("endpoint"),
|
| 93 |
+
"method": request_data.get("method"),
|
| 94 |
+
"content_length": request_data.get("content_length", 0),
|
| 95 |
+
"user_agent": request_data.get("user_agent", "unknown")
|
| 96 |
+
}
|
| 97 |
+
}
|
| 98 |
+
)
|
| 99 |
+
return request_id
|
| 100 |
+
|
| 101 |
+
@staticmethod
|
| 102 |
+
def log_processing_stage(stage: str, data: dict, request_id: str = None):
|
| 103 |
+
"""Log processing stage with timing and context"""
|
| 104 |
+
api_logger.info(
|
| 105 |
+
f"Processing stage: {stage}",
|
| 106 |
+
extra={
|
| 107 |
+
"request_id": request_id,
|
| 108 |
+
"context": {
|
| 109 |
+
"stage": stage,
|
| 110 |
+
**data
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
@staticmethod
|
| 116 |
+
def capture_error(error: Exception, context: dict, request_id: str = None) -> str:
|
| 117 |
+
"""Capture error with full context"""
|
| 118 |
+
error_id = str(uuid.uuid4())[:8]
|
| 119 |
+
|
| 120 |
+
api_logger.error(
|
| 121 |
+
f"Error occurred: {str(error)}",
|
| 122 |
+
exc_info=True,
|
| 123 |
+
extra={
|
| 124 |
+
"request_id": request_id,
|
| 125 |
+
"context": {
|
| 126 |
+
"error_id": error_id,
|
| 127 |
+
"error_type": type(error).__name__,
|
| 128 |
+
"error_message": str(error),
|
| 129 |
+
**context
|
| 130 |
+
}
|
| 131 |
+
}
|
| 132 |
+
)
|
| 133 |
+
return error_id
|
| 134 |
+
|
| 135 |
+
error_tracker = ErrorTracker()
|
| 136 |
+
|
| 137 |
# Validate dependencies on startup
|
| 138 |
def validate_dependencies():
|
| 139 |
"""Validate that all required dependencies are available"""
|
|
|
|
| 740 |
|
| 741 |
@app.get("/health")
|
| 742 |
async def health():
|
| 743 |
+
"""Enhanced health check endpoint with comprehensive system status"""
|
| 744 |
+
import psutil
|
| 745 |
+
import sys
|
| 746 |
+
|
| 747 |
+
try:
|
| 748 |
+
# Basic model status
|
| 749 |
+
model_loaded = model is not None and tokenizer is not None
|
| 750 |
+
|
| 751 |
+
# System information
|
| 752 |
+
memory_info = psutil.virtual_memory()
|
| 753 |
+
cpu_percent = psutil.cpu_percent(interval=1)
|
| 754 |
+
|
| 755 |
+
# Test model inference if loaded
|
| 756 |
+
inference_working = False
|
| 757 |
+
inference_time = None
|
| 758 |
+
if model_loaded:
|
| 759 |
+
try:
|
| 760 |
+
start_time = time.time()
|
| 761 |
+
test_result = await process_single_chunk("Test sentence for health check.", ParaphraseStyle.neutral)
|
| 762 |
+
inference_time = time.time() - start_time
|
| 763 |
+
inference_working = len(test_result.output) > 0
|
| 764 |
+
except Exception as e:
|
| 765 |
+
logger.warning(f"Health check inference failed: {e}")
|
| 766 |
+
inference_working = False
|
| 767 |
+
|
| 768 |
+
# Determine overall status
|
| 769 |
+
if model_loaded and inference_working:
|
| 770 |
+
overall_status = "healthy"
|
| 771 |
+
elif model_loaded:
|
| 772 |
+
overall_status = "degraded"
|
| 773 |
+
else:
|
| 774 |
+
overall_status = "unhealthy"
|
| 775 |
+
|
| 776 |
+
health_data = {
|
| 777 |
+
"status": overall_status,
|
| 778 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 779 |
+
"model_status": {
|
| 780 |
+
"loaded": model_loaded,
|
| 781 |
+
"inference_working": inference_working,
|
| 782 |
+
"inference_time_ms": round(inference_time * 1000, 2) if inference_time else None
|
| 783 |
+
},
|
| 784 |
+
"system_info": {
|
| 785 |
+
"python_version": sys.version.split()[0],
|
| 786 |
+
"memory_usage_mb": round(memory_info.used / 1024 / 1024, 2),
|
| 787 |
+
"memory_available_mb": round(memory_info.available / 1024 / 1024, 2),
|
| 788 |
+
"memory_percent": memory_info.percent,
|
| 789 |
+
"cpu_percent": cpu_percent
|
| 790 |
+
},
|
| 791 |
+
"dependencies": {
|
| 792 |
+
"torch_version": torch.__version__,
|
| 793 |
+
"transformers_available": True, # If we got here, transformers is available
|
| 794 |
+
"reportlab_available": True, # If we got here, reportlab is available
|
| 795 |
+
"docx_available": True # If we got here, python-docx is available
|
| 796 |
+
}
|
| 797 |
+
}
|
| 798 |
+
|
| 799 |
+
# Log health check
|
| 800 |
+
logger.info(f"Health check completed: {overall_status}")
|
| 801 |
+
|
| 802 |
+
return health_data
|
| 803 |
+
|
| 804 |
+
except Exception as e:
|
| 805 |
+
error_id = error_tracker.capture_error(e, {"endpoint": "/health"})
|
| 806 |
+
return {
|
| 807 |
+
"status": "unhealthy",
|
| 808 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 809 |
+
"error": f"Health check failed: {str(e)}",
|
| 810 |
+
"error_id": error_id
|
| 811 |
+
}
|
| 812 |
+
|
| 813 |
+
@app.get("/model-status")
|
| 814 |
+
async def model_status():
|
| 815 |
+
"""Detailed model status endpoint"""
|
| 816 |
+
try:
|
| 817 |
+
model_loaded = model is not None and tokenizer is not None
|
| 818 |
+
|
| 819 |
+
if not model_loaded:
|
| 820 |
+
return {
|
| 821 |
+
"loaded": False,
|
| 822 |
+
"error": "Model or tokenizer not loaded",
|
| 823 |
+
"timestamp": datetime.utcnow().isoformat() + "Z"
|
| 824 |
+
}
|
| 825 |
+
|
| 826 |
+
# Test inference with timing
|
| 827 |
+
test_texts = [
|
| 828 |
+
"Short test.",
|
| 829 |
+
"This is a medium length test sentence for model verification.",
|
| 830 |
+
"This is a longer test sentence that will help us understand how the model performs with more substantial input text for comprehensive testing."
|
| 831 |
+
]
|
| 832 |
+
|
| 833 |
+
inference_results = []
|
| 834 |
+
for i, text in enumerate(test_texts):
|
| 835 |
+
try:
|
| 836 |
+
start_time = time.time()
|
| 837 |
+
result = await process_single_chunk(text, ParaphraseStyle.neutral)
|
| 838 |
+
inference_time = time.time() - start_time
|
| 839 |
+
|
| 840 |
+
inference_results.append({
|
| 841 |
+
"test_case": i + 1,
|
| 842 |
+
"input_length": len(text),
|
| 843 |
+
"output_length": len(result.output),
|
| 844 |
+
"inference_time_ms": round(inference_time * 1000, 2),
|
| 845 |
+
"success": True
|
| 846 |
+
})
|
| 847 |
+
except Exception as e:
|
| 848 |
+
inference_results.append({
|
| 849 |
+
"test_case": i + 1,
|
| 850 |
+
"input_length": len(text),
|
| 851 |
+
"success": False,
|
| 852 |
+
"error": str(e)
|
| 853 |
+
})
|
| 854 |
+
|
| 855 |
+
return {
|
| 856 |
+
"loaded": True,
|
| 857 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 858 |
+
"model_info": {
|
| 859 |
+
"model_name": "Vamsi/T5_Paraphrase_Paws",
|
| 860 |
+
"device": "cpu"
|
| 861 |
+
},
|
| 862 |
+
"inference_tests": inference_results,
|
| 863 |
+
"performance_summary": {
|
| 864 |
+
"successful_tests": sum(1 for r in inference_results if r["success"]),
|
| 865 |
+
"total_tests": len(inference_results),
|
| 866 |
+
"avg_inference_time_ms": round(
|
| 867 |
+
sum(r.get("inference_time_ms", 0) for r in inference_results if r["success"]) /
|
| 868 |
+
max(1, sum(1 for r in inference_results if r["success"])), 2
|
| 869 |
+
)
|
| 870 |
+
}
|
| 871 |
+
}
|
| 872 |
+
|
| 873 |
+
except Exception as e:
|
| 874 |
+
error_id = error_tracker.capture_error(e, {"endpoint": "/model-status"})
|
| 875 |
+
return {
|
| 876 |
+
"loaded": False,
|
| 877 |
+
"error": str(e),
|
| 878 |
+
"error_id": error_id,
|
| 879 |
+
"timestamp": datetime.utcnow().isoformat() + "Z"
|
| 880 |
+
}
|
| 881 |
+
|
| 882 |
+
@app.get("/environment")
|
| 883 |
+
async def environment_info():
|
| 884 |
+
"""System environment information endpoint"""
|
| 885 |
+
try:
|
| 886 |
+
import psutil
|
| 887 |
+
import sys
|
| 888 |
+
import platform
|
| 889 |
+
|
| 890 |
+
# Get package versions
|
| 891 |
+
package_versions = {}
|
| 892 |
+
try:
|
| 893 |
+
import torch
|
| 894 |
+
package_versions["torch"] = torch.__version__
|
| 895 |
+
except ImportError:
|
| 896 |
+
package_versions["torch"] = "not_installed"
|
| 897 |
+
|
| 898 |
+
try:
|
| 899 |
+
import transformers
|
| 900 |
+
package_versions["transformers"] = transformers.__version__
|
| 901 |
+
except ImportError:
|
| 902 |
+
package_versions["transformers"] = "not_installed"
|
| 903 |
+
|
| 904 |
+
try:
|
| 905 |
+
import reportlab
|
| 906 |
+
package_versions["reportlab"] = reportlab.Version
|
| 907 |
+
except ImportError:
|
| 908 |
+
package_versions["reportlab"] = "not_installed"
|
| 909 |
+
|
| 910 |
+
try:
|
| 911 |
+
import docx
|
| 912 |
+
package_versions["python-docx"] = "installed" # python-docx doesn't have __version__
|
| 913 |
+
except ImportError:
|
| 914 |
+
package_versions["python-docx"] = "not_installed"
|
| 915 |
+
|
| 916 |
+
# System information
|
| 917 |
+
memory_info = psutil.virtual_memory()
|
| 918 |
+
disk_info = psutil.disk_usage('/')
|
| 919 |
+
|
| 920 |
+
return {
|
| 921 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 922 |
+
"system": {
|
| 923 |
+
"platform": platform.platform(),
|
| 924 |
+
"python_version": sys.version,
|
| 925 |
+
"architecture": platform.architecture()[0],
|
| 926 |
+
"processor": platform.processor() or "unknown"
|
| 927 |
+
},
|
| 928 |
+
"memory": {
|
| 929 |
+
"total_gb": round(memory_info.total / 1024 / 1024 / 1024, 2),
|
| 930 |
+
"available_gb": round(memory_info.available / 1024 / 1024 / 1024, 2),
|
| 931 |
+
"used_gb": round(memory_info.used / 1024 / 1024 / 1024, 2),
|
| 932 |
+
"percent_used": memory_info.percent
|
| 933 |
+
},
|
| 934 |
+
"disk": {
|
| 935 |
+
"total_gb": round(disk_info.total / 1024 / 1024 / 1024, 2),
|
| 936 |
+
"free_gb": round(disk_info.free / 1024 / 1024 / 1024, 2),
|
| 937 |
+
"used_gb": round(disk_info.used / 1024 / 1024 / 1024, 2),
|
| 938 |
+
"percent_used": round((disk_info.used / disk_info.total) * 100, 2)
|
| 939 |
+
},
|
| 940 |
+
"packages": package_versions,
|
| 941 |
+
"environment_variables": {
|
| 942 |
+
"PORT": os.getenv("PORT", "not_set"),
|
| 943 |
+
"PYTHONPATH": os.getenv("PYTHONPATH", "not_set")
|
| 944 |
+
}
|
| 945 |
+
}
|
| 946 |
+
|
| 947 |
+
except Exception as e:
|
| 948 |
+
error_id = error_tracker.capture_error(e, {"endpoint": "/environment"})
|
| 949 |
+
return {
|
| 950 |
+
"error": str(e),
|
| 951 |
+
"error_id": error_id,
|
| 952 |
+
"timestamp": datetime.utcnow().isoformat() + "Z"
|
| 953 |
+
}
|
| 954 |
|
| 955 |
|
| 956 |
@app.post("/humanize", response_model=ParaphraseResponse)
|
|
|
|
| 1103 |
Returns:
|
| 1104 |
Processed document in requested format
|
| 1105 |
"""
|
| 1106 |
+
# Generate request ID for tracking
|
| 1107 |
+
request_id = error_tracker.log_request({
|
| 1108 |
+
"endpoint": "/humanize-document",
|
| 1109 |
+
"method": "POST",
|
| 1110 |
+
"filename": file.filename,
|
| 1111 |
+
"content_type": file.content_type,
|
| 1112 |
+
"style": style,
|
| 1113 |
+
"output_format": output_format
|
| 1114 |
+
})
|
| 1115 |
|
| 1116 |
request_start_time = time.time()
|
|
|
|
|
|
|
| 1117 |
|
| 1118 |
+
try:
|
| 1119 |
+
# Check model availability
|
| 1120 |
+
if model is None or tokenizer is None:
|
| 1121 |
+
error_tracker.capture_error(
|
| 1122 |
+
Exception("Model not loaded"),
|
| 1123 |
+
{"stage": "model_check", "request_id": request_id}
|
| 1124 |
+
)
|
| 1125 |
+
raise HTTPException(status_code=503, detail="Model not loaded")
|
| 1126 |
+
|
| 1127 |
+
error_tracker.log_processing_stage("file_upload", {
|
| 1128 |
+
"filename": file.filename,
|
| 1129 |
+
"content_type": file.content_type,
|
| 1130 |
+
"style": style,
|
| 1131 |
+
"output_format": output_format
|
| 1132 |
+
}, request_id)
|
| 1133 |
+
|
| 1134 |
+
# Read file content
|
| 1135 |
+
content = await file.read()
|
| 1136 |
+
filename = file.filename.lower() if file.filename else ""
|
| 1137 |
+
|
| 1138 |
+
error_tracker.log_processing_stage("file_read", {
|
| 1139 |
+
"file_size_bytes": len(content),
|
| 1140 |
+
"filename": filename
|
| 1141 |
+
}, request_id)
|
| 1142 |
+
|
| 1143 |
+
# Extract text based on file type
|
| 1144 |
+
text_extraction_start = time.time()
|
| 1145 |
+
try:
|
| 1146 |
+
if filename.endswith(".txt"):
|
| 1147 |
+
text = content.decode('utf-8')
|
| 1148 |
+
error_tracker.log_processing_stage("text_extraction", {
|
| 1149 |
+
"file_type": "txt",
|
| 1150 |
+
"extracted_length": len(text),
|
| 1151 |
+
"extraction_time_ms": round((time.time() - text_extraction_start) * 1000, 2)
|
| 1152 |
+
}, request_id)
|
| 1153 |
+
elif filename.endswith(".docx"):
|
| 1154 |
+
# Parse DOCX file using python-docx
|
| 1155 |
+
try:
|
| 1156 |
+
from docx import Document
|
| 1157 |
+
doc_file = io.BytesIO(content)
|
| 1158 |
+
doc = Document(doc_file)
|
| 1159 |
+
text = "\n".join([paragraph.text for paragraph in doc.paragraphs if paragraph.text.strip()])
|
| 1160 |
+
if not text.strip():
|
| 1161 |
+
error_tracker.capture_error(
|
| 1162 |
+
ValueError("DOCX file appears to be empty"),
|
| 1163 |
+
{"stage": "docx_parsing", "filename": filename},
|
| 1164 |
+
request_id
|
| 1165 |
+
)
|
| 1166 |
+
raise HTTPException(status_code=400, detail="DOCX file appears to be empty")
|
| 1167 |
+
|
| 1168 |
+
error_tracker.log_processing_stage("text_extraction", {
|
| 1169 |
+
"file_type": "docx",
|
| 1170 |
+
"extracted_length": len(text),
|
| 1171 |
+
"paragraph_count": len(doc.paragraphs),
|
| 1172 |
+
"extraction_time_ms": round((time.time() - text_extraction_start) * 1000, 2)
|
| 1173 |
+
}, request_id)
|
| 1174 |
+
except Exception as docx_error:
|
| 1175 |
+
error_tracker.capture_error(docx_error, {
|
| 1176 |
+
"stage": "docx_parsing",
|
| 1177 |
+
"filename": filename,
|
| 1178 |
+
"file_size": len(content)
|
| 1179 |
+
}, request_id)
|
| 1180 |
+
raise HTTPException(status_code=400, detail=f"Could not parse DOCX file: {str(docx_error)}")
|
| 1181 |
+
else:
|
| 1182 |
+
# Try to decode as text
|
| 1183 |
+
text = content.decode('utf-8')
|
| 1184 |
+
error_tracker.log_processing_stage("text_extraction", {
|
| 1185 |
+
"file_type": "generic",
|
| 1186 |
+
"extracted_length": len(text),
|
| 1187 |
+
"extraction_time_ms": round((time.time() - text_extraction_start) * 1000, 2)
|
| 1188 |
+
}, request_id)
|
| 1189 |
+
except HTTPException:
|
| 1190 |
+
# Re-raise HTTP exceptions
|
| 1191 |
+
raise
|
| 1192 |
+
except Exception as e:
|
| 1193 |
+
error_tracker.capture_error(e, {
|
| 1194 |
+
"stage": "text_extraction",
|
| 1195 |
+
"filename": filename,
|
| 1196 |
+
"file_size": len(content)
|
| 1197 |
+
}, request_id)
|
| 1198 |
+
raise HTTPException(status_code=400, detail=f"Could not process file: {str(e)}")
|
| 1199 |
+
|
| 1200 |
+
# Validate extracted text
|
| 1201 |
+
word_count = len(text.split())
|
| 1202 |
+
if not text or word_count < MIN_WORDS:
|
| 1203 |
+
error_tracker.capture_error(
|
| 1204 |
+
ValueError(f"Invalid text extracted: {word_count} words (minimum: {MIN_WORDS})"),
|
| 1205 |
+
{"stage": "text_validation", "word_count": word_count, "text_length": len(text)},
|
| 1206 |
+
request_id
|
| 1207 |
+
)
|
| 1208 |
+
raise HTTPException(status_code=400, detail="Could not extract valid text")
|
| 1209 |
+
|
| 1210 |
+
error_tracker.log_processing_stage("text_validation", {
|
| 1211 |
+
"text_length": len(text),
|
| 1212 |
+
"word_count": word_count,
|
| 1213 |
+
"validation_passed": True
|
| 1214 |
+
}, request_id)
|
| 1215 |
+
|
| 1216 |
+
# Process the text
|
| 1217 |
+
processing_start_time = time.time()
|
| 1218 |
+
error_tracker.log_processing_stage("text_processing_start", {
|
| 1219 |
+
"input_length": len(text),
|
| 1220 |
+
"word_count": word_count,
|
| 1221 |
+
"style": style
|
| 1222 |
+
}, request_id)
|
| 1223 |
+
|
| 1224 |
+
result = await process_long_text(text, style)
|
| 1225 |
+
paraphrased = result.output
|
| 1226 |
+
processing_time = time.time() - processing_start_time
|
| 1227 |
+
|
| 1228 |
+
error_tracker.log_processing_stage("text_processing_complete", {
|
| 1229 |
+
"output_length": len(paraphrased),
|
| 1230 |
+
"processing_time_ms": round(processing_time * 1000, 2)
|
| 1231 |
+
}, request_id)
|
| 1232 |
+
|
| 1233 |
+
# Return in requested format
|
| 1234 |
+
if output_format == "json":
|
| 1235 |
+
total_time = time.time() - request_start_time
|
| 1236 |
+
error_tracker.log_processing_stage("response_json", {
|
| 1237 |
+
"total_time_ms": round(total_time * 1000, 2)
|
| 1238 |
+
}, request_id)
|
| 1239 |
+
return {"output": paraphrased, "style": style}
|
| 1240 |
+
|
| 1241 |
+
elif output_format == "pdf":
|
| 1242 |
+
file_start_time = time.time()
|
| 1243 |
+
error_tracker.log_processing_stage("pdf_generation_start", {
|
| 1244 |
+
"input_length": len(paraphrased)
|
| 1245 |
+
}, request_id)
|
| 1246 |
+
|
| 1247 |
+
pdf_bytes = create_pdf(paraphrased)
|
| 1248 |
+
file_time = time.time() - file_start_time
|
| 1249 |
+
total_time = time.time() - request_start_time
|
| 1250 |
+
|
| 1251 |
+
error_tracker.log_processing_stage("pdf_generation_complete", {
|
| 1252 |
+
"pdf_size_bytes": len(pdf_bytes),
|
| 1253 |
+
"generation_time_ms": round(file_time * 1000, 2),
|
| 1254 |
+
"total_time_ms": round(total_time * 1000, 2)
|
| 1255 |
+
}, request_id)
|
| 1256 |
+
|
| 1257 |
+
return Response(
|
| 1258 |
+
content=pdf_bytes,
|
| 1259 |
+
media_type="application/pdf",
|
| 1260 |
+
headers={
|
| 1261 |
+
"Content-Disposition": "attachment; filename=humanized.pdf",
|
| 1262 |
+
"Content-Length": str(len(pdf_bytes)),
|
| 1263 |
+
"Cache-Control": "no-cache, no-store, must-revalidate"
|
| 1264 |
+
}
|
| 1265 |
+
)
|
| 1266 |
+
|
| 1267 |
+
elif output_format == "docx":
|
| 1268 |
+
file_start_time = time.time()
|
| 1269 |
+
error_tracker.log_processing_stage("docx_generation_start", {
|
| 1270 |
+
"input_length": len(paraphrased)
|
| 1271 |
+
}, request_id)
|
| 1272 |
+
|
| 1273 |
+
docx_bytes = create_docx(paraphrased)
|
| 1274 |
+
file_time = time.time() - file_start_time
|
| 1275 |
+
total_time = time.time() - request_start_time
|
| 1276 |
+
|
| 1277 |
+
error_tracker.log_processing_stage("docx_generation_complete", {
|
| 1278 |
+
"docx_size_bytes": len(docx_bytes),
|
| 1279 |
+
"generation_time_ms": round(file_time * 1000, 2),
|
| 1280 |
+
"total_time_ms": round(total_time * 1000, 2)
|
| 1281 |
+
}, request_id)
|
| 1282 |
+
|
| 1283 |
+
return Response(
|
| 1284 |
+
content=docx_bytes,
|
| 1285 |
+
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
| 1286 |
+
headers={
|
| 1287 |
+
"Content-Disposition": "attachment; filename=humanized.docx",
|
| 1288 |
+
"Content-Length": str(len(docx_bytes)),
|
| 1289 |
+
"Cache-Control": "no-cache, no-store, must-revalidate"
|
| 1290 |
+
}
|
| 1291 |
+
)
|
| 1292 |
+
|
| 1293 |
+
else:
|
| 1294 |
+
error_tracker.capture_error(
|
| 1295 |
+
ValueError(f"Invalid output format: {output_format}"),
|
| 1296 |
+
{"stage": "format_validation", "output_format": output_format},
|
| 1297 |
+
request_id
|
| 1298 |
+
)
|
| 1299 |
+
raise HTTPException(status_code=400, detail="Invalid output format")
|
| 1300 |
|
| 1301 |
+
except HTTPException:
|
| 1302 |
+
# Re-raise HTTP exceptions (they're already logged)
|
| 1303 |
+
raise
|
| 1304 |
+
except Exception as e:
|
| 1305 |
+
# Capture any unexpected errors
|
| 1306 |
+
error_id = error_tracker.capture_error(e, {
|
| 1307 |
+
"stage": "unexpected_error",
|
| 1308 |
+
"request_id": request_id,
|
| 1309 |
+
"total_time_ms": round((time.time() - request_start_time) * 1000, 2)
|
| 1310 |
+
}, request_id)
|
| 1311 |
+
raise HTTPException(status_code=500, detail=f"Internal server error (ID: {error_id})")
|
| 1312 |
try:
|
| 1313 |
if filename.endswith(".txt"):
|
| 1314 |
text = content.decode('utf-8')
|