Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -4,6 +4,7 @@ os.environ["XDG_CACHE_HOME"] = "/tmp"
|
|
4 |
os.makedirs("/tmp/matplotlib", exist_ok=True)
|
5 |
os.makedirs("/tmp/data", exist_ok=True)
|
6 |
os.makedirs("/tmp/models_cache", exist_ok=True)
|
|
|
7 |
from fastapi import FastAPI
|
8 |
import io
|
9 |
import time
|
@@ -12,6 +13,9 @@ import tempfile
|
|
12 |
import numpy as np
|
13 |
import matplotlib.pyplot as plt
|
14 |
import pdfplumber
|
|
|
|
|
|
|
15 |
import spacy
|
16 |
import torch
|
17 |
import sqlite3
|
@@ -491,6 +495,8 @@ def process_audio_to_text(audio_file_path):
|
|
491 |
|
492 |
def extract_named_entities(text):
|
493 |
"""Extracts named entities from legal text."""
|
|
|
|
|
494 |
max_length = 10000
|
495 |
entities = []
|
496 |
for i in range(0, len(text), max_length):
|
@@ -519,6 +525,8 @@ def extract_context_for_risk_terms(text, risk_keywords, window=1):
|
|
519 |
"""
|
520 |
Extracts and summarizes the context around risk terms.
|
521 |
"""
|
|
|
|
|
522 |
doc = nlp(text)
|
523 |
sentences = list(doc.sents)
|
524 |
risk_contexts = {category: [] for category in risk_keywords}
|
@@ -1406,7 +1414,122 @@ async def paypal_webhook(request: Request):
|
|
1406 |
logger.error(f"Webhook processing error: {str(e)}")
|
1407 |
# Return 200 even on error to acknowledge receipt to PayPal
|
1408 |
return {"status": "error", "message": str(e)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1409 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1410 |
# Add this to your startup code
|
1411 |
@app.on_event("startup")
|
1412 |
async def startup_event():
|
|
|
4 |
os.makedirs("/tmp/matplotlib", exist_ok=True)
|
5 |
os.makedirs("/tmp/data", exist_ok=True)
|
6 |
os.makedirs("/tmp/models_cache", exist_ok=True)
|
7 |
+
os.makedirs("/tmp/static", exist_ok=True)
|
8 |
from fastapi import FastAPI
|
9 |
import io
|
10 |
import time
|
|
|
13 |
import numpy as np
|
14 |
import matplotlib.pyplot as plt
|
15 |
import pdfplumber
|
16 |
+
from fastapi.responses import FileResponse, HTMLResponse
|
17 |
+
import pandas as pd
|
18 |
+
import plotly.express as px
|
19 |
import spacy
|
20 |
import torch
|
21 |
import sqlite3
|
|
|
495 |
|
496 |
def extract_named_entities(text):
|
497 |
"""Extracts named entities from legal text."""
|
498 |
+
if nlp is None:
|
499 |
+
return [{"entity": "NLP model not available", "label": "N/A"}]
|
500 |
max_length = 10000
|
501 |
entities = []
|
502 |
for i in range(0, len(text), max_length):
|
|
|
525 |
"""
|
526 |
Extracts and summarizes the context around risk terms.
|
527 |
"""
|
528 |
+
if nlp is None or summarizer is None:
|
529 |
+
return {category: "NLP/summarizer model not available" for category in risk_keywords}
|
530 |
doc = nlp(text)
|
531 |
sentences = list(doc.sents)
|
532 |
risk_contexts = {category: [] for category in risk_keywords}
|
|
|
1414 |
logger.error(f"Webhook processing error: {str(e)}")
|
1415 |
# Return 200 even on error to acknowledge receipt to PayPal
|
1416 |
return {"status": "error", "message": str(e)}
|
1417 |
+
@app.get("/download_risk_chart")
|
1418 |
+
async def download_risk_chart():
|
1419 |
+
"""Generate and return a risk assessment chart as an image file."""
|
1420 |
+
try:
|
1421 |
+
risk_scores = {
|
1422 |
+
"Liability": 11,
|
1423 |
+
"Termination": 12,
|
1424 |
+
"Indemnification": 10,
|
1425 |
+
"Payment Risk": 41,
|
1426 |
+
"Insurance": 71
|
1427 |
+
}
|
1428 |
+
plt.figure(figsize=(8, 5))
|
1429 |
+
plt.bar(risk_scores.keys(), risk_scores.values(), color='red')
|
1430 |
+
plt.xlabel("Risk Categories")
|
1431 |
+
plt.ylabel("Risk Score")
|
1432 |
+
plt.title("Legal Risk Assessment")
|
1433 |
+
plt.xticks(rotation=30)
|
1434 |
+
risk_chart_path = os.path.join(STATIC_DIR, "risk_chart.png")
|
1435 |
+
plt.savefig(risk_chart_path)
|
1436 |
+
plt.close()
|
1437 |
+
return FileResponse(risk_chart_path, media_type="image/png", filename="risk_chart.png")
|
1438 |
+
except Exception as e:
|
1439 |
+
raise HTTPException(status_code=500, detail=f"Error generating risk chart: {str(e)}")
|
1440 |
+
|
1441 |
+
@app.get("/download_risk_pie_chart")
|
1442 |
+
async def download_risk_pie_chart():
|
1443 |
+
try:
|
1444 |
+
risk_scores = {
|
1445 |
+
"Liability": 11,
|
1446 |
+
"Termination": 12,
|
1447 |
+
"Indemnification": 10,
|
1448 |
+
"Payment Risk": 41,
|
1449 |
+
"Insurance": 71
|
1450 |
+
}
|
1451 |
+
plt.figure(figsize=(6, 6))
|
1452 |
+
plt.pie(risk_scores.values(), labels=risk_scores.keys(), autopct='%1.1f%%', startangle=90)
|
1453 |
+
plt.title("Legal Risk Distribution")
|
1454 |
+
pie_chart_path = os.path.join(STATIC_DIR, "risk_pie_chart.png")
|
1455 |
+
plt.savefig(pie_chart_path)
|
1456 |
+
plt.close()
|
1457 |
+
return FileResponse(pie_chart_path, media_type="image/png", filename="risk_pie_chart.png")
|
1458 |
+
except Exception as e:
|
1459 |
+
raise HTTPException(status_code=500, detail=f"Error generating pie chart: {str(e)}")
|
1460 |
|
1461 |
+
@app.get("/download_risk_radar_chart")
|
1462 |
+
async def download_risk_radar_chart():
|
1463 |
+
try:
|
1464 |
+
risk_scores = {
|
1465 |
+
"Liability": 11,
|
1466 |
+
"Termination": 12,
|
1467 |
+
"Indemnification": 10,
|
1468 |
+
"Payment Risk": 41,
|
1469 |
+
"Insurance": 71
|
1470 |
+
}
|
1471 |
+
categories = list(risk_scores.keys())
|
1472 |
+
values = list(risk_scores.values())
|
1473 |
+
categories += categories[:1]
|
1474 |
+
values += values[:1]
|
1475 |
+
angles = np.linspace(0, 2 * np.pi, len(categories), endpoint=False).tolist()
|
1476 |
+
angles += angles[:1]
|
1477 |
+
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True))
|
1478 |
+
ax.plot(angles, values, 'o-', linewidth=2)
|
1479 |
+
ax.fill(angles, values, alpha=0.25)
|
1480 |
+
ax.set_thetagrids(np.degrees(angles[:-1]), categories)
|
1481 |
+
ax.set_title("Legal Risk Radar Chart", y=1.1)
|
1482 |
+
radar_chart_path = os.path.join(STATIC_DIR, "risk_radar_chart.png")
|
1483 |
+
plt.savefig(radar_chart_path)
|
1484 |
+
plt.close()
|
1485 |
+
return FileResponse(radar_chart_path, media_type="image/png", filename="risk_radar_chart.png")
|
1486 |
+
except Exception as e:
|
1487 |
+
raise HTTPException(status_code=500, detail=f"Error generating radar chart: {str(e)}")
|
1488 |
+
|
1489 |
+
@app.get("/download_risk_trend_chart")
|
1490 |
+
async def download_risk_trend_chart():
|
1491 |
+
try:
|
1492 |
+
dates = ["2025-01-01", "2025-02-01", "2025-03-01", "2025-04-01"]
|
1493 |
+
risk_history = {
|
1494 |
+
"Liability": [10, 12, 11, 13],
|
1495 |
+
"Termination": [12, 15, 14, 13],
|
1496 |
+
"Indemnification": [9, 10, 11, 10],
|
1497 |
+
"Payment Risk": [40, 42, 41, 43],
|
1498 |
+
"Insurance": [70, 69, 71, 72]
|
1499 |
+
}
|
1500 |
+
plt.figure(figsize=(10, 6))
|
1501 |
+
for category, scores in risk_history.items():
|
1502 |
+
plt.plot(dates, scores, marker='o', label=category)
|
1503 |
+
plt.xlabel("Date")
|
1504 |
+
plt.ylabel("Risk Score")
|
1505 |
+
plt.title("Historical Legal Risk Trends")
|
1506 |
+
plt.xticks(rotation=45)
|
1507 |
+
plt.legend()
|
1508 |
+
trend_chart_path = os.path.join(STATIC_DIR, "risk_trend_chart.png")
|
1509 |
+
plt.savefig(trend_chart_path, bbox_inches="tight")
|
1510 |
+
plt.close()
|
1511 |
+
return FileResponse(trend_chart_path, media_type="image/png", filename="risk_trend_chart.png")
|
1512 |
+
except Exception as e:
|
1513 |
+
raise HTTPException(status_code=500, detail=f"Error generating trend chart: {str(e)}")
|
1514 |
+
|
1515 |
+
@app.get("/interactive_risk_chart", response_class=HTMLResponse)
|
1516 |
+
async def interactive_risk_chart():
|
1517 |
+
try:
|
1518 |
+
risk_scores = {
|
1519 |
+
"Liability": 11,
|
1520 |
+
"Termination": 12,
|
1521 |
+
"Indemnification": 10,
|
1522 |
+
"Payment Risk": 41,
|
1523 |
+
"Insurance": 71
|
1524 |
+
}
|
1525 |
+
df = pd.DataFrame({
|
1526 |
+
"Risk Category": list(risk_scores.keys()),
|
1527 |
+
"Risk Score": list(risk_scores.values())
|
1528 |
+
})
|
1529 |
+
fig = px.bar(df, x="Risk Category", y="Risk Score", title="Interactive Legal Risk Assessment")
|
1530 |
+
return fig.to_html()
|
1531 |
+
except Exception as e:
|
1532 |
+
raise HTTPException(status_code=500, detail=f"Error generating interactive chart: {str(e)}")
|
1533 |
# Add this to your startup code
|
1534 |
@app.on_event("startup")
|
1535 |
async def startup_event():
|