Spaces:
Sleeping
Sleeping
Update server.py
Browse files
server.py
CHANGED
|
@@ -14,7 +14,7 @@ from pydantic import BaseModel
|
|
| 14 |
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
| 15 |
|
| 16 |
# --- Configuration ---
|
| 17 |
-
MODEL_ID = "Qwen/Qwen2.5-3B-Instruct"
|
| 18 |
PORT = int(os.environ.get("PORT", 8000))
|
| 19 |
HOST = "0.0.0.0"
|
| 20 |
DB_FILE = "chatbot.db"
|
|
@@ -23,7 +23,7 @@ JSON_SOURCE = "database.json"
|
|
| 23 |
logging.basicConfig(level=logging.INFO)
|
| 24 |
logger = logging.getLogger(__name__)
|
| 25 |
|
| 26 |
-
app = FastAPI(title="Hebrew Smart Home Technician", version="13.
|
| 27 |
|
| 28 |
app.add_middleware(
|
| 29 |
CORSMiddleware,
|
|
@@ -48,6 +48,24 @@ SEARCH_MAP = {
|
|
| 48 |
"מתח": ["3.3V", "5V", "VIN", "Power"]
|
| 49 |
}
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
def init_db():
|
| 52 |
if os.path.exists(DB_FILE): os.remove(DB_FILE)
|
| 53 |
conn = sqlite3.connect(DB_FILE)
|
|
@@ -86,37 +104,29 @@ def expand_query(query: str) -> List[str]:
|
|
| 86 |
return list(search_terms)
|
| 87 |
|
| 88 |
def simplify_schematic_text(text: str) -> str:
|
| 89 |
-
"""
|
| 90 |
-
Cleans raw schematic lines into readable Hebrew.
|
| 91 |
-
Order matters to prevent double-replacement!
|
| 92 |
-
"""
|
| 93 |
-
# 1. Clean specific long component names first
|
| 94 |
text = text.replace("ESP32-DEVKITC-32D_ESP32-DEVKITC-30GPIO", "בקר ESP32")
|
| 95 |
text = text.replace("BOB_19002", "ממיר רמות")
|
| 96 |
-
text = text.replace("06060106_070403", "ממיר רמות")
|
| 97 |
text = text.replace("TLM-SH_board", "הלוח הראשי")
|
| 98 |
text = text.replace("StudentBoard", "הלוח הראשי")
|
| 99 |
-
text = text.replace("040709_0804060105", "הלוח הראשי")
|
| 100 |
|
| 101 |
-
# 2. Clean Generic names
|
| 102 |
-
# Check if we haven't already replaced it (simple check)
|
| 103 |
if "NEXTION" in text:
|
| 104 |
text = text.replace("LCD1 (NEXTION)", "מסך המגע")
|
| 105 |
text = text.replace("HMI (NEXTION)", "מסך המגע")
|
| 106 |
-
text = text.replace("NEXTION", "מסך")
|
| 107 |
|
| 108 |
text = text.replace("LCD1", "מסך")
|
| 109 |
text = text.replace("U2", "הבקר")
|
| 110 |
text = text.replace("U3", "הלוח")
|
| 111 |
text = text.replace("U4", "הממיר")
|
| 112 |
|
| 113 |
-
# 3. Clean Verbs
|
| 114 |
text = text.replace("connects to", "מחובר אל")
|
| 115 |
text = text.replace("Pin", "פין")
|
| 116 |
|
| 117 |
return text
|
| 118 |
|
| 119 |
-
def query_knowledge_base(query: str) -> str:
|
| 120 |
conn = sqlite3.connect(DB_FILE)
|
| 121 |
cursor = conn.cursor()
|
| 122 |
search_terms = expand_query(query)
|
|
@@ -125,7 +135,6 @@ def query_knowledge_base(query: str) -> str:
|
|
| 125 |
results = []
|
| 126 |
seen_ids = set()
|
| 127 |
|
| 128 |
-
# Run Search
|
| 129 |
for term in search_terms:
|
| 130 |
cursor.execute("SELECT id, content, topic FROM knowledge WHERE content LIKE ? OR topic LIKE ?", (f'%{term}%', f'%{term}%'))
|
| 131 |
rows = cursor.fetchall()
|
|
@@ -146,30 +155,25 @@ def query_knowledge_base(query: str) -> str:
|
|
| 146 |
if results:
|
| 147 |
raw_content = results[0][1]
|
| 148 |
|
| 149 |
-
# SCHEMATIC PROCESSING
|
| 150 |
if "Schematic" in raw_content:
|
| 151 |
lines = raw_content.split('\n')
|
| 152 |
relevant_lines = []
|
| 153 |
target_terms = [t.lower() for t in search_terms if len(t) > 1]
|
| 154 |
|
| 155 |
for line in lines:
|
| 156 |
-
# Find lines that mention our search terms AND contain connection info
|
| 157 |
if "connect" in line.lower() and any(t in line.lower() for t in target_terms):
|
| 158 |
clean_line = simplify_schematic_text(line.strip())
|
| 159 |
relevant_lines.append(f"- {clean_line}")
|
| 160 |
|
| 161 |
-
# If we found specific lines, return ONLY them
|
| 162 |
if relevant_lines:
|
| 163 |
context_str = "רשימת החיבורים הרלוונטית שנמצאה:\n" + "\n".join(relevant_lines)
|
| 164 |
-
|
| 165 |
-
return context_str
|
| 166 |
else:
|
| 167 |
-
|
| 168 |
-
return "נמצא קובץ שרטוט, אך לא נמצאו חיבורים ספציפיים לרכיב שביקשת."
|
| 169 |
|
| 170 |
-
return raw_content
|
| 171 |
|
| 172 |
-
return ""
|
| 173 |
|
| 174 |
def save_message(role: str, content: str):
|
| 175 |
try:
|
|
@@ -225,20 +229,24 @@ async def chat_completions(request: ChatCompletionRequest):
|
|
| 225 |
context = ""
|
| 226 |
if last_user_msg:
|
| 227 |
save_message("user", last_user_msg.content)
|
| 228 |
-
context = query_knowledge_base(last_user_msg.content)
|
| 229 |
|
| 230 |
-
# --- הנחיה ברורה וחד-משמעית ---
|
| 231 |
if context:
|
| 232 |
sys_msg = (
|
| 233 |
-
"אתה
|
| 234 |
-
"ה
|
| 235 |
-
"
|
| 236 |
-
"
|
| 237 |
-
"
|
| 238 |
-
f"\nמידע
|
| 239 |
)
|
| 240 |
else:
|
| 241 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
if request.messages[0].role == "system":
|
| 244 |
request.messages[0].content = sys_msg
|
|
@@ -269,9 +277,18 @@ async def chat_completions(request: ChatCompletionRequest):
|
|
| 269 |
async def stream_generator():
|
| 270 |
full_text = ""
|
| 271 |
for text in streamer:
|
|
|
|
| 272 |
if text:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
full_text += text
|
| 274 |
yield f"data: {json.dumps({'choices': [{'delta': {'content': text}}]}, ensure_ascii=False)}\n\n"
|
|
|
|
| 275 |
save_message("assistant", full_text)
|
| 276 |
yield "data: [DONE]\n\n"
|
| 277 |
|
|
|
|
| 14 |
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
| 15 |
|
| 16 |
# --- Configuration ---
|
| 17 |
+
MODEL_ID = "Qwen/Qwen2.5-3B-Instruct"
|
| 18 |
PORT = int(os.environ.get("PORT", 8000))
|
| 19 |
HOST = "0.0.0.0"
|
| 20 |
DB_FILE = "chatbot.db"
|
|
|
|
| 23 |
logging.basicConfig(level=logging.INFO)
|
| 24 |
logger = logging.getLogger(__name__)
|
| 25 |
|
| 26 |
+
app = FastAPI(title="Hebrew Smart Home Technician", version="13.1.0")
|
| 27 |
|
| 28 |
app.add_middleware(
|
| 29 |
CORSMiddleware,
|
|
|
|
| 48 |
"מתח": ["3.3V", "5V", "VIN", "Power"]
|
| 49 |
}
|
| 50 |
|
| 51 |
+
# --- שומר שפה (מורחב) ---
|
| 52 |
+
def is_valid_text(text: str) -> bool:
|
| 53 |
+
"""
|
| 54 |
+
בודק אם הטקסט מכיל תווים בשפות אסורות.
|
| 55 |
+
מחזיר False אם נמצא תו אסור.
|
| 56 |
+
"""
|
| 57 |
+
for char in text:
|
| 58 |
+
code = ord(char)
|
| 59 |
+
# CJK Unified Ideographs (Chinese)
|
| 60 |
+
if 0x4E00 <= code <= 0x9FFF: return False
|
| 61 |
+
# Cyrillic (Russian)
|
| 62 |
+
if 0x0400 <= code <= 0x04FF: return False
|
| 63 |
+
# Hiragana & Katakana (Japanese)
|
| 64 |
+
if 0x3040 <= code <= 0x30FF: return False
|
| 65 |
+
# Hangul (Korean)
|
| 66 |
+
if 0xAC00 <= code <= 0xD7AF: return False
|
| 67 |
+
return True
|
| 68 |
+
|
| 69 |
def init_db():
|
| 70 |
if os.path.exists(DB_FILE): os.remove(DB_FILE)
|
| 71 |
conn = sqlite3.connect(DB_FILE)
|
|
|
|
| 104 |
return list(search_terms)
|
| 105 |
|
| 106 |
def simplify_schematic_text(text: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
text = text.replace("ESP32-DEVKITC-32D_ESP32-DEVKITC-30GPIO", "בקר ESP32")
|
| 108 |
text = text.replace("BOB_19002", "ממיר רמות")
|
| 109 |
+
text = text.replace("06060106_070403", "ממיר רמות")
|
| 110 |
text = text.replace("TLM-SH_board", "הלוח הראשי")
|
| 111 |
text = text.replace("StudentBoard", "הלוח הראשי")
|
| 112 |
+
text = text.replace("040709_0804060105", "הלוח הראשי")
|
| 113 |
|
|
|
|
|
|
|
| 114 |
if "NEXTION" in text:
|
| 115 |
text = text.replace("LCD1 (NEXTION)", "מסך המגע")
|
| 116 |
text = text.replace("HMI (NEXTION)", "מסך המגע")
|
| 117 |
+
text = text.replace("NEXTION", "מסך")
|
| 118 |
|
| 119 |
text = text.replace("LCD1", "מסך")
|
| 120 |
text = text.replace("U2", "הבקר")
|
| 121 |
text = text.replace("U3", "הלוח")
|
| 122 |
text = text.replace("U4", "הממיר")
|
| 123 |
|
|
|
|
| 124 |
text = text.replace("connects to", "מחובר אל")
|
| 125 |
text = text.replace("Pin", "פין")
|
| 126 |
|
| 127 |
return text
|
| 128 |
|
| 129 |
+
def query_knowledge_base(query: str) -> Tuple[str, List[str]]:
|
| 130 |
conn = sqlite3.connect(DB_FILE)
|
| 131 |
cursor = conn.cursor()
|
| 132 |
search_terms = expand_query(query)
|
|
|
|
| 135 |
results = []
|
| 136 |
seen_ids = set()
|
| 137 |
|
|
|
|
| 138 |
for term in search_terms:
|
| 139 |
cursor.execute("SELECT id, content, topic FROM knowledge WHERE content LIKE ? OR topic LIKE ?", (f'%{term}%', f'%{term}%'))
|
| 140 |
rows = cursor.fetchall()
|
|
|
|
| 155 |
if results:
|
| 156 |
raw_content = results[0][1]
|
| 157 |
|
|
|
|
| 158 |
if "Schematic" in raw_content:
|
| 159 |
lines = raw_content.split('\n')
|
| 160 |
relevant_lines = []
|
| 161 |
target_terms = [t.lower() for t in search_terms if len(t) > 1]
|
| 162 |
|
| 163 |
for line in lines:
|
|
|
|
| 164 |
if "connect" in line.lower() and any(t in line.lower() for t in target_terms):
|
| 165 |
clean_line = simplify_schematic_text(line.strip())
|
| 166 |
relevant_lines.append(f"- {clean_line}")
|
| 167 |
|
|
|
|
| 168 |
if relevant_lines:
|
| 169 |
context_str = "רשימת החיבורים הרלוונטית שנמצאה:\n" + "\n".join(relevant_lines)
|
| 170 |
+
return context_str, search_terms
|
|
|
|
| 171 |
else:
|
| 172 |
+
return "נמצא קובץ שרטוט, אך לא נמצאו חיבורים ספציפיים לרכיב ��ביקשת.", search_terms
|
|
|
|
| 173 |
|
| 174 |
+
return raw_content, search_terms
|
| 175 |
|
| 176 |
+
return "", search_terms
|
| 177 |
|
| 178 |
def save_message(role: str, content: str):
|
| 179 |
try:
|
|
|
|
| 229 |
context = ""
|
| 230 |
if last_user_msg:
|
| 231 |
save_message("user", last_user_msg.content)
|
| 232 |
+
context, _ = query_knowledge_base(last_user_msg.content)
|
| 233 |
|
|
|
|
| 234 |
if context:
|
| 235 |
sys_msg = (
|
| 236 |
+
"תפקידך: אתה המדריך הטכני של פרויקט 'בית חכם תלם'.\n"
|
| 237 |
+
"הנחיות קריטיות:\n"
|
| 238 |
+
"1. דבר אך ורק בשפה העברית. אל תשתמש בשום שפה אחרת.\n"
|
| 239 |
+
"2. השתמש במידע המצורף כדי לענות.\n"
|
| 240 |
+
"3. אם המידע הוא רשימת חיבורים, הסבר אותה במשפט פשוט.\n"
|
| 241 |
+
f"\nמידע טכני:\n{context}"
|
| 242 |
)
|
| 243 |
else:
|
| 244 |
+
# הנחיית חירום משופרת למקרים ללא הקשר
|
| 245 |
+
sys_msg = (
|
| 246 |
+
"System: You are a helpful assistant speaking ONLY Hebrew.\n"
|
| 247 |
+
"Instruction: Reply to the user in Hebrew. Do not use Chinese, Russian, or English.\n"
|
| 248 |
+
"If the user says Shalom, say Shalom back."
|
| 249 |
+
)
|
| 250 |
|
| 251 |
if request.messages[0].role == "system":
|
| 252 |
request.messages[0].content = sys_msg
|
|
|
|
| 277 |
async def stream_generator():
|
| 278 |
full_text = ""
|
| 279 |
for text in streamer:
|
| 280 |
+
# הגנה בזמן אמת: אם מתגלה סינית, עוצרים מיד!
|
| 281 |
if text:
|
| 282 |
+
if not is_valid_text(text):
|
| 283 |
+
logger.warning(f"Blocked forbidden text: {text}")
|
| 284 |
+
# אופציה א: דלג על התו (עלול ליצור מילים שבורות)
|
| 285 |
+
# continue
|
| 286 |
+
# אופציה ב (מומלצת): עצור את התשובה כדי לא להציג זבל
|
| 287 |
+
break
|
| 288 |
+
|
| 289 |
full_text += text
|
| 290 |
yield f"data: {json.dumps({'choices': [{'delta': {'content': text}}]}, ensure_ascii=False)}\n\n"
|
| 291 |
+
|
| 292 |
save_message("assistant", full_text)
|
| 293 |
yield "data: [DONE]\n\n"
|
| 294 |
|