Spaces:
Sleeping
Sleeping
File size: 2,032 Bytes
ab9128a bf9d04a ae19b46 ab9128a bc0fe32 ab9128a bf9d04a ab9128a bf9d04a ab9128a bf9d04a ab9128a bf9d04a ab9128a bf9d04a | 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 | 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"}
|