dataflow-server / ai_service.py
Ilirt's picture
upload
5aaca54 verified
Raw History Blame Contribute Delete
8.23 kB
"""
DataFlow Server — Mistral AI Service (OCR + AI Forecasting)
"""
import os
import json
import base64
import re
from datetime import datetime
from mistralai import Mistral
from typing import Optional
MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY", "")
def _get_client() -> Mistral:
if not MISTRAL_API_KEY or MISTRAL_API_KEY == "your_mistral_api_key_here":
raise ValueError("MISTRAL_API_KEY is not set in .env file")
return Mistral(api_key=MISTRAL_API_KEY)
# ─── OCR: Extract text and fields from document image ───
async def ocr_extract(image_bytes: bytes, filename: str) -> dict:
"""
Send image to Mistral Vision API for OCR extraction.
Returns: text, detected_type, confidence, amount, date, supplier
"""
try:
client = _get_client()
b64 = base64.b64encode(image_bytes).decode("utf-8")
ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else "jpg"
mime = {"jpg": "image/jpeg", "jpeg": "image/jpeg",
"png": "image/png", "pdf": "application/pdf"}.get(ext, "image/jpeg")
prompt = """Проанализируй этот документ и извлеки следующую информацию в JSON формате:
{
"detected_type": "invoice|receipt|contract|spec|other",
"confidence": 0.0-1.0,
"extracted_text": "полный текст документа",
"amount": number or null,
"date": "YYYY-MM-DD" or null,
"supplier": "название поставщика" or null,
"document_number": "номер документа" or null
}
Отвечай ТОЛЬКО валидным JSON без дополнительного текста."""
response = client.chat.complete(
model="pixtral-12b-2409",
messages=[{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{"type": "image_url",
"image_url": {"url": f"data:{mime};base64,{b64}"}}
]
}]
)
raw = response.choices[0].message.content.strip()
# Clean up markdown code blocks if present
raw = re.sub(r"```json\s*|\s*```", "", raw).strip()
data = json.loads(raw)
return {
"success": True,
"detected_type": data.get("detected_type", "other"),
"confidence": float(data.get("confidence", 0.5)),
"extracted_text": data.get("extracted_text", ""),
"extracted_amount": data.get("amount"),
"extracted_date": data.get("date"),
"extracted_supplier": data.get("supplier"),
"document_number": data.get("document_number"),
}
except ValueError as e:
# API key not set — return mock result
return _mock_ocr(filename)
except Exception as e:
print(f"OCR error: {e}")
return {"success": False, "error": str(e)}
def _mock_ocr(filename: str) -> dict:
"""Mock OCR result when API key is not configured."""
return {
"success": True,
"detected_type": "invoice",
"confidence": 0.85,
"extracted_text": f"[Mock OCR] Файл: {filename}\nСумма: 150 000 KZT\nДата: {datetime.now().strftime('%Y-%m-%d')}\nПоставщик: Тестовый поставщик",
"extracted_amount": 150000.0,
"extracted_date": datetime.now().strftime("%Y-%m-%d"),
"extracted_supplier": "Тестовый поставщик",
"document_number": "INV-001",
}
# ─── AI Forecast: Analyze project and predict budget risk ───
async def generate_forecast(
project_name: str,
budget: float,
spent: float,
days_elapsed: int,
total_days: int,
expense_categories: dict,
completed_tasks: int,
total_tasks: int,
) -> dict:
"""
Use Mistral to generate an intelligent budget forecast.
Returns risk analysis, probability, scenarios, recommendations.
"""
try:
client = _get_client()
budget_used_pct = (spent / budget * 100) if budget > 0 else 0
time_elapsed_pct = (days_elapsed / total_days * 100) if total_days > 0 else 0
task_completion_pct = (completed_tasks / total_tasks * 100) if total_tasks > 0 else 0
cats_str = "\n".join([f" - {k}: {v:,.0f} ₸" for k, v in expense_categories.items()])
prompt = f"""Ты финансовый аналитик проектов. Проанализируй данные проекта и создай прогноз в JSON формате.
ДАННЫЕ ПРОЕКТА:
- Название: {project_name}
- Бюджет: {budget:,.0f} ₸
- Потрачено: {spent:,.0f} ₸ ({budget_used_pct:.1f}% бюджета)
- Прошло времени: {days_elapsed} из {total_days} дней ({time_elapsed_pct:.1f}%)
- Задачи выполнены: {completed_tasks} из {total_tasks} ({task_completion_pct:.1f}%)
- Расходы по категориям:
{cats_str if cats_str else " Нет данных"}
Верни ТОЛЬКО валидный JSON без markdown:
{{
"risk_level": "green|yellow|red",
"overrun_probability": 0-100,
"optimistic_forecast": число,
"realistic_forecast": число,
"pessimistic_forecast": число,
"recommendations": ["рекомендация 1", "рекомендация 2", "рекомендация 3", "рекомендация 4"]
}}"""
response = client.chat.complete(
model="mistral-large-latest",
messages=[{"role": "user", "content": prompt}],
temperature=0.3,
)
raw = response.choices[0].message.content.strip()
raw = re.sub(r"```json\s*|\s*```", "", raw).strip()
data = json.loads(raw)
return {
"success": True,
"risk_level": data.get("risk_level", "green"),
"overrun_probability": float(data.get("overrun_probability", 0)),
"optimistic_forecast": float(data.get("optimistic_forecast", budget)),
"realistic_forecast": float(data.get("realistic_forecast", budget)),
"pessimistic_forecast": float(data.get("pessimistic_forecast", budget * 1.2)),
"recommendations": data.get("recommendations", []),
}
except ValueError:
return _mock_forecast(budget, spent)
except Exception as e:
print(f"Forecast error: {e}")
return _mock_forecast(budget, spent)
def _mock_forecast(budget: float, spent: float) -> dict:
"""Mock forecast when Mistral API key is not configured."""
ratio = spent / budget if budget > 0 else 0
if ratio < 0.4:
risk = "green"
prob = 10
elif ratio < 0.7:
risk = "yellow"
prob = 35
else:
risk = "red"
prob = 70
return {
"success": True,
"risk_level": risk,
"overrun_probability": prob,
"optimistic_forecast": budget * 0.92,
"realistic_forecast": budget * 1.04,
"pessimistic_forecast": budget * 1.18,
"recommendations": [
"Оптимизировать расходы на инфраструктуру",
"Пересмотреть приоритеты задач",
"Рассмотреть увеличение бюджета",
"Провести ревью текущих расходов",
],
}
# ─── AI Chat: Answer questions about project ───
async def ai_chat(question: str, context: str) -> str:
"""General AI assistant for project-related questions."""
try:
client = _get_client()
response = client.chat.complete(
model="mistral-small-latest",
messages=[
{"role": "system", "content": f"Ты помощник по управлению проектами. Контекст проекта:\n{context}"},
{"role": "user", "content": question}
],
temperature=0.7,
)
return response.choices[0].message.content
except Exception as e:
return f"[Mock ответ] Функция AI-чата требует настроенный MISTRAL_API_KEY. Ошибка: {str(e)}"