""" 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)