from fastapi import FastAPI, HTTPException from pydantic import BaseModel from datetime import datetime import json import os from huggingface_hub import HfApi from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], # Или конкретно ['https://zammad.astanait.edu.kz'] allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) JSONL_FILE = "feedback_dataset.jsonl" HF_REPO_ID = "Dum4n/aitu-feedback-api" # укажи свой Space ID class Feedback(BaseModel): question: str answer: str rating: int def append_local_log(record): """Локально сохраняем""" with open(JSONL_FILE, "a", encoding="utf-8") as f: f.write(json.dumps(record, ensure_ascii=False) + "\n") def push_to_huggingface(record): """Загружаем в репозиторий""" token = os.getenv("HF_TOKEN") if not token: raise RuntimeError("❌ HF_TOKEN is not set in environment variables.") filename = f"logs/feedback_{datetime.now().isoformat()}.jsonl" temp_path = f"/tmp/{os.path.basename(filename)}" with open(temp_path, "w", encoding="utf-8") as f: f.write(json.dumps(record, ensure_ascii=False) + "\n") api = HfApi() api.upload_file( path_or_fileobj=temp_path, path_in_repo=filename, repo_id=HF_REPO_ID, repo_type="space", token=token, commit_message="📬 New feedback logged" ) @app.post("/rate") def rate(feedback: Feedback): if feedback.rating < 1 or feedback.rating > 5: raise HTTPException(status_code=400, detail="Rating must be between 1 and 5") record = { "timestamp": datetime.now().isoformat(), "question": feedback.question.strip(), "answer": feedback.answer.strip(), "rating": int(feedback.rating) } append_local_log(record) push_to_huggingface(record) return {"message": "✅ Feedback saved & pushed to repo"}