Spaces:
Running
Running
Download custom_topic_quiz_generator_app.py from HomemadeMirpur/ed-cad-ref: direct link, hf CLI and curl.
- Browser
- Download file 8.2 kB
-
https://huggingface.co/spaces/HomemadeMirpur/ed-cad-ref/resolve/main/custom_topic_quiz_generator_app.py
- Command line
-
hf download hf://spaces/HomemadeMirpur/ed-cad-ref/custom_topic_quiz_generator_app.py
-
curl -L -o custom_topic_quiz_generator_app.py https://huggingface.co/spaces/HomemadeMirpur/ed-cad-ref/resolve/main/custom_topic_quiz_generator_app.py
8.2 kB
| import base64 | |
| import binascii | |
| import functools | |
| import hmac | |
| import logging | |
| import os | |
| import threading | |
| import time | |
| from dataclasses import asdict | |
| from typing import Dict, Set | |
| from dotenv import load_dotenv | |
| from flask import Flask, Response, jsonify, request | |
| from werkzeug.exceptions import RequestEntityTooLarge | |
| from shared_models import ModelBundle | |
| from retrieval.config import QuizConfig | |
| from retrieval.index_manager import QuizIndexManager | |
| from retrieval.search import HybridQuizSearcher, SearchFilters | |
| load_dotenv() | |
| logging.basicConfig( | |
| level=os.getenv("LOG_LEVEL", "INFO").upper(), | |
| format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", | |
| ) | |
| logger = logging.getLogger(__name__) | |
| config = QuizConfig.from_env() | |
| app = Flask(__name__) | |
| app.config["MAX_CONTENT_LENGTH"] = config.body_limit_bytes | |
| models = ModelBundle.load( | |
| embedding_model_name=config.embedding_model, | |
| reranker_model_name=config.reranker_model, | |
| use_gpu_for_embeddings=config.embedding_gpu, | |
| enable_reranker=config.reranker_enabled, | |
| ) | |
| manager = QuizIndexManager(config, models) | |
| searcher = HybridQuizSearcher(config, models, manager) | |
| def _basic_credentials() -> tuple[str, str]: | |
| raw = request.headers.get("Authorization", "").strip() | |
| if not raw.lower().startswith("basic "): | |
| return "", "" | |
| encoded = raw[6:].strip() | |
| if not encoded: | |
| return "", "" | |
| try: | |
| decoded = base64.b64decode(encoded, validate=True).decode("utf-8") | |
| except (binascii.Error, UnicodeDecodeError, ValueError): | |
| return "", "" | |
| if ":" not in decoded: | |
| return "", "" | |
| return tuple(decoded.split(":", 1)) | |
| def _requires_basic_auth(expected_username: str, expected_password: str): | |
| def decorator(function): | |
| def wrapped(*args, **kwargs): | |
| provided_username, provided_password = _basic_credentials() | |
| username_ok = bool(expected_username) and hmac.compare_digest( | |
| provided_username, expected_username | |
| ) | |
| password_ok = bool(expected_password) and hmac.compare_digest( | |
| provided_password, expected_password | |
| ) | |
| if not username_ok or not password_ok: | |
| response = jsonify({"error": "Unauthorized"}) | |
| response.headers["WWW-Authenticate"] = 'Basic realm="custom-quiz-api"' | |
| return response, 401 | |
| return function(*args, **kwargs) | |
| return wrapped | |
| return decorator | |
| def _positive_int(value: object, default: int) -> int: | |
| try: | |
| parsed = int(value) | |
| except (TypeError, ValueError): | |
| return default | |
| return parsed | |
| def _exclude_ids(value: object) -> Set[int]: | |
| if not isinstance(value, list): | |
| return set() | |
| if len(value) > config.max_exclude_ids: | |
| raise ValueError( | |
| f"exclude_ids exceeds the maximum of {config.max_exclude_ids}." | |
| ) | |
| result = set() | |
| for item in value: | |
| try: | |
| parsed = int(item) | |
| except (TypeError, ValueError): | |
| continue | |
| if parsed > 0: | |
| result.add(parsed) | |
| return result | |
| def _initialize() -> None: | |
| try: | |
| if manager.load_active(): | |
| return | |
| except Exception: | |
| logger.exception("[CUSTOM_TOPIC_QUIZ_GENERATOR] Active index could not be loaded.") | |
| try: | |
| if config.csv_path.is_file(): | |
| manager.rebuild(config.csv_path) | |
| return | |
| if config.csv_url: | |
| manager.refresh_from_google() | |
| except Exception: | |
| logger.exception( | |
| "[CUSTOM_TOPIC_QUIZ_GENERATOR] Startup index initialization failed; health will remain unready." | |
| ) | |
| def _refresh_loop() -> None: | |
| while True: | |
| time.sleep(config.refresh_minutes * 60) | |
| try: | |
| manager.refresh_from_google() | |
| except Exception: | |
| logger.exception("[CUSTOM_TOPIC_QUIZ_GENERATOR] Scheduled CSV refresh failed.") | |
| _initialize() | |
| if config.refresh_minutes > 0 and config.csv_url: | |
| threading.Thread(target=_refresh_loop, daemon=True).start() | |
| def body_too_large(_: RequestEntityTooLarge): | |
| return jsonify({"error": "Request body is too large."}), 413 | |
| def health(): | |
| status = manager.status() | |
| return jsonify({"status": "ok" if status["ready"] else "unready", **status}), (200 if status["ready"] else 503) | |
| def custom_topic_quiz_generator_search(): | |
| data = request.get_json(silent=True) | |
| if not isinstance(data, dict): | |
| return jsonify({"error": "Request body must be a JSON object."}), 400 | |
| query = str(data.get("query") or "").strip() | |
| if not query: | |
| return jsonify({"error": "query is required."}), 400 | |
| if len(query) > 300: | |
| return jsonify({"error": "query is too long."}), 400 | |
| limit = _positive_int(data.get("limit"), 10) | |
| if limit < 1 or limit > config.max_results: | |
| return jsonify({"error": f"limit must be between 1 and {config.max_results}."}), 400 | |
| mode = str(data.get("mode") or "quiz").strip().lower() | |
| if mode not in {"quiz", "exam", "flash"}: | |
| return jsonify({"error": "mode must be quiz, exam, or flash."}), 400 | |
| try: | |
| exclusions = _exclude_ids(data.get("exclude_ids")) | |
| filters = SearchFilters.from_payload(data.get("filters")) | |
| response = searcher.search( | |
| query=query, | |
| limit=limit, | |
| exclude_ids=exclusions, | |
| filters=filters, | |
| ) | |
| except ValueError as error: | |
| return jsonify({"error": str(error)}), 400 | |
| except RuntimeError as error: | |
| logger.warning("[CUSTOM_TOPIC_QUIZ_GENERATOR] Search unavailable: %s", error) | |
| return jsonify({"error": "Quiz retrieval is temporarily unavailable."}), 503 | |
| except Exception: | |
| logger.exception("[CUSTOM_TOPIC_QUIZ_GENERATOR] Search failed.") | |
| return jsonify({"error": "Quiz retrieval failed."}), 500 | |
| logger.info( | |
| "[CUSTOM_TOPIC_QUIZ_GENERATOR] request_id=%s mode=%s query_chars=%d requested=%d returned=%d excluded=%d candidates=%d exhausted=%s timings_ms=%s", | |
| str(data.get("request_id") or "")[:80], | |
| mode, | |
| len(query), | |
| response.requested, | |
| response.returned, | |
| response.excluded_count, | |
| response.candidate_count, | |
| response.exhausted, | |
| response.timings_ms, | |
| ) | |
| return jsonify( | |
| { | |
| "query": query, | |
| "normalized_query": response.normalized_query, | |
| "index_version": response.index_version, | |
| "results": [asdict(item) for item in response.results], | |
| "requested": response.requested, | |
| "returned": response.returned, | |
| "exhausted": response.exhausted, | |
| } | |
| ) | |
| def index_status(): | |
| return jsonify(manager.status()) | |
| def index_rebuild(): | |
| data = request.get_json(silent=True) or {} | |
| try: | |
| result = manager.rebuild(force=bool(data.get("force"))) | |
| return jsonify(result), (409 if result.get("status") == "busy" else 200) | |
| except Exception as error: | |
| logger.exception("[CUSTOM_TOPIC_QUIZ_GENERATOR] Manual rebuild failed.") | |
| return jsonify({"error": str(error)}), 400 | |
| def index_refresh(): | |
| data = request.get_json(silent=True) or {} | |
| try: | |
| result = manager.refresh_from_google(force=bool(data.get("force"))) | |
| return jsonify(result), (409 if result.get("status") == "busy" else 200) | |
| except Exception as error: | |
| logger.exception("[CUSTOM_TOPIC_QUIZ_GENERATOR] Google refresh failed.") | |
| return jsonify({"error": str(error)}), 400 | |
| if __name__ == "__main__": | |
| port = int(os.getenv("PORT", "7861")) | |
| app.run(host="0.0.0.0", port=port, threaded=True) | |