nixaut-codelabs commited on
Commit
9de51df
·
verified ·
1 Parent(s): b57189b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -24
app.py CHANGED
@@ -41,17 +41,11 @@ model_path = ensure_local_model(MODEL_REPO, LOCAL_DIR)
41
 
42
  tokenizer = AutoTokenizer.from_pretrained(model_path, local_files_only=True)
43
 
44
- ### DEĞİŞİKLİK BURADA BAŞLIYOR ###
45
- # Gemma modelleri için sohbet şablonunu manuel olarak ayarlıyoruz.
46
- # Bu, eski transformers versiyonlarında veya ortam sorunlarında hatayı önler.
47
- gemma_chat_template = (
48
- "{% if messages[0]['role'] == 'system' %}"
49
- "{% raise_exception('System messages are not supported by this model!') %}"
50
- "{% endif %}"
51
  "{% for message in messages %}"
52
- "{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}"
53
- "{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}"
54
- "{% endif %}"
55
  "{% if message['role'] == 'user' %}"
56
  "{{ '<start_of_turn>user\\n' + message['content'] | trim + '<end_of_turn>\\n' }}"
57
  "{% elif message['role'] == 'assistant' %}"
@@ -63,13 +57,10 @@ gemma_chat_template = (
63
  "{% endif %}"
64
  )
65
 
66
- # Not: Modelin kendi tokenizer_config.json dosyasında sistem mesajları desteklenmediği belirtiliyor.
67
- # Bu yüzden yukarıdaki şablonda sistem mesajı gelirse hata vermesi sağlanmıştır.
68
- # build_prompt fonksiyonunu da buna göre güncelleyeceğiz.
69
  if tokenizer.chat_template is None:
70
- print("Chat template manuel olarak ayarlanıyor.")
71
- tokenizer.chat_template = gemma_chat_template
72
- ### DEĞİŞİKLİK BURADA BİTİYOR ###
73
 
74
 
75
  model = AutoModelForCausalLM.from_pretrained(
@@ -80,7 +71,7 @@ model = AutoModelForCausalLM.from_pretrained(
80
  )
81
  model.eval()
82
 
83
- # Çok katı moderasyon system prompt (yalnızca "s" veya "u")
84
  MODERATION_SYSTEM_PROMPT = (
85
  "You are a multilingual content moderation classifier. "
86
  "You MUST respond with exactly one lowercase letter: 's' for safe, 'u' for unsafe. "
@@ -91,24 +82,21 @@ MODERATION_SYSTEM_PROMPT = (
91
  )
92
 
93
  def build_prompt(message, max_ctx_tokens=128):
94
- # ### DEĞİŞİKLİK 2: Sistem mesajı artık desteklenmiyor ###
95
  # Sistem mesajını ilk kullanıcı mesajının bir parçası haline getiriyoruz.
96
- # Bu, Gemma'nın talimat takip etme (instruction-tuned) yapısına daha uygundur.
97
  full_user_message = f"{MODERATION_SYSTEM_PROMPT}\n\nUser input: '{message}'"
98
 
99
  messages = [
100
  {"role": "user", "content": full_user_message}
101
  ]
102
 
103
- # Doğru chat template kullanımı
104
  text = tokenizer.apply_chat_template(
105
  messages,
106
  tokenize=False,
107
  add_generation_prompt=True
108
  )
109
- # Token sınırını aşarsa kısalt (Bu senaryoda pek olası değil ama iyi bir pratik)
110
  while len(tokenizer(text, add_special_tokens=False).input_ids) > max_ctx_tokens and len(full_user_message) > 100:
111
- full_user_message = full_user_message[:len(full_user_message)-50] # Mesajı sondan kısalt
112
  messages[0]['content'] = full_user_message
113
  text = tokenizer.apply_chat_template(
114
  messages,
@@ -163,7 +151,6 @@ def respond_stream(message, history, max_tokens, temperature, top_p):
163
  finally:
164
  thread.join()
165
 
166
- # Çıktıyı kesin olarak s/u'ya indir
167
  final_label = enforce_s_u(partial_text)
168
  end_time = time.time() if start_time else time.time()
169
  duration = max(1e-6, end_time - start_time)
@@ -172,7 +159,6 @@ def respond_stream(message, history, max_tokens, temperature, top_p):
172
 
173
  demo = gr.ChatInterface(
174
  respond_stream,
175
- chatbot=False, # Bu parametre ChatInterface'de bulunmuyor, chatbot'u gizlemek için temayı kullanabilirsiniz.
176
  additional_inputs=[
177
  gr.Slider(minimum=1, maximum=4, value=1, step=1, label="Max new tokens"),
178
  gr.Slider(minimum=0.0, maximum=1.0, value=0.0, step=0.1, label="Temperature"),
 
41
 
42
  tokenizer = AutoTokenizer.from_pretrained(model_path, local_files_only=True)
43
 
44
+ ### DEĞİŞİKLİK BURADA: ŞABLON BASİTLEŞTİRİLDİ ###
45
+ # 'raise_exception' komutunu içermeyen, eski transformers versiyonlarıyla uyumlu şablon.
46
+ # Zaten kodumuz şablonu doğru formatta beslediği için bu kontrolleri kaldırabiliriz.
47
+ gemma_chat_template_simplified = (
 
 
 
48
  "{% for message in messages %}"
 
 
 
49
  "{% if message['role'] == 'user' %}"
50
  "{{ '<start_of_turn>user\\n' + message['content'] | trim + '<end_of_turn>\\n' }}"
51
  "{% elif message['role'] == 'assistant' %}"
 
57
  "{% endif %}"
58
  )
59
 
 
 
 
60
  if tokenizer.chat_template is None:
61
+ print("Chat template manuel olarak ayarlanıyor (basitleştirilmiş versiyon).")
62
+ tokenizer.chat_template = gemma_chat_template_simplified
63
+ ### DEĞİŞİKLİK SONA ERDİ ###
64
 
65
 
66
  model = AutoModelForCausalLM.from_pretrained(
 
71
  )
72
  model.eval()
73
 
74
+ # Çok katı moderasyon system prompt
75
  MODERATION_SYSTEM_PROMPT = (
76
  "You are a multilingual content moderation classifier. "
77
  "You MUST respond with exactly one lowercase letter: 's' for safe, 'u' for unsafe. "
 
82
  )
83
 
84
  def build_prompt(message, max_ctx_tokens=128):
 
85
  # Sistem mesajını ilk kullanıcı mesajının bir parçası haline getiriyoruz.
 
86
  full_user_message = f"{MODERATION_SYSTEM_PROMPT}\n\nUser input: '{message}'"
87
 
88
  messages = [
89
  {"role": "user", "content": full_user_message}
90
  ]
91
 
 
92
  text = tokenizer.apply_chat_template(
93
  messages,
94
  tokenize=False,
95
  add_generation_prompt=True
96
  )
97
+
98
  while len(tokenizer(text, add_special_tokens=False).input_ids) > max_ctx_tokens and len(full_user_message) > 100:
99
+ full_user_message = full_user_message[:len(full_user_message)-50]
100
  messages[0]['content'] = full_user_message
101
  text = tokenizer.apply_chat_template(
102
  messages,
 
151
  finally:
152
  thread.join()
153
 
 
154
  final_label = enforce_s_u(partial_text)
155
  end_time = time.time() if start_time else time.time()
156
  duration = max(1e-6, end_time - start_time)
 
159
 
160
  demo = gr.ChatInterface(
161
  respond_stream,
 
162
  additional_inputs=[
163
  gr.Slider(minimum=1, maximum=4, value=1, step=1, label="Max new tokens"),
164
  gr.Slider(minimum=0.0, maximum=1.0, value=0.0, step=0.1, label="Temperature"),