File size: 8,449 Bytes
369b6c9 fa156f3 ca81162 fa156f3 369b6c9 348ea76 369b6c9 | 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 | """Work Programme & Cash Flow module endpoints — saved history + per-project
credit consumption. The tools themselves run fully client-side; this only
persists results and enforces the 50-AED-per-project entitlement."""
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from typing import Optional, Dict, Any
from api.auth import get_current_user
from utils.features import (
FEATURES, get_credits, count_projects, consume_credit,
save_module_project, list_module_projects, get_module_project, delete_module_project,
)
router = APIRouter()
class SaveModuleReq(BaseModel):
project_id: Optional[int] = None
name: str
config: Dict[str, Any] = {}
summary: Dict[str, Any] = {}
def _check_feature(feature: str):
if feature not in FEATURES:
raise HTTPException(status_code=404, detail="Unknown feature.")
@router.get("/{feature}")
async def list_history(feature: str, current_user: dict = Depends(get_current_user)):
_check_feature(feature)
return list_module_projects(current_user["id"], feature)
@router.get("/{feature}/item/{project_id}")
async def get_one(feature: str, project_id: int, current_user: dict = Depends(get_current_user)):
_check_feature(feature)
proj = get_module_project(current_user["id"], feature, project_id)
if not proj:
raise HTTPException(status_code=404, detail="Not found.")
return proj
@router.post("/{feature}/save")
async def save(feature: str, req: SaveModuleReq, current_user: dict = Depends(get_current_user)):
_check_feature(feature)
is_admin = current_user.get("role") == "admin"
is_new = not req.project_id
user_id = current_user["id"]
if is_new and not is_admin:
from utils.usage import check_limit, EVENT_PROJECT
ok, msg = check_limit(current_user, EVENT_PROJECT, feature=feature)
if not ok:
raise HTTPException(status_code=403, detail=msg)
pid = save_module_project(user_id, feature, req.name, req.config, req.summary, req.project_id)
if pid is None:
raise HTTPException(status_code=500, detail="Failed to save.")
if is_new and not is_admin:
from utils.usage import settle_project_creation
settle_project_creation(current_user, feature, {"project_id": pid, "project_name": req.name})
return {"message": "Saved.", "project_id": pid}
@router.delete("/{feature}/item/{project_id}")
async def delete_one(feature: str, project_id: int, current_user: dict = Depends(get_current_user)):
_check_feature(feature)
ok, err = delete_module_project(current_user["id"], feature, project_id)
if not ok:
raise HTTPException(status_code=500, detail=f"Delete failed: {err}")
return {"message": "Deleted."}
import json
import re
from fastapi import UploadFile, File
@router.post("/spec/prefill")
async def spec_prefill(file: UploadFile = File(...), current_user: dict = Depends(get_current_user)):
filename = file.filename or ""
try:
content = await file.read()
if filename.lower().endswith(".pdf"):
import fitz
doc = fitz.open(stream=content, filetype="pdf")
text = ""
for page in doc:
text += page.get_text()
else:
text = content.decode("utf-8", errors="ignore")
except Exception as e:
raise HTTPException(status_code=400, detail=f"Failed to read file: {str(e)}")
text = text.strip()
if not text:
return {"_success": False, "_error": "The specification file has no readable text."}
from utils.key_manager import get_key_manager
manager = get_key_manager()
api_key, current_model = manager.get_key_and_model()
if not api_key or api_key == "NO_API_KEY_FOUND":
return {"_success": False, "_error": "No Gemini API key found. Please check Settings."}
valid_types = ["G+0", "G+1", "G+2", "G+3", "G+4", "G+M", "G+M+1", "G+M+2", "B+G", "B+G+1", "B+G+2", "B+G+3"]
valid_emirates = ["Dubai", "Abu Dhabi", "Sharjah", "Ajman", "RAK", "UAQ", "Fujairah", "Other"]
prompt = f"""You are a UAE quantity-surveying assistant. Read the villa project SPECIFICATION text and extract only the values you can determine WITH CONFIDENCE. This is for a private villa — there is no fire-fighting or fire-alarm scope.
Return STRICT JSON: {{ "suggestions": {{ ... }}, "confidence": "high|medium|low", "notes": "short note" }}.
Inside "suggestions", include ONLY keys you found; OMIT anything not stated in the text (do not guess). Use these keys and types:
- villaType: one of {", ".join(valid_types)} (floor configuration).
- buaPerFloor: number (m² built-up area of a typical floor).
- basementArea, mezzanineArea: number (m², only if present).
- projectName, clientName, plotNumber, consultantName, contractorName: string.
- location: one of {", ".join(valid_emirates)}.
- hasPool, hasRoofGarden, hasExternalLandscape, hasBoundaryWall, hasDemolition: boolean.
- complexityFactor: 0.8 (simple), 1.0 (standard) or 1.2 (complex/high-end finishes).
- contractValueAed: number (AED).
- advancePaymentPct, retentionPct, vatPct: number (percent).
- certificationPeriodDays, paymentPeriodDays: number (days).
- defectsLiabilityMonths: number (months).
SPECIFICATION:
{text[:24000]}"""
try:
from google import genai
from google.genai import types
client = genai.Client(api_key=api_key)
response = client.models.generate_content(
model=current_model,
contents=prompt,
config=types.GenerateContentConfig(
response_mime_type="application/json",
temperature=0.0
)
)
raw = response.text.strip()
raw = re.sub(r"```json|```", "", raw).strip()
parsed = json.loads(raw)
suggestions = parsed.get("suggestions", {})
sanitized = {}
def to_num(v):
try:
return float(v)
except (TypeError, ValueError):
return None
def to_bool(v):
if isinstance(v, bool):
return v
if str(v).lower() in ("true", "1", "yes"):
return True
if str(v).lower() in ("false", "0", "no"):
return False
return None
# Strings
for k in ("projectName", "clientName", "plotNumber", "consultantName", "contractorName"):
if k in suggestions and suggestions[k]:
sanitized[k] = str(suggestions[k]).strip()
# Numbers
for k in ("buaPerFloor", "basementArea", "mezzanineArea", "contractValueAed",
"advancePaymentPct", "retentionPct", "vatPct", "certificationPeriodDays",
"paymentPeriodDays", "defectsLiabilityMonths"):
if k in suggestions:
val = to_num(suggestions[k])
if val is not None and val >= 0:
sanitized[k] = val
# Booleans
for k in ("hasPool", "hasRoofGarden", "hasExternalLandscape", "hasBoundaryWall", "hasDemolition"):
if k in suggestions:
val = to_bool(suggestions[k])
if val is not None:
sanitized[k] = val
# Specials
if "villaType" in suggestions:
vt = str(suggestions["villaType"]).upper().strip()
if vt in valid_types:
sanitized["villaType"] = vt
if "location" in suggestions:
loc = str(suggestions["location"]).strip()
matching = [e for e in valid_emirates if e.lower() == loc.lower()]
if matching:
sanitized["location"] = matching[0]
if "complexityFactor" in suggestions:
cf = to_num(suggestions["complexityFactor"])
if cf is not None:
sanitized["complexityFactor"] = 0.8 if cf < 0.9 else (1.2 if cf > 1.1 else 1.0)
return {
"_success": True,
"suggestions": sanitized,
"confidence": parsed.get("confidence", "low"),
"notes": parsed.get("notes", "")
}
except Exception as e:
return {"_success": False, "_error": f"AI extraction failed: {str(e)}"}
|