Update inference_test_turkcell_with_intents.py
Browse files
inference_test_turkcell_with_intents.py
CHANGED
@@ -1,4 +1,3 @@
|
|
1 |
-
# fine_tune_inference_with_intent.py
|
2 |
import os, torch, threading, uvicorn, time, traceback, zipfile, random, json, shutil, asyncio, re
|
3 |
from fastapi import FastAPI
|
4 |
from fastapi.responses import HTMLResponse, JSONResponse
|
@@ -20,7 +19,8 @@ USE_FINE_TUNE = False
|
|
20 |
FINE_TUNE_REPO = "UcsTurkey/trained-zips"
|
21 |
FINE_TUNE_ZIP = "trained_model_000_009.zip"
|
22 |
USE_SAMPLING = False
|
23 |
-
|
|
|
24 |
FALLBACK_ANSWERS = [
|
25 |
"Bu konuda maalesef bilgim yok.",
|
26 |
"Ne demek istediğinizi tam anlayamadım.",
|
@@ -75,181 +75,6 @@ def root():
|
|
75 |
</body></html>
|
76 |
"""
|
77 |
|
78 |
-
@app.post("/train_intents", status_code=202)
|
79 |
-
def train_intents(train_input: TrainInput):
|
80 |
-
global INTENT_DEFINITIONS
|
81 |
-
|
82 |
-
log("📥 POST /train_intents çağrıldı.")
|
83 |
-
intents = train_input.intents
|
84 |
-
INTENT_DEFINITIONS = {intent["name"]: intent for intent in intents}
|
85 |
-
|
86 |
-
threading.Thread(target=lambda: background_training(intents), daemon=True).start()
|
87 |
-
return {"status": "accepted", "message": "Intent eğitimi arka planda başlatıldı."}
|
88 |
-
|
89 |
-
def background_training(intents):
|
90 |
-
try:
|
91 |
-
log("🔧 Intent eğitimi başlatıldı...")
|
92 |
-
|
93 |
-
# 1. Verileri derle
|
94 |
-
log("📌 Intent örnekleri toplanıyor...")
|
95 |
-
texts, labels, label2id = [], [], {}
|
96 |
-
for idx, intent in enumerate(intents):
|
97 |
-
label2id[intent["name"]] = idx
|
98 |
-
for ex in intent["examples"]:
|
99 |
-
texts.append(ex)
|
100 |
-
labels.append(idx)
|
101 |
-
log(f"📌 Toplam örnek sayısı: {len(texts)}")
|
102 |
-
|
103 |
-
# 2. Dataset oluştur
|
104 |
-
log("📦 Dataset oluşturuluyor...")
|
105 |
-
dataset = Dataset.from_dict({"text": texts, "label": labels})
|
106 |
-
|
107 |
-
# 3. Tokenizer ve model yükle
|
108 |
-
log("📥 Tokenizer yükleniyor...")
|
109 |
-
tokenizer = AutoTokenizer.from_pretrained(INTENT_MODEL_ID)
|
110 |
-
|
111 |
-
log("📦 Model konfigürasyonu hazırlanıyor...")
|
112 |
-
config = AutoConfig.from_pretrained(INTENT_MODEL_ID)
|
113 |
-
config.problem_type = "single_label_classification"
|
114 |
-
config.num_labels = len(label2id)
|
115 |
-
|
116 |
-
log("📦 Model yükleniyor...")
|
117 |
-
model = AutoModelForSequenceClassification.from_pretrained(INTENT_MODEL_ID, config=config)
|
118 |
-
log("✅ Tokenizer ve model hazır.")
|
119 |
-
|
120 |
-
# 4. Tokenize işlemi
|
121 |
-
log("🧪 Tokenize işlemi başlatılıyor...")
|
122 |
-
sample = dataset[0]["text"]
|
123 |
-
log(f"📄 Örnek: {sample}")
|
124 |
-
result = tokenizer(sample, truncation=True, padding=True)
|
125 |
-
log(f"✅ Tokenizer sonucu: {result['input_ids'][:5]}")
|
126 |
-
|
127 |
-
log("🔁 Manuel tokenize işlemi başlatılıyor...")
|
128 |
-
tokenized_data = {"input_ids": [], "attention_mask": [], "label": []}
|
129 |
-
for row in dataset:
|
130 |
-
out = tokenizer(row["text"], truncation=True, padding="max_length", max_length=128)
|
131 |
-
tokenized_data["input_ids"].append(out["input_ids"])
|
132 |
-
tokenized_data["attention_mask"].append(out["attention_mask"])
|
133 |
-
tokenized_data["label"].append(row["label"])
|
134 |
-
|
135 |
-
tokenized = Dataset.from_dict(tokenized_data)
|
136 |
-
tokenized.set_format(type="torch", columns=["input_ids", "attention_mask", "label"])
|
137 |
-
|
138 |
-
log(f"📊 Eğitim örnek sayısı (manuel tokenized): {len(tokenized)}")
|
139 |
-
if len(tokenized) == 0:
|
140 |
-
log("❌ Tokenize edilmiş veri boş! Eğitim başlatılamıyor.")
|
141 |
-
return
|
142 |
-
|
143 |
-
# 5. Çıktı klasörü
|
144 |
-
log("📁 Çıktı klasörü hazırlanıyor...")
|
145 |
-
INTENT_OUTPUT_DIR = "/app/intent_train_output"
|
146 |
-
os.makedirs(INTENT_OUTPUT_DIR, exist_ok=True)
|
147 |
-
|
148 |
-
# 6. Eğitim ayarları
|
149 |
-
log("⚙️ Eğitim ayarları yapılandırılıyor...")
|
150 |
-
args = TrainingArguments(
|
151 |
-
INTENT_OUTPUT_DIR,
|
152 |
-
per_device_train_batch_size=4,
|
153 |
-
num_train_epochs=3,
|
154 |
-
logging_steps=10,
|
155 |
-
save_strategy="no",
|
156 |
-
report_to=[]
|
157 |
-
)
|
158 |
-
|
159 |
-
trainer = Trainer(
|
160 |
-
model=model,
|
161 |
-
args=args,
|
162 |
-
train_dataset=tokenized,
|
163 |
-
data_collator=default_data_collator
|
164 |
-
)
|
165 |
-
|
166 |
-
# 7. Eğitim başlatılıyor
|
167 |
-
log("🚀 trainer.train() başlatılıyor...")
|
168 |
-
trainer.train()
|
169 |
-
log("✅ trainer.train() tamamlandı.")
|
170 |
-
|
171 |
-
# 8. Model kaydediliyor
|
172 |
-
log("💾 Model diske kaydediliyor...")
|
173 |
-
if os.path.exists(INTENT_MODEL_PATH):
|
174 |
-
shutil.rmtree(INTENT_MODEL_PATH)
|
175 |
-
model.save_pretrained(INTENT_MODEL_PATH)
|
176 |
-
tokenizer.save_pretrained(INTENT_MODEL_PATH)
|
177 |
-
with open(os.path.join(INTENT_MODEL_PATH, "label2id.json"), "w") as f:
|
178 |
-
json.dump(label2id, f)
|
179 |
-
|
180 |
-
log("✅ Intent eğitimi tamamlandı ve model kaydedildi.")
|
181 |
-
|
182 |
-
except Exception as e:
|
183 |
-
log(f"❌ Intent eğitimi hatası: {e}")
|
184 |
-
traceback.print_exc()
|
185 |
-
|
186 |
-
@app.post("/load_intent_model")
|
187 |
-
def load_intent_model():
|
188 |
-
global INTENT_MODEL, INTENT_TOKENIZER, LABEL2ID
|
189 |
-
try:
|
190 |
-
INTENT_TOKENIZER = AutoTokenizer.from_pretrained(INTENT_MODEL_PATH)
|
191 |
-
INTENT_MODEL = AutoModelForSequenceClassification.from_pretrained(INTENT_MODEL_PATH)
|
192 |
-
with open(os.path.join(INTENT_MODEL_PATH, "label2id.json")) as f:
|
193 |
-
LABEL2ID = json.load(f)
|
194 |
-
return {"status": "ok", "message": "Intent modeli yüklendi."}
|
195 |
-
except Exception as e:
|
196 |
-
return JSONResponse(content={"error": str(e)}, status_code=500)
|
197 |
-
|
198 |
-
async def detect_intent(text):
|
199 |
-
inputs = INTENT_TOKENIZER(text, return_tensors="pt")
|
200 |
-
outputs = INTENT_MODEL(**inputs)
|
201 |
-
pred_id = outputs.logits.argmax().item()
|
202 |
-
id2label = {v: k for k, v in LABEL2ID.items()}
|
203 |
-
return id2label[pred_id]
|
204 |
-
|
205 |
-
def extract_parameters(variables_list, user_input):
|
206 |
-
for pattern in variables_list:
|
207 |
-
regex = re.sub(r"(\w+):\{(.+?)\}", r"(?P<\1>.+?)", pattern)
|
208 |
-
match = re.match(regex, user_input)
|
209 |
-
if match:
|
210 |
-
return [{"key": k, "value": v} for k, v in match.groupdict().items()]
|
211 |
-
return []
|
212 |
-
|
213 |
-
def execute_intent(intent_name, user_input):
|
214 |
-
if intent_name in INTENT_DEFINITIONS:
|
215 |
-
definition = INTENT_DEFINITIONS[intent_name]
|
216 |
-
variables = extract_parameters(definition.get("variables", []), user_input)
|
217 |
-
log(f"🚀 execute_intent('{intent_name}', {variables})")
|
218 |
-
return {"intent": intent_name, "parameters": variables}
|
219 |
-
return {"intent": intent_name, "parameters": []}
|
220 |
-
|
221 |
-
async def generate_response(text):
|
222 |
-
messages = [{"role": "user", "content": text}]
|
223 |
-
encodeds = tokenizer.apply_chat_template(messages, return_tensors="pt", add_generation_prompt=True)
|
224 |
-
eos_token = tokenizer("<|im_end|>", add_special_tokens=False)["input_ids"][0]
|
225 |
-
|
226 |
-
input_ids = encodeds.to(model.device)
|
227 |
-
attention_mask = (input_ids != tokenizer.pad_token_id).long()
|
228 |
-
|
229 |
-
with torch.no_grad():
|
230 |
-
output = model.generate(
|
231 |
-
input_ids=input_ids,
|
232 |
-
attention_mask=attention_mask,
|
233 |
-
max_new_tokens=128,
|
234 |
-
do_sample=USE_SAMPLING,
|
235 |
-
eos_token_id=eos_token,
|
236 |
-
pad_token_id=tokenizer.pad_token_id,
|
237 |
-
return_dict_in_generate=True,
|
238 |
-
output_scores=True
|
239 |
-
)
|
240 |
-
|
241 |
-
try:
|
242 |
-
decoded = tokenizer.decode(output.sequences[0], skip_special_tokens=True).strip()
|
243 |
-
# Kullanıcı mesajlarını ve rolleri çıkar
|
244 |
-
for tag in ["assistant", "<|im_start|>assistant"]:
|
245 |
-
start = decoded.find(tag)
|
246 |
-
if start != -1:
|
247 |
-
return decoded[start + len(tag):].strip()
|
248 |
-
return decoded
|
249 |
-
except Exception as decode_error:
|
250 |
-
log(f"❌ Decode hatası: {decode_error}")
|
251 |
-
return random.choice(FALLBACK_ANSWERS)
|
252 |
-
|
253 |
@app.post("/chat")
|
254 |
async def chat(msg: Message):
|
255 |
user_input = msg.user_input.strip()
|
@@ -261,53 +86,43 @@ async def chat(msg: Message):
|
|
261 |
intent_task = asyncio.create_task(detect_intent(user_input))
|
262 |
response_task = asyncio.create_task(generate_response(user_input))
|
263 |
intent = await intent_task
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
264 |
if intent in INTENT_DEFINITIONS:
|
265 |
result = execute_intent(intent, user_input)
|
266 |
return result
|
267 |
else:
|
268 |
response = await response_task
|
269 |
-
return {"response": response}
|
270 |
else:
|
271 |
response = await generate_response(user_input)
|
272 |
-
|
|
|
|
|
273 |
|
274 |
except Exception as e:
|
275 |
traceback.print_exc()
|
276 |
return JSONResponse(content={"error": str(e)}, status_code=500)
|
277 |
|
278 |
-
def
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
log("🧠 setup_model() başladı")
|
286 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
287 |
-
|
288 |
-
# === Ana model
|
289 |
-
log("📥 Tokenizer indiriliyor...")
|
290 |
-
tokenizer = AutoTokenizer.from_pretrained(MODEL_BASE, use_fast=False)
|
291 |
-
log("🧠 Model indiriliyor...")
|
292 |
-
model = AutoModelForCausalLM.from_pretrained(MODEL_BASE, torch_dtype=torch.float32).to(device)
|
293 |
-
tokenizer.pad_token = tokenizer.pad_token or tokenizer.eos_token
|
294 |
-
model.config.pad_token_id = tokenizer.pad_token_id
|
295 |
-
eos_token_id = tokenizer("<|im_end|>", add_special_tokens=False)["input_ids"][0]
|
296 |
-
model.eval()
|
297 |
-
log("✅ Ana model eval() çağrıldı")
|
298 |
-
|
299 |
-
# === Intent BERT modeli önden indiriliyor (ama kullanılmıyor)
|
300 |
-
log(f"📦 Intent modeli indiriliyor: {INTENT_MODEL_ID}")
|
301 |
-
_ = AutoTokenizer.from_pretrained(INTENT_MODEL_ID)
|
302 |
-
_ = AutoModelForSequenceClassification.from_pretrained(INTENT_MODEL_ID)
|
303 |
-
log("✅ Intent modeli indirildi (önbelleğe alındı).")
|
304 |
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
traceback.print_exc()
|
309 |
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
|
|
|
|
1 |
import os, torch, threading, uvicorn, time, traceback, zipfile, random, json, shutil, asyncio, re
|
2 |
from fastapi import FastAPI
|
3 |
from fastapi.responses import HTMLResponse, JSONResponse
|
|
|
19 |
FINE_TUNE_REPO = "UcsTurkey/trained-zips"
|
20 |
FINE_TUNE_ZIP = "trained_model_000_009.zip"
|
21 |
USE_SAMPLING = False
|
22 |
+
GENERATION_CONFIDENCE_THRESHOLD = -1.5
|
23 |
+
INTENT_CONFIDENCE_THRESHOLD = 0.5
|
24 |
FALLBACK_ANSWERS = [
|
25 |
"Bu konuda maalesef bilgim yok.",
|
26 |
"Ne demek istediğinizi tam anlayamadım.",
|
|
|
75 |
</body></html>
|
76 |
"""
|
77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
@app.post("/chat")
|
79 |
async def chat(msg: Message):
|
80 |
user_input = msg.user_input.strip()
|
|
|
86 |
intent_task = asyncio.create_task(detect_intent(user_input))
|
87 |
response_task = asyncio.create_task(generate_response(user_input))
|
88 |
intent = await intent_task
|
89 |
+
|
90 |
+
if intent is None:
|
91 |
+
log("🟡 Intent confidence düşük. Ana modele yönlendiriliyor.")
|
92 |
+
response = await response_task
|
93 |
+
if isinstance(response, dict) and response.get("score", 0) < GENERATION_CONFIDENCE_THRESHOLD:
|
94 |
+
return {"response": random.choice(FALLBACK_ANSWERS)}
|
95 |
+
return {"response": response if isinstance(response, str) else response.get("text", "")}
|
96 |
+
|
97 |
if intent in INTENT_DEFINITIONS:
|
98 |
result = execute_intent(intent, user_input)
|
99 |
return result
|
100 |
else:
|
101 |
response = await response_task
|
102 |
+
return {"response": response if isinstance(response, str) else response.get("text", "")}
|
103 |
else:
|
104 |
response = await generate_response(user_input)
|
105 |
+
if isinstance(response, dict) and response.get("score", 0) < GENERATION_CONFIDENCE_THRESHOLD:
|
106 |
+
return {"response": random.choice(FALLBACK_ANSWERS)}
|
107 |
+
return {"response": response if isinstance(response, str) else response.get("text", "")}
|
108 |
|
109 |
except Exception as e:
|
110 |
traceback.print_exc()
|
111 |
return JSONResponse(content={"error": str(e)}, status_code=500)
|
112 |
|
113 |
+
async def detect_intent(text):
|
114 |
+
inputs = INTENT_TOKENIZER(text, return_tensors="pt")
|
115 |
+
outputs = INTENT_MODEL(**inputs)
|
116 |
+
logits = outputs.logits
|
117 |
+
probs = torch.nn.functional.softmax(logits, dim=1)
|
118 |
+
pred_id = logits.argmax().item()
|
119 |
+
confidence = probs[0][pred_id].item()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
|
121 |
+
id2label = {v: k for k, v in LABEL2ID.items()}
|
122 |
+
intent_name = id2label[pred_id]
|
123 |
+
log(f"🔍 Intent tahmini: {intent_name} (confidence: {confidence:.2f})")
|
|
|
124 |
|
125 |
+
if confidence < INTENT_CONFIDENCE_THRESHOLD:
|
126 |
+
log(f"⚠️ Düşük confidence ({confidence:.2f}) nedeniyle intent boş döndü.")
|
127 |
+
return None
|
128 |
+
return intent_name
|