Spaces:
Sleeping
Sleeping
File size: 8,614 Bytes
c09e844 4bc008b c09e844 59e37d1 c09e844 59e37d1 c09e844 |
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 |
"""
Prediction Router
Handles single and batch predictions
"""
import io
import csv
from typing import List, Dict
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File, Form
from fastapi.responses import StreamingResponse
from sqlalchemy.orm import Session
from app.database import get_db
from app.models import User, PredictionHistory
from app.schemas import (
SinglePredictionRequest,
SinglePredictionResponse,
BatchPredictionResponse,
PredictionHistoryResponse,
PDFReportRequest
)
from app.services.auth_service import get_current_user
from app.services.ml_service import get_ml_service, MLPredictionService
from app.services.visualization_service import get_viz_service, VisualizationService
from app.services.report_service import get_report_service, ReportService
router = APIRouter()
@router.post("/single", response_model=SinglePredictionResponse)
async def predict_single(
request: SinglePredictionRequest,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db),
ml_service: MLPredictionService = Depends(get_ml_service)
):
"""
Predict rating for a single comment
- **product_name**: Name of the product
- **comment**: Vietnamese product review text
Returns predicted rating (1-5 stars) with confidence score
"""
# Make prediction
prediction = ml_service.predict_single(request.comment)
# Save to history
history = PredictionHistory(
user_id=current_user.id,
product_name=request.product_name,
comment=request.comment,
predicted_rating=prediction['rating'],
confidence_score=prediction['confidence'],
prediction_type='single'
)
db.add(history)
db.commit()
return {
"predicted_rating": prediction['rating'],
"confidence_score": prediction['confidence'],
"comment": request.comment
}
@router.post("/batch", response_model=BatchPredictionResponse)
async def predict_batch(
product_name: str = Form(None),
file: UploadFile = File(...),
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db),
ml_service: MLPredictionService = Depends(get_ml_service),
viz_service: VisualizationService = Depends(get_viz_service),
report_service: ReportService = Depends(get_report_service)
):
"""
Predict ratings for batch of comments from CSV file
- **product_name**: Name of the product
- **file**: CSV file with 'Comment' column
Returns predictions with visualization data (wordcloud, distribution chart)
"""
# Validate file type
if not file.filename.endswith('.csv'):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="File must be a CSV"
)
try:
# Read CSV file
contents = await file.read()
csv_file = io.StringIO(contents.decode('utf-8'))
reader = csv.DictReader(csv_file)
# Check for Comment column
if 'Comment' not in reader.fieldnames:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="CSV must contain 'Comment' column"
)
# Extract comments
comments = []
for row in reader:
if row.get('Comment', '').strip():
comments.append(row['Comment'].strip())
if not comments:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="No valid comments found in CSV"
)
# Make batch predictions
predictions = ml_service.predict_batch(comments)
final_product_name = product_name if product_name else "Unknown Product"
# Save to history
for pred in predictions:
history = PredictionHistory(
user_id=current_user.id,
product_name=final_product_name,
comment=pred['text'],
predicted_rating=pred['rating'],
confidence_score=pred['confidence'],
prediction_type='batch'
)
db.add(history)
db.commit()
# Calculate rating distribution
ratings = [p['rating'] for p in predictions]
distribution = viz_service.calculate_rating_distribution(ratings)
# Generate word cloud
wordcloud_filename = f"wordcloud_{current_user.username}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
wordcloud_url = viz_service.generate_wordcloud(comments, wordcloud_filename)
# Prepare results for CSV download
results = []
for pred in predictions:
results.append({
'Comment': pred['text'],
'Predicted_Rating': pred['rating'],
'Confidence': pred['confidence']
})
# Generate PDF report
pdf_filename = f"report_{current_user.username}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
pdf_content = report_service.generate_pdf_report(
predictions=predictions,
distribution=distribution,
wordcloud_path=wordcloud_url,
username=current_user.username,
filename=pdf_filename
)
return {
"total_predictions": len(predictions),
"rating_distribution": distribution,
"wordcloud_url": wordcloud_url,
"results": results,
"csv_download_url": f"/api/predict/download/{current_user.id}/{datetime.now().timestamp()}",
"pdf_download_url": f"/api/predict/download-pdf/{current_user.id}/{datetime.now().timestamp()}"
}
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Error processing file: {str(e)}"
)
@router.get("/history", response_model=List[PredictionHistoryResponse])
async def get_prediction_history(
limit: int = 50,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
"""
Get prediction history for current user
- **limit**: Maximum number of records to return (default: 50)
"""
history = db.query(PredictionHistory).filter(
PredictionHistory.user_id == current_user.id
).order_by(PredictionHistory.created_at.desc()).limit(limit).all()
return history
@router.post("/download-csv")
async def download_predictions_csv(
results: List[dict],
current_user: User = Depends(get_current_user)
):
"""
Download prediction results as CSV
"""
# Create CSV in memory
output = io.StringIO()
if results:
fieldnames = results[0].keys()
writer = csv.DictWriter(output, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(results)
# Reset position
output.seek(0)
# Return as streaming response
return StreamingResponse(
iter([output.getvalue()]),
media_type="text/csv",
headers={
"Content-Disposition": f"attachment; filename=predictions_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
}
)
@router.post("/download-pdf")
async def download_predictions_pdf(
request: PDFReportRequest,
current_user: User = Depends(get_current_user),
report_service: ReportService = Depends(get_report_service)
):
"""
Download prediction results as PDF report
"""
try:
pdf_content = report_service.generate_pdf_report(
predictions=request.predictions,
distribution=request.distribution,
wordcloud_path=request.wordcloud_path,
username=current_user.username
)
return StreamingResponse(
io.BytesIO(pdf_content),
media_type="application/pdf",
headers={
"Content-Disposition": f"attachment; filename=predictions_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
}
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Error generating PDF: {str(e)}"
)
|