Download handler.py from bobduru/gemma-27b-flagging-project: direct link, hf CLI and curl.
- Browser
- Download file 2.13 kB
-
https://huggingface.co/bobduru/gemma-27b-flagging-project/resolve/main/handler.py
- Command line
-
hf download hf://bobduru/gemma-27b-flagging-project/handler.py
-
curl -L -o handler.py https://huggingface.co/bobduru/gemma-27b-flagging-project/resolve/main/handler.py
2.13 kB
| import os | |
| from dotenv import load_dotenv | |
| from transformers import AutoProcessor, Gemma3ForConditionalGeneration | |
| from huggingface_hub import login | |
| import torch | |
| from flag_classifier import FlagClassifier | |
| import time | |
| # Load env vars from .env file | |
| load_dotenv() | |
| class EndpointHandler: | |
| def __init__(self, path="."): | |
| keyword_path = os.path.join(path, "keywords.csv") | |
| model_id = os.getenv("MODEL_ID") | |
| if model_id is None: | |
| model_id = "google/gemma-3-12b-it" | |
| self.clf = FlagClassifier(model_id=model_id, keyword_csv_path=keyword_path, n_keywords_to_keep=20) | |
| def __call__(self, data): | |
| # Step 1: Check input format | |
| if not isinstance(data, dict) or "inputs" not in data: | |
| return {"error": "Missing 'inputs' key in request."} | |
| inputs = data["inputs"] | |
| if not isinstance(inputs, list) or not all(isinstance(item, dict) and "value" in item for item in inputs): | |
| return {"error": "'inputs' must be a list of dicts with a 'value' key."} | |
| # Step 2: Get parameters if provided | |
| params = data.get("parameters", {}) | |
| keywords_strategy = params.get("keywords_strategy", "none") | |
| batch_size = params.get("batch_size", 16) | |
| classification_method = params.get("classification_method", "token_likelihood") | |
| padding_side = params.get("padding_side", "left") | |
| # Step 3: Classify with timing | |
| start_time = time.time() | |
| try: | |
| results = self.clf.classify_list( | |
| inputs, | |
| keywords_strategy=keywords_strategy, | |
| batch_size=batch_size, | |
| classification_method=classification_method, | |
| padding_side=padding_side | |
| ) | |
| duration = round(time.time() - start_time, 4) | |
| return { | |
| "results": results, | |
| "processing_time": duration, | |
| "model_config": str(self.clf.model.config), | |
| "tokenizer_config": str(self.clf.tokenizer.init_kwargs), | |
| } | |
| except Exception as e: | |
| return {"error": str(e)} |