Spaces:
Sleeping
Sleeping
fix3
Browse files
main.py
CHANGED
|
@@ -3,35 +3,30 @@ import uuid
|
|
| 3 |
import json
|
| 4 |
import asyncio
|
| 5 |
import urllib.parse
|
| 6 |
-
from typing import List, Literal
|
| 7 |
from fastapi import FastAPI, HTTPException, Security, Depends
|
| 8 |
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 9 |
from pydantic import BaseModel
|
| 10 |
import httpx
|
| 11 |
import aio_pika
|
| 12 |
|
| 13 |
-
# --- Инициализация приложения ---
|
| 14 |
app = FastAPI(title="Tender AI API")
|
| 15 |
security = HTTPBearer()
|
| 16 |
|
| 17 |
-
# --- Переменные окружения ---
|
| 18 |
SUPABASE_URL = os.getenv("SUPABASE_URL", "")
|
| 19 |
SUPABASE_KEY = os.getenv("SUPABASE_KEY", "")
|
| 20 |
CLOUDAMQP_URL = os.getenv("CLOUDAMQP_URL", "")
|
| 21 |
API_TOKEN = os.getenv("API_TOKEN", "my_secret_token_for_gpt")
|
| 22 |
|
| 23 |
-
# --- Pydantic модели ---
|
| 24 |
class DocumentInput(BaseModel):
|
| 25 |
url: str
|
| 26 |
name: str
|
| 27 |
|
| 28 |
class AnalyzeRequest(BaseModel):
|
| 29 |
client_name: str = "Неизвестный клиент"
|
| 30 |
-
|
| 31 |
-
mode: Literal["analytics", "estimate"] = "analytics"
|
| 32 |
documents: List[DocumentInput]
|
| 33 |
|
| 34 |
-
# --- Класс для прямой работы с базой без багов Supabase-py ---
|
| 35 |
class SupabaseAsync:
|
| 36 |
def __init__(self, url: str, key: str):
|
| 37 |
self.base_url = url.rstrip("/")
|
|
@@ -43,22 +38,20 @@ class SupabaseAsync:
|
|
| 43 |
}
|
| 44 |
|
| 45 |
async def _request(self, method: str, endpoint: str, **kwargs):
|
| 46 |
-
# Отключаем http2 (http2=False) для стабильности
|
| 47 |
async with httpx.AsyncClient(http2=False, timeout=30.0) as client:
|
| 48 |
url = f"{self.base_url}/rest/v1/{endpoint}"
|
| 49 |
last_err = None
|
| 50 |
-
for _ in range(3):
|
| 51 |
try:
|
| 52 |
resp = await client.request(method, url, headers=self.headers, **kwargs)
|
| 53 |
resp.raise_for_status()
|
| 54 |
-
if resp.content:
|
| 55 |
-
return resp.json()
|
| 56 |
return {}
|
| 57 |
except httpx.HTTPStatusError as e:
|
| 58 |
raise Exception(f"БД вернула ошибку {e.response.status_code}: {e.response.text}")
|
| 59 |
except Exception as e:
|
| 60 |
last_err = e
|
| 61 |
-
await asyncio.sleep(1)
|
| 62 |
raise last_err
|
| 63 |
|
| 64 |
async def get_client_by_name(self, name: str):
|
|
@@ -81,98 +74,79 @@ class SupabaseAsync:
|
|
| 81 |
return await self._request("PATCH", f"calculations?id=eq.{calc_id}", json=data)
|
| 82 |
|
| 83 |
|
| 84 |
-
# --- 1. ЗАЩИТА ---
|
| 85 |
def verify_token(credentials: HTTPAuthorizationCredentials = Security(security)):
|
| 86 |
if credentials.credentials != API_TOKEN:
|
| 87 |
raise HTTPException(status_code=401, detail="Invalid token")
|
| 88 |
return credentials.credentials
|
| 89 |
|
| 90 |
-
#
|
| 91 |
-
async def send_to_queue(task_id: str,
|
| 92 |
connection = await aio_pika.connect_robust(CLOUDAMQP_URL)
|
| 93 |
async with connection:
|
| 94 |
channel = await connection.channel()
|
| 95 |
queue = await channel.declare_queue("tender_tasks", durable=True)
|
| 96 |
message_body = json.dumps({
|
| 97 |
"task_id": task_id,
|
| 98 |
-
"
|
| 99 |
-
"mode": mode
|
| 100 |
}).encode("utf-8")
|
| 101 |
await channel.default_exchange.publish(
|
| 102 |
-
aio_pika.Message(
|
| 103 |
-
body=message_body,
|
| 104 |
-
delivery_mode=aio_pika.DeliveryMode.PERSISTENT
|
| 105 |
-
),
|
| 106 |
routing_key=queue.name,
|
| 107 |
)
|
| 108 |
|
| 109 |
-
# --- 3. ЭНДПОИНТ АНАЛИЗА ---
|
| 110 |
@app.post("/api/v1/tenders/analyze", dependencies=[Depends(verify_token)])
|
| 111 |
async def analyze_tenders(request: AnalyzeRequest):
|
| 112 |
try:
|
| 113 |
db = SupabaseAsync(SUPABASE_URL, SUPABASE_KEY)
|
| 114 |
|
| 115 |
-
# Умный поиск или создание клиента
|
| 116 |
clients = await db.get_client_by_name(request.client_name)
|
| 117 |
-
if clients:
|
| 118 |
-
db_client_id = clients[0]["id"]
|
| 119 |
else:
|
| 120 |
new_client = await db.create_client(request.client_name)
|
| 121 |
db_client_id = new_client[0]["id"]
|
| 122 |
|
| 123 |
calculation_id = str(uuid.uuid4())
|
| 124 |
-
|
| 125 |
-
# Создаем расчет
|
| 126 |
await db.create_calculation({
|
| 127 |
"id": calculation_id,
|
| 128 |
"client_id": db_client_id,
|
| 129 |
"status": "pending"
|
| 130 |
})
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
| 134 |
|
| 135 |
-
|
| 136 |
-
task_id
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
"status": "pending"
|
| 143 |
-
})
|
| 144 |
-
tasks_to_queue.append((task_id, doc.url, request.mode))
|
| 145 |
-
|
| 146 |
-
# Записываем документы в БД
|
| 147 |
-
await db.create_documents(documents_data)
|
| 148 |
|
| 149 |
-
# Отправляем в очередь
|
| 150 |
-
|
| 151 |
-
await send_to_queue(task_id, doc_url, mode)
|
| 152 |
|
| 153 |
-
return {
|
| 154 |
-
"batch_id": calculation_id,
|
| 155 |
-
"message": f"Принято {len(request.documents)} документов в обработку. Режим: {request.mode}"
|
| 156 |
-
}
|
| 157 |
|
| 158 |
except Exception as e:
|
| 159 |
print(f"[API ERROR] {str(e)}")
|
| 160 |
raise HTTPException(status_code=500, detail=f"Ошибка БД или Очереди: {str(e)}")
|
| 161 |
|
| 162 |
-
# --- 4. ЭНДПОИНТ СТАТУСА ---
|
| 163 |
@app.get("/api/v1/tenders/status/{batch_id}", dependencies=[Depends(verify_token)])
|
| 164 |
async def check_status(batch_id: str):
|
| 165 |
try:
|
| 166 |
db = SupabaseAsync(SUPABASE_URL, SUPABASE_KEY)
|
| 167 |
documents = await db.get_documents_by_calc(batch_id)
|
| 168 |
|
| 169 |
-
if not documents:
|
| 170 |
-
raise HTTPException(status_code=404, detail="Расчет не найден")
|
| 171 |
|
| 172 |
statuses = [doc.get("status", "pending") for doc in documents]
|
| 173 |
|
| 174 |
if "error" in statuses:
|
| 175 |
-
return {"status": "error", "message": "Ошибка при обработке
|
| 176 |
|
| 177 |
if "pending" in statuses or "processing" in statuses:
|
| 178 |
return {"status": "processing", "message": "Документы еще обрабатываются..."}
|
|
@@ -184,12 +158,9 @@ async def check_status(batch_id: str):
|
|
| 184 |
task_id = doc.get("task_id")
|
| 185 |
|
| 186 |
if isinstance(extracted, str):
|
| 187 |
-
try:
|
| 188 |
-
|
| 189 |
-
except json.JSONDecodeError:
|
| 190 |
-
pass
|
| 191 |
|
| 192 |
-
# Защита от одинаковых имен документов
|
| 193 |
result_key = doc_name
|
| 194 |
if result_key in aggregated_result:
|
| 195 |
suffix = task_id or str(uuid.uuid4())
|
|
@@ -198,19 +169,12 @@ async def check_status(batch_id: str):
|
|
| 198 |
aggregated_result[result_key] = extracted or {}
|
| 199 |
|
| 200 |
try:
|
| 201 |
-
await db.update_calculation(batch_id, {
|
| 202 |
-
|
| 203 |
-
})
|
| 204 |
-
except Exception as db_err:
|
| 205 |
-
print(f"[API WARNING] Не смог обновить calculations: {db_err}")
|
| 206 |
|
| 207 |
-
return {
|
| 208 |
-
"status": "completed",
|
| 209 |
-
"data": aggregated_result
|
| 210 |
-
}
|
| 211 |
|
| 212 |
-
except HTTPException:
|
| 213 |
-
raise
|
| 214 |
except Exception as e:
|
| 215 |
print(f"[API ERROR] 500: {str(e)}")
|
| 216 |
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
| 3 |
import json
|
| 4 |
import asyncio
|
| 5 |
import urllib.parse
|
| 6 |
+
from typing import List, Literal
|
| 7 |
from fastapi import FastAPI, HTTPException, Security, Depends
|
| 8 |
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 9 |
from pydantic import BaseModel
|
| 10 |
import httpx
|
| 11 |
import aio_pika
|
| 12 |
|
|
|
|
| 13 |
app = FastAPI(title="Tender AI API")
|
| 14 |
security = HTTPBearer()
|
| 15 |
|
|
|
|
| 16 |
SUPABASE_URL = os.getenv("SUPABASE_URL", "")
|
| 17 |
SUPABASE_KEY = os.getenv("SUPABASE_KEY", "")
|
| 18 |
CLOUDAMQP_URL = os.getenv("CLOUDAMQP_URL", "")
|
| 19 |
API_TOKEN = os.getenv("API_TOKEN", "my_secret_token_for_gpt")
|
| 20 |
|
|
|
|
| 21 |
class DocumentInput(BaseModel):
|
| 22 |
url: str
|
| 23 |
name: str
|
| 24 |
|
| 25 |
class AnalyzeRequest(BaseModel):
|
| 26 |
client_name: str = "Неизвестный клиент"
|
| 27 |
+
mode: Literal["analytics", "estimate"] = "analytics"
|
|
|
|
| 28 |
documents: List[DocumentInput]
|
| 29 |
|
|
|
|
| 30 |
class SupabaseAsync:
|
| 31 |
def __init__(self, url: str, key: str):
|
| 32 |
self.base_url = url.rstrip("/")
|
|
|
|
| 38 |
}
|
| 39 |
|
| 40 |
async def _request(self, method: str, endpoint: str, **kwargs):
|
|
|
|
| 41 |
async with httpx.AsyncClient(http2=False, timeout=30.0) as client:
|
| 42 |
url = f"{self.base_url}/rest/v1/{endpoint}"
|
| 43 |
last_err = None
|
| 44 |
+
for _ in range(3):
|
| 45 |
try:
|
| 46 |
resp = await client.request(method, url, headers=self.headers, **kwargs)
|
| 47 |
resp.raise_for_status()
|
| 48 |
+
if resp.content: return resp.json()
|
|
|
|
| 49 |
return {}
|
| 50 |
except httpx.HTTPStatusError as e:
|
| 51 |
raise Exception(f"БД вернула ошибку {e.response.status_code}: {e.response.text}")
|
| 52 |
except Exception as e:
|
| 53 |
last_err = e
|
| 54 |
+
await asyncio.sleep(1)
|
| 55 |
raise last_err
|
| 56 |
|
| 57 |
async def get_client_by_name(self, name: str):
|
|
|
|
| 74 |
return await self._request("PATCH", f"calculations?id=eq.{calc_id}", json=data)
|
| 75 |
|
| 76 |
|
|
|
|
| 77 |
def verify_token(credentials: HTTPAuthorizationCredentials = Security(security)):
|
| 78 |
if credentials.credentials != API_TOKEN:
|
| 79 |
raise HTTPException(status_code=401, detail="Invalid token")
|
| 80 |
return credentials.credentials
|
| 81 |
|
| 82 |
+
# ИЗМЕНЕНИЕ: Теперь принимаем список URL (document_urls)
|
| 83 |
+
async def send_to_queue(task_id: str, document_urls: list, mode: str):
|
| 84 |
connection = await aio_pika.connect_robust(CLOUDAMQP_URL)
|
| 85 |
async with connection:
|
| 86 |
channel = await connection.channel()
|
| 87 |
queue = await channel.declare_queue("tender_tasks", durable=True)
|
| 88 |
message_body = json.dumps({
|
| 89 |
"task_id": task_id,
|
| 90 |
+
"document_urls": document_urls,
|
| 91 |
+
"mode": mode,
|
| 92 |
}).encode("utf-8")
|
| 93 |
await channel.default_exchange.publish(
|
| 94 |
+
aio_pika.Message(body=message_body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT),
|
|
|
|
|
|
|
|
|
|
| 95 |
routing_key=queue.name,
|
| 96 |
)
|
| 97 |
|
|
|
|
| 98 |
@app.post("/api/v1/tenders/analyze", dependencies=[Depends(verify_token)])
|
| 99 |
async def analyze_tenders(request: AnalyzeRequest):
|
| 100 |
try:
|
| 101 |
db = SupabaseAsync(SUPABASE_URL, SUPABASE_KEY)
|
| 102 |
|
|
|
|
| 103 |
clients = await db.get_client_by_name(request.client_name)
|
| 104 |
+
if clients: db_client_id = clients[0]["id"]
|
|
|
|
| 105 |
else:
|
| 106 |
new_client = await db.create_client(request.client_name)
|
| 107 |
db_client_id = new_client[0]["id"]
|
| 108 |
|
| 109 |
calculation_id = str(uuid.uuid4())
|
|
|
|
|
|
|
| 110 |
await db.create_calculation({
|
| 111 |
"id": calculation_id,
|
| 112 |
"client_id": db_client_id,
|
| 113 |
"status": "pending"
|
| 114 |
})
|
| 115 |
|
| 116 |
+
# ИЗМЕНЕНИЕ: Создаем ЕДИНУЮ задачу для всего пакета документов
|
| 117 |
+
task_id = str(uuid.uuid4())
|
| 118 |
+
combined_names = " + ".join([d.name for d in request.documents])
|
| 119 |
+
urls = [d.url for d in request.documents]
|
| 120 |
|
| 121 |
+
await db.create_documents([{
|
| 122 |
+
"task_id": task_id,
|
| 123 |
+
"calculation_id": calculation_id,
|
| 124 |
+
"document_url": json.dumps(urls), # Сохраняем массив ссылок как JSON строку
|
| 125 |
+
"document_name": combined_names,
|
| 126 |
+
"status": "pending"
|
| 127 |
+
}])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
+
# Отправляем весь массив в очередь одним сообщением
|
| 130 |
+
await send_to_queue(task_id, urls, request.mode)
|
|
|
|
| 131 |
|
| 132 |
+
return {"batch_id": calculation_id, "message": f"Принято {len(urls)} документов как единый пакет. Режим: {request.mode}"}
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
except Exception as e:
|
| 135 |
print(f"[API ERROR] {str(e)}")
|
| 136 |
raise HTTPException(status_code=500, detail=f"Ошибка БД или Очереди: {str(e)}")
|
| 137 |
|
|
|
|
| 138 |
@app.get("/api/v1/tenders/status/{batch_id}", dependencies=[Depends(verify_token)])
|
| 139 |
async def check_status(batch_id: str):
|
| 140 |
try:
|
| 141 |
db = SupabaseAsync(SUPABASE_URL, SUPABASE_KEY)
|
| 142 |
documents = await db.get_documents_by_calc(batch_id)
|
| 143 |
|
| 144 |
+
if not documents: raise HTTPException(status_code=404, detail="Расчет не найден")
|
|
|
|
| 145 |
|
| 146 |
statuses = [doc.get("status", "pending") for doc in documents]
|
| 147 |
|
| 148 |
if "error" in statuses:
|
| 149 |
+
return {"status": "error", "message": "Ошибка при обработке документов"}
|
| 150 |
|
| 151 |
if "pending" in statuses or "processing" in statuses:
|
| 152 |
return {"status": "processing", "message": "Документы еще обрабатываются..."}
|
|
|
|
| 158 |
task_id = doc.get("task_id")
|
| 159 |
|
| 160 |
if isinstance(extracted, str):
|
| 161 |
+
try: extracted = json.loads(extracted)
|
| 162 |
+
except json.JSONDecodeError: pass
|
|
|
|
|
|
|
| 163 |
|
|
|
|
| 164 |
result_key = doc_name
|
| 165 |
if result_key in aggregated_result:
|
| 166 |
suffix = task_id or str(uuid.uuid4())
|
|
|
|
| 169 |
aggregated_result[result_key] = extracted or {}
|
| 170 |
|
| 171 |
try:
|
| 172 |
+
await db.update_calculation(batch_id, {"status": "completed"})
|
| 173 |
+
except: pass
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
+
return {"status": "completed", "data": aggregated_result}
|
|
|
|
|
|
|
|
|
|
| 176 |
|
| 177 |
+
except HTTPException: raise
|
|
|
|
| 178 |
except Exception as e:
|
| 179 |
print(f"[API ERROR] 500: {str(e)}")
|
| 180 |
raise HTTPException(status_code=500, detail=str(e))
|