Spaces:
Sleeping
Sleeping
| import json | |
| import os | |
| from typing import Optional | |
| from _types import AnswerCacheEntry, AnswerCache | |
| CACHE_FILE = "answers_cache.json" | |
| def load_cache(cache_path: str = CACHE_FILE) -> AnswerCache: | |
| if not os.path.exists(cache_path): | |
| return {} | |
| with open(cache_path, "r", encoding="utf-8") as f: | |
| try: | |
| return json.load(f) | |
| except json.JSONDecodeError: | |
| return {} | |
| def save_cache(cache: AnswerCache, cache_path: str = CACHE_FILE) -> None: | |
| with open(cache_path, "w", encoding="utf-8") as f: | |
| json.dump(cache, f, ensure_ascii=False, indent=2) | |
| def cache_answers(questions, cache_path: str = CACHE_FILE) -> AnswerCache: | |
| """ | |
| Initializes the cache with all answers as incorrect. | |
| Structure: { task_id: { answer: '', isCorrect: False } } | |
| """ | |
| cache: AnswerCache = {} | |
| for q in questions: | |
| task_id = q.get("task_id") | |
| if task_id: | |
| cache[task_id] = {"answer": "", "isCorrect": False} | |
| save_cache(cache, cache_path) | |
| return cache | |
| def update_cache_answer(task_id: str, answer: str, is_correct: bool = False, cache_path: str = CACHE_FILE): | |
| """ | |
| Update the cache with the answer and its correctness status. | |
| """ | |
| cache = load_cache(cache_path) | |
| cache[task_id] = {"answer": answer, "isCorrect": is_correct} | |
| save_cache(cache, cache_path) | |
| def get_cached_answer(task_id: str, cache_path: str = CACHE_FILE) -> Optional[AnswerCacheEntry]: | |
| """ | |
| Retrieve the cached answer for a given task ID. | |
| """ | |
| cache = load_cache(cache_path) | |
| return cache.get(task_id) | |