| from fastapi import APIRouter, Request
|
| from fastapi.responses import HTMLResponse
|
| from db.database import SessionLocal
|
| from db.models import Prediction, TrainingSession
|
| from jinja2 import Template
|
|
|
| router = APIRouter()
|
|
|
| dashboard_template = """
|
| <!DOCTYPE html>
|
| <html lang='en'>
|
| <head>
|
| <meta charset='UTF-8'>
|
| <title>Hallucination Detection Dashboard</title>
|
| <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css'>
|
| </head>
|
| <body>
|
| <div class='container mt-4'>
|
| <h1>Hallucination Detection Dashboard</h1>
|
| <div class='row'>
|
| <div class='col-md-4'>
|
| <div class='card mb-3'>
|
| <div class='card-body'>
|
| <h5 class='card-title'>Total Predictions</h5>
|
| <p class='card-text'>{{ total_predictions }}</p>
|
| </div>
|
| </div>
|
| </div>
|
| <div class='col-md-4'>
|
| <div class='card mb-3'>
|
| <div class='card-body'>
|
| <h5 class='card-title'>Hallucination Rate</h5>
|
| <p class='card-text'>{{ hallucination_rate }}%</p>
|
| </div>
|
| </div>
|
| </div>
|
| <div class='col-md-4'>
|
| <div class='card mb-3'>
|
| <div class='card-body'>
|
| <h5 class='card-title'>Avg Confidence</h5>
|
| <p class='card-text'>{{ avg_confidence }}</p>
|
| </div>
|
| </div>
|
| </div>
|
| </div>
|
| <h3>Recent Predictions</h3>
|
| <table class='table table-striped'>
|
| <thead><tr><th>Time</th><th>Prompt</th><th>Response</th><th>Question</th><th>Result</th><th>Confidence</th></tr></thead>
|
| <tbody>
|
| {% for p in recent_predictions %}
|
| <tr>
|
| <td>{{ p.created_at }}</td>
|
| <td>{{ p.prompt[:30] }}...</td>
|
| <td>{{ p.response[:30] }}...</td>
|
| <td>{{ p.question[:30] }}...</td>
|
| <td>{{ 'Hallucination' if p.is_hallucination else 'Factual' }}</td>
|
| <td>{{ p.confidence_score }}</td>
|
| </tr>
|
| {% endfor %}
|
| </tbody>
|
| </table>
|
| </div>
|
| </body>
|
| </html>
|
| """
|
|
|
| @router.get("/", response_class=HTMLResponse)
|
| def dashboard(request: Request):
|
| db = SessionLocal()
|
| preds = db.query(Prediction).order_by(Prediction.created_at.desc()).limit(20).all()
|
| total = db.query(Prediction).count()
|
| halluc = db.query(Prediction).filter(Prediction.is_hallucination == True).count()
|
| avg_conf = db.query(Prediction.confidence_score).all()
|
| avg_conf = round(sum([x[0] for x in avg_conf])/len(avg_conf), 2) if avg_conf else 0
|
| halluc_rate = round((halluc/total)*100, 2) if total else 0
|
| html = Template(dashboard_template).render(
|
| total_predictions=total,
|
| hallucination_rate=halluc_rate,
|
| avg_confidence=avg_conf,
|
| recent_predictions=preds
|
| )
|
| db.close()
|
| return HTMLResponse(content=html)
|
|
|