-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin_server.py
More file actions
84 lines (73 loc) · 3.54 KB
/
admin_server.py
File metadata and controls
84 lines (73 loc) · 3.54 KB
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
from fastapi import FastAPI, Form, HTTPException, Request, Query
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
import asyncio
import os
import sys
# Add the backend directory to the Python path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), 'backend')))
from backend.app.services.legal_scraper import legal_scraper
from backend.app.models.database import db_manager, LawUnit
from backend.app.utils.logger import setup_logger
app = FastAPI()
logger = setup_logger(log_dir="backend/logs")
class LawTextInput(BaseModel):
legal_text: str
category: str = "Manual"
db_key: str
@app.get("/admin/databases")
async def get_databases():
return JSONResponse(content=db_manager.get_db_names())
@app.post("/admin/add_law")
async def add_law(law_input: LawTextInput):
logger.info(f"Received request to add new law from text to database '{law_input.db_key}'.")
law_data = await legal_scraper.digest_text_to_law(law_input.legal_text, category=law_input.category)
if not law_data:
raise HTTPException(status_code=400, detail="Could not digest legal text. The AI may have failed to extract structured data.")
db = db_manager.get_session(law_input.db_key)
try:
existing_law = db.query(LawUnit).filter(LawUnit.law_id == law_data.get("law_id")).first()
if existing_law:
logger.info(f"Law with ID {law_data.get('law_id')} already exists in '{law_input.db_key}'. Updating.")
for key, value in law_data.items():
setattr(existing_law, key, value)
else:
new_law = LawUnit(**law_data)
db.add(new_law)
db.commit()
logger.info(f"Successfully added/updated law in '{law_input.db_key}': {law_data.get('law_id')}")
# Redirect includes the db_key to stay on the same report page
return RedirectResponse(url=f"/database_report.html?db_key={law_input.db_key}", status_code=303)
except Exception as e:
db.rollback()
logger.error(f"Database error while adding law to '{law_input.db_key}': {e}")
raise HTTPException(status_code=500, detail="Database operation failed.")
finally:
db.close()
@app.delete("/admin/delete_law/{law_id}")
async def delete_law(law_id: str, db_key: str = Query(...)):
logger.info(f"Received request to delete law with ID: {law_id} from database '{db_key}'")
db = db_manager.get_session(db_key)
try:
law_to_delete = db.query(LawUnit).filter(LawUnit.law_id == law_id).first()
if law_to_delete:
db.delete(law_to_delete)
db.commit()
logger.info(f"Successfully deleted law with ID: {law_id} from '{db_key}'")
return {"status": "success", "message": f"Law ID {law_id} deleted."}
else:
logger.warning(f"Attempted to delete non-existent law ID: {law_id} from '{db_key}'")
raise HTTPException(status_code=404, detail=f"Law with ID '{law_id}' not found.")
except Exception as e:
db.rollback()
logger.error(f"Database error while deleting law from '{db_key}': {e}")
raise HTTPException(status_code=500, detail="Database operation failed.")
finally:
db.close()
# Mount the main directory to serve database_report.html and other static files
app.mount("/", StaticFiles(directory=".", html=True), name="static")
if __name__ == "__main__":
import uvicorn
logger.info("Starting Admin Server on http://localhost:8001")
uvicorn.run(app, host="0.0.0.0", port=8001)