ItamarMordo commited on
Commit
77540c0
·
verified ·
1 Parent(s): 860da06

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +39 -13
server.py CHANGED
@@ -15,7 +15,6 @@ from pydantic import BaseModel
15
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
16
 
17
  # --- Configuration ---
18
- # שימוש במודל 1.5B למהירות מקסימלית על CPU
19
  MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
20
  PORT = int(os.environ.get("PORT", 8000))
21
  HOST = "0.0.0.0"
@@ -27,7 +26,7 @@ logging.basicConfig(level=logging.INFO)
27
  logger = logging.getLogger(__name__)
28
 
29
  # --- FastAPI ---
30
- app = FastAPI(title="Hebrew RAG Chatbot (Refined)", version="3.9.1")
31
 
32
  app.add_middleware(
33
  CORSMiddleware,
@@ -42,6 +41,25 @@ model = None
42
  tokenizer = None
43
  device = "cpu"
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  # --- Hebrew Helpers ---
46
  STOP_WORDS = {
47
  "של", "את", "על", "עם", "כי", "זה", "או", "אם", "גם", "הוא",
@@ -135,7 +153,7 @@ class Message(BaseModel):
135
  class ChatCompletionRequest(BaseModel):
136
  messages: List[Message]
137
  max_tokens: Optional[int] = 512
138
- temperature: Optional[float] = 0.3 # עלייה קלה בטמפרטורה לתיקון שגיאות כתיב
139
  top_p: Optional[float] = 0.9
140
  stream: Optional[bool] = False
141
 
@@ -194,21 +212,21 @@ async def chat_completions(request: ChatCompletionRequest):
194
  retrieved = query_knowledge_base(last_msg.content)
195
 
196
  sys_prompt = (
197
- "System: You are a helpful assistant for the 'Telem Smart Home' project. "
198
- "Instructions:\n"
199
- "1. Answer ONLY in Hebrew (עברית).\n"
200
- "2. Use the provided Context to answer the question accurately.\n"
201
- "3. If the answer is not in the context, apologize politely in Hebrew."
202
  )
203
 
204
  if retrieved:
205
  topics = ", ".join(sorted(list(set([i[0] for i in retrieved]))))
206
  content = "\n---\n".join([i[1] for i in retrieved])
207
- sys_prompt += f"\n\nContext ({topics}):\n{content}\n\nInstruction: Answer in Hebrew based on the context above."
208
  else:
209
  sys_prompt += (
210
  "\n\nContext: No specific document found.\n"
211
- "Instruction: If this is a greeting (Shalom), reply politely in Hebrew. "
212
  "Otherwise, say you don't know."
213
  )
214
 
@@ -229,11 +247,12 @@ async def chat_completions(request: ChatCompletionRequest):
229
  attention_mask=attention_mask,
230
  max_new_tokens=request.max_tokens,
231
  do_sample=True,
232
- temperature=0.3, # עלייה קלה בטמפרטורה
233
  top_p=0.9,
234
- top_k=40,
235
  pad_token_id=tokenizer.eos_token_id,
236
- repetition_penalty=1.05, # ענישה מזערית לשמירת שטף
 
237
  )
238
 
239
  if request.stream:
@@ -246,6 +265,13 @@ async def chat_completions(request: ChatCompletionRequest):
246
  full_text = ""
247
  for text in streamer:
248
  if text:
 
 
 
 
 
 
 
249
  full_text += text
250
  yield f"data: {json.dumps({'choices': [{'delta': {'content': text}}]}, ensure_ascii=False)}\n\n"
251
  save_message("assistant", full_text)
 
15
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
16
 
17
  # --- Configuration ---
 
18
  MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
19
  PORT = int(os.environ.get("PORT", 8000))
20
  HOST = "0.0.0.0"
 
26
  logger = logging.getLogger(__name__)
27
 
28
  # --- FastAPI ---
29
+ app = FastAPI(title="Hebrew RAG Chatbot (Protected)", version="4.0.0")
30
 
31
  app.add_middleware(
32
  CORSMiddleware,
 
41
  tokenizer = None
42
  device = "cpu"
43
 
44
+ # --- Language Guard Logic ---
45
+ # טווחי יוניקוד: ערבית, סינית (CJK), יפנית, קוריאנית, קירילית (רוסית)
46
+ FORBIDDEN_RANGES = [
47
+ (0x0600, 0x06FF), # Arabic
48
+ (0x4E00, 0x9FFF), # CJK Unified Ideographs (Chinese)
49
+ (0x3040, 0x309F), # Hiragana (Japanese)
50
+ (0x30A0, 0x30FF), # Katakana (Japanese)
51
+ (0x0400, 0x04FF), # Cyrillic
52
+ ]
53
+
54
+ def contains_forbidden_chars(text: str) -> bool:
55
+ """בודק אם הטקסט מכיל תווים בשפות אסורות (סינית, ערבית וכו')"""
56
+ for char in text:
57
+ code = ord(char)
58
+ for start, end in FORBIDDEN_RANGES:
59
+ if start <= code <= end:
60
+ return True
61
+ return False
62
+
63
  # --- Hebrew Helpers ---
64
  STOP_WORDS = {
65
  "של", "את", "על", "עם", "כי", "זה", "או", "אם", "גם", "הוא",
 
153
  class ChatCompletionRequest(BaseModel):
154
  messages: List[Message]
155
  max_tokens: Optional[int] = 512
156
+ temperature: Optional[float] = 0.3
157
  top_p: Optional[float] = 0.9
158
  stream: Optional[bool] = False
159
 
 
212
  retrieved = query_knowledge_base(last_msg.content)
213
 
214
  sys_prompt = (
215
+ "You are a helpful assistant for the 'Telem Smart Home' project. "
216
+ "INSTRUCTIONS:\n"
217
+ "1. Answer ONLY in Hebrew (עברית). English is allowed only for technical terms (e.g. ESP32, WiFi).\n"
218
+ "2. NEVER use Arabic, Chinese, or Russian characters.\n"
219
+ "3. Use the provided Context to answer."
220
  )
221
 
222
  if retrieved:
223
  topics = ", ".join(sorted(list(set([i[0] for i in retrieved]))))
224
  content = "\n---\n".join([i[1] for i in retrieved])
225
+ sys_prompt += f"\n\nContext ({topics}):\n{content}\n\nAnswer in Hebrew:"
226
  else:
227
  sys_prompt += (
228
  "\n\nContext: No specific document found.\n"
229
+ "Instruction: If this is 'Shalom', reply politely in Hebrew. "
230
  "Otherwise, say you don't know."
231
  )
232
 
 
247
  attention_mask=attention_mask,
248
  max_new_tokens=request.max_tokens,
249
  do_sample=True,
250
+ temperature=0.3,
251
  top_p=0.9,
252
+ top_k=40,
253
  pad_token_id=tokenizer.eos_token_id,
254
+ repetition_penalty=1.05,
255
+ no_repeat_ngram_size=3 # Prevents loops like "Essential For The Project"
256
  )
257
 
258
  if request.stream:
 
265
  full_text = ""
266
  for text in streamer:
267
  if text:
268
+ # --- THE GUARD ---
269
+ # אם המודל מנסה לפלוט סינית/ערבית - אנחנו חותכים אותו כאן ועכשיו.
270
+ if contains_forbidden_chars(text):
271
+ logger.warning(f"Blocked forbidden language output: {text}")
272
+ # אופציונלי: אפשר לעצור את הזרם לגמרי עם break
273
+ continue
274
+
275
  full_text += text
276
  yield f"data: {json.dumps({'choices': [{'delta': {'content': text}}]}, ensure_ascii=False)}\n\n"
277
  save_message("assistant", full_text)