File size: 2,125 Bytes
9a6da9e
 
e4cec43
9a6da9e
e4cec43
7549c4a
 
e4cec43
9a6da9e
 
 
e4cec43
a522295
998cbd4
d1d2ac7
 
 
 
 
 
22e0c5b
329c02a
7549c4a
 
 
 
 
 
 
 
 
 
c51f164
7549c4a
0588a61
d1d2ac7
7549c4a
 
 
 
 
 
c51f164
0588a61
d1d2ac7
 
7549c4a
 
 
 
d00a401
a6a2b9e
c09cd8f
7549c4a
 
 
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
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)}