Update handler.py
Browse files- handler.py +160 -165
handler.py
CHANGED
|
@@ -1,165 +1,160 @@
|
|
| 1 |
-
from typing import Dict, List, Any
|
| 2 |
-
import json
|
| 3 |
-
import torch
|
| 4 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
self.
|
| 12 |
-
self.
|
| 13 |
-
self.
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
"""
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def
|
| 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 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
#
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
#
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
if data is None:
|
| 163 |
-
return None
|
| 164 |
-
|
| 165 |
-
return _service.handle(data, context)
|
|
|
|
| 1 |
+
from typing import Dict, List, Any
|
| 2 |
+
import json
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 5 |
+
|
| 6 |
+
class EndpointHandler:
|
| 7 |
+
def __init__(self, path=""):
|
| 8 |
+
"""
|
| 9 |
+
Initialize model and tokenizer
|
| 10 |
+
"""
|
| 11 |
+
self.model_dir = path
|
| 12 |
+
self.initialized = False
|
| 13 |
+
self.model = None
|
| 14 |
+
self.tokenizer = None
|
| 15 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 16 |
+
|
| 17 |
+
def __call__(self, data):
|
| 18 |
+
"""
|
| 19 |
+
Main entry point for the handler
|
| 20 |
+
"""
|
| 21 |
+
if not self.initialized:
|
| 22 |
+
self.initialize()
|
| 23 |
+
|
| 24 |
+
if data is None:
|
| 25 |
+
return {"error": "No input data provided"}
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
inputs = self.preprocess(data)
|
| 29 |
+
outputs = self.inference(inputs)
|
| 30 |
+
return self.postprocess(outputs)
|
| 31 |
+
except Exception as e:
|
| 32 |
+
return {"error": str(e)}
|
| 33 |
+
|
| 34 |
+
def initialize(self):
|
| 35 |
+
"""
|
| 36 |
+
Load the model and tokenizer
|
| 37 |
+
"""
|
| 38 |
+
try:
|
| 39 |
+
# Load tokenizer
|
| 40 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_dir)
|
| 41 |
+
if not self.tokenizer.pad_token:
|
| 42 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 43 |
+
|
| 44 |
+
# Load model
|
| 45 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 46 |
+
self.model_dir,
|
| 47 |
+
device_map="auto",
|
| 48 |
+
torch_dtype=torch.float16
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
self.initialized = True
|
| 52 |
+
except Exception as e:
|
| 53 |
+
raise RuntimeError(f"Error initializing model: {str(e)}")
|
| 54 |
+
|
| 55 |
+
def build_prompt(self, project_info):
|
| 56 |
+
"""
|
| 57 |
+
Build an input prompt from project features
|
| 58 |
+
"""
|
| 59 |
+
nom = project_info.get("Nom du projet", "")
|
| 60 |
+
description = project_info.get("Description", "")
|
| 61 |
+
duree = project_info.get("Durée (mois)", "")
|
| 62 |
+
complexite = project_info.get("Complexité (1-5)", "")
|
| 63 |
+
secteur = project_info.get("Secteur", "")
|
| 64 |
+
taches = project_info.get("Tâches Identifiées", "")
|
| 65 |
+
|
| 66 |
+
prompt = (f"Nom du projet: {nom}\n"
|
| 67 |
+
f"Description: {description}\n"
|
| 68 |
+
f"Durée (mois): {duree}\n"
|
| 69 |
+
f"Complexité (1-5): {complexite}\n"
|
| 70 |
+
f"Secteur: {secteur}\n"
|
| 71 |
+
f"Tâches Identifiées: {taches}\n\n"
|
| 72 |
+
"### Instruction:\n"
|
| 73 |
+
"Fournis les informations en format JSON pour:\n"
|
| 74 |
+
"- Compétences Requises\n"
|
| 75 |
+
"- Employés Alloués\n"
|
| 76 |
+
"- Répartition par Compétences\n\n"
|
| 77 |
+
"### Réponse:\n")
|
| 78 |
+
return prompt
|
| 79 |
+
|
| 80 |
+
def preprocess(self, data):
|
| 81 |
+
"""
|
| 82 |
+
Preprocess the input data
|
| 83 |
+
"""
|
| 84 |
+
try:
|
| 85 |
+
inputs = data.get("inputs", {})
|
| 86 |
+
|
| 87 |
+
# Handle string inputs (could be JSON string or direct prompt)
|
| 88 |
+
if isinstance(inputs, str):
|
| 89 |
+
try:
|
| 90 |
+
# Try to parse as JSON
|
| 91 |
+
inputs = json.loads(inputs)
|
| 92 |
+
except:
|
| 93 |
+
# If parsing fails, assume it's a direct prompt
|
| 94 |
+
return {"prompt": inputs}
|
| 95 |
+
|
| 96 |
+
# Build prompt if project info is provided
|
| 97 |
+
if isinstance(inputs, dict) and "Nom du projet" in inputs:
|
| 98 |
+
prompt = self.build_prompt(inputs)
|
| 99 |
+
else:
|
| 100 |
+
prompt = inputs
|
| 101 |
+
|
| 102 |
+
return {"prompt": prompt}
|
| 103 |
+
except Exception as e:
|
| 104 |
+
raise Exception(f"Error in preprocessing: {str(e)}")
|
| 105 |
+
|
| 106 |
+
def inference(self, inputs):
|
| 107 |
+
"""
|
| 108 |
+
Generate text based on the input prompt
|
| 109 |
+
"""
|
| 110 |
+
try:
|
| 111 |
+
prompt = inputs.get("prompt", "")
|
| 112 |
+
|
| 113 |
+
# Tokenize input
|
| 114 |
+
tokenized_inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device)
|
| 115 |
+
|
| 116 |
+
# Generate output
|
| 117 |
+
with torch.no_grad():
|
| 118 |
+
outputs = self.model.generate(
|
| 119 |
+
**tokenized_inputs,
|
| 120 |
+
max_new_tokens=800,
|
| 121 |
+
do_sample=False, # Deterministic generation
|
| 122 |
+
eos_token_id=self.tokenizer.eos_token_id
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
# Decode output
|
| 126 |
+
generated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 127 |
+
|
| 128 |
+
# Extract response part (after "### Réponse:")
|
| 129 |
+
if "### Réponse:" in generated_text:
|
| 130 |
+
response = generated_text.split("### Réponse:")[-1].strip()
|
| 131 |
+
else:
|
| 132 |
+
response = generated_text.strip()
|
| 133 |
+
|
| 134 |
+
# Clean up response (remove markdown code block markers)
|
| 135 |
+
if response.startswith("```json"):
|
| 136 |
+
response = response.split("```json", 1)[1]
|
| 137 |
+
if response.startswith("```"):
|
| 138 |
+
response = response.split("```", 1)[1]
|
| 139 |
+
if response.endswith("```"):
|
| 140 |
+
response = response.rsplit("```", 1)[0]
|
| 141 |
+
|
| 142 |
+
return response.strip()
|
| 143 |
+
except Exception as e:
|
| 144 |
+
raise Exception(f"Error in inference: {str(e)}")
|
| 145 |
+
|
| 146 |
+
def postprocess(self, inference_output):
|
| 147 |
+
"""
|
| 148 |
+
Post-process the model output
|
| 149 |
+
"""
|
| 150 |
+
try:
|
| 151 |
+
# Try to parse as JSON to ensure it's valid
|
| 152 |
+
try:
|
| 153 |
+
parsed_json = json.loads(inference_output)
|
| 154 |
+
# Return the parsed JSON if successful
|
| 155 |
+
return {"generated_text": inference_output}
|
| 156 |
+
except json.JSONDecodeError:
|
| 157 |
+
# If not valid JSON, return as is
|
| 158 |
+
return {"generated_text": inference_output}
|
| 159 |
+
except Exception as e:
|
| 160 |
+
raise Exception(f"Error in postprocessing: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|