Spaces:
Sleeping
Sleeping
File size: 6,164 Bytes
5e9fd8b |
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 |
""" api.py - Расширенный API для фронтенда """
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional, Dict, Any
from ai_backend import PracticeAIBackendSimple
import uvicorn
# Инициализация бэкенда
backend = PracticeAIBackendSimple()
# Создание FastAPI приложения
app = FastAPI(title="Practice AI Backend", version="2.0")
# CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# Модели запросов
class TextRequest(BaseModel):
text: str
specialization: Optional[str] = "it"
class HonestyRequest(BaseModel):
text: str
history: List[str]
class ReputationRequest(BaseModel):
entries: List[Dict[str, Any]]
class SkillGapRequest(BaseModel):
texts: List[str]
target_specialization: str
class RatingRequest(BaseModel):
entry_id: str
user_id: str
rating: int
class ApprovalRequest(BaseModel):
entry_id: str
status: str # 'approved', 'rejected', 'pending'
# Эндпоинты
@app.get("/")
async def root():
return {
"service": "Practice AI Backend",
"version": "2.0",
"status": "running",
"endpoints": {
"analyze_honesty": "/api/analyze/honesty",
"improve_text": "/api/improve/text",
"calculate_reputation": "/api/calculate/reputation",
"detect_specialization": "/api/detect/specialization",
"generate_thought": "/api/generate/thought",
"analyze_skillgap": "/api/analyze/skillgap",
"health": "/api/health"
}
}
@app.post("/api/analyze/honesty")
async def analyze_honesty(request: HonestyRequest):
try:
result = backend.analyze_honesty(request.text, request.history)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/improve/text")
async def improve_text(request: TextRequest):
try:
improved = backend.improve_text(request.text, request.specialization)
return {"improved_text": improved}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/calculate/reputation")
async def calculate_reputation(request: ReputationRequest):
try:
result = backend.calculate_reputation(request.entries)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/detect/specialization")
async def detect_specialization(request: TextRequest):
try:
spec, scores = backend.detect_specialization(request.text)
return {
"specialization": spec,
"confidence_scores": scores
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/generate/thought")
async def generate_thought(request: TextRequest):
try:
thought = backend.generate_thought(request.specialization, request.text)
return {"generated_text": thought}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/analyze/skillgap")
async def analyze_skillgap(request: SkillGapRequest):
try:
result = backend.analyze_skill_gap(request.texts, request.target_specialization)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/rate/entry")
async def rate_entry(request: RatingRequest):
"""Оценить запись"""
try:
# Здесь должна быть логика сохранения оценки в БД
# Это пример - в реальности нужно сохранять в вашу БД
return {
"success": True,
"message": "Оценка сохранена",
"entry_id": request.entry_id,
"rating": request.rating
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/approve/entry")
async def approve_entry(request: ApprovalRequest):
"""Одобрить/отклонить запись"""
try:
# Здесь должна быть логика изменения статуса в БД
return {
"success": True,
"message": f"Статус изменен на {request.status}",
"entry_id": request.entry_id,
"status": request.status
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/health")
async def health_check():
return {
"status": "healthy",
"backend": "PracticeAIBackendSimple",
"ml_available": True,
"version": "2.0"
}
# Запуск сервера
if __name__ == "__main__":
print("Запуск API сервера на http://localhost:8000")
print("Доступные эндпоинты:")
print(" GET / - информация о сервисе")
print(" POST /api/analyze/honesty - анализ честности текста")
print(" POST /api/improve/text - улучшение текста")
print(" POST /api/calculate/reputation - расчет репутации")
print(" POST /api/detect/specialization - определение специальности")
print(" POST /api/generate/thought - генерация текста")
print(" POST /api/analyze/skillgap - анализ пробелов в навыках")
print(" POST /api/rate/entry - оценить запись")
print(" POST /api/approve/entry - одобрить/отклонить запись")
print(" GET /api/health - проверка здоровья сервиса")
uvicorn.run(app, host="0.0.0.0", port=8000) |