Spaces:
Sleeping
Sleeping
Update server.py
Browse files
server.py
CHANGED
|
@@ -22,7 +22,7 @@ HF_TOKEN = os.environ.get("HF_TOKEN")
|
|
| 22 |
logging.basicConfig(level=logging.INFO)
|
| 23 |
logger = logging.getLogger(__name__)
|
| 24 |
|
| 25 |
-
app = FastAPI(title="Hebrew Smart Home Technician", version="10.
|
| 26 |
|
| 27 |
app.add_middleware(
|
| 28 |
CORSMiddleware,
|
|
@@ -34,7 +34,7 @@ app.add_middleware(
|
|
| 34 |
|
| 35 |
client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)
|
| 36 |
|
| 37 |
-
# --- מילון מונחים לחיפוש
|
| 38 |
SEARCH_MAP = {
|
| 39 |
"בקר": ["ESP32", "Controller", "Main Board", "DevKit"],
|
| 40 |
"מסך": ["Nextion", "Display", "Screen", "HMI", "Nextion Screen"],
|
|
@@ -89,15 +89,12 @@ def simplify_schematic_text(text: str) -> str:
|
|
| 89 |
Cleans up the English schematic text and translates key terms to Hebrew
|
| 90 |
for better readability in the chat.
|
| 91 |
"""
|
| 92 |
-
# 1. ניקוי רעשים בסיסי (הסרת סוגריים אם נותרו)
|
| 93 |
text = re.sub(r'\([A-Za-z0-9_\-]+\)', '', text)
|
| 94 |
|
| 95 |
-
# 2. פישוט שמות פינים טכניים
|
| 96 |
text = text.replace("D16_or_RX2", "RX2")
|
| 97 |
text = text.replace("D17_or_TX2", "TX2")
|
| 98 |
text = text.replace("3V3", "3.3V")
|
| 99 |
|
| 100 |
-
# 3. תרגום לעברית (מותאם ל-DEVICE_MAP החדש ב-GUI)
|
| 101 |
replacements = {
|
| 102 |
"Level Shifter": "ממיר רמות",
|
| 103 |
"Student Board": "לוח תלמיד",
|
|
@@ -110,11 +107,9 @@ def simplify_schematic_text(text: str) -> str:
|
|
| 110 |
}
|
| 111 |
|
| 112 |
for eng, heb in replacements.items():
|
| 113 |
-
# שימוש ב-Regex כדי להחליף מילים שלמות בלבד
|
| 114 |
text = re.sub(r'\b' + re.escape(eng) + r'\b', heb, text)
|
| 115 |
|
| 116 |
-
|
| 117 |
-
text = text.replace("Pin Pin", "פין") # Fix double pins just in case
|
| 118 |
text = text.replace("פין פין", "פין")
|
| 119 |
text = re.sub(r'\s+', ' ', text).strip()
|
| 120 |
|
|
@@ -127,9 +122,9 @@ def query_knowledge_base(query: str) -> str:
|
|
| 127 |
search_terms = expand_query(query)
|
| 128 |
logger.info(f"🔍 Searching for: {search_terms}")
|
| 129 |
|
| 130 |
-
# בדיקה האם זו שאלה כללית על חיבורים
|
| 131 |
is_general_schematic_query = any(x in query for x in ["הכל", "כל החיבורים", "שרטוט", "מה מחובר", "לאן", "פינים"])
|
| 132 |
-
|
|
|
|
| 133 |
results = []
|
| 134 |
seen_ids = set()
|
| 135 |
|
|
@@ -140,13 +135,13 @@ def query_knowledge_base(query: str) -> str:
|
|
| 140 |
if row_id not in seen_ids:
|
| 141 |
score = 1
|
| 142 |
if "Schematic" in content:
|
| 143 |
-
score += 100
|
| 144 |
elif term.lower() in topic.lower():
|
| 145 |
score += 10
|
| 146 |
results.append((score, content))
|
| 147 |
seen_ids.add(row_id)
|
| 148 |
|
| 149 |
-
#
|
| 150 |
if not results and is_general_schematic_query:
|
| 151 |
cursor.execute("SELECT id, content, topic FROM knowledge WHERE content LIKE '%Schematic%'")
|
| 152 |
row = cursor.fetchone()
|
|
@@ -160,24 +155,27 @@ def query_knowledge_base(query: str) -> str:
|
|
| 160 |
if results:
|
| 161 |
raw_content = results[0][1]
|
| 162 |
|
|
|
|
| 163 |
if "Schematic" in raw_content:
|
| 164 |
lines = raw_content.split('\n')
|
| 165 |
relevant_lines = []
|
| 166 |
|
| 167 |
-
# אם זו שאלה כללית
|
|
|
|
|
|
|
|
|
|
| 168 |
if is_general_schematic_query:
|
| 169 |
for line in lines:
|
| 170 |
if "connect" in line.lower():
|
| 171 |
relevant_lines.append(line.strip())
|
| 172 |
else:
|
| 173 |
-
# סינון רגיל לפי מילות מפתח
|
| 174 |
target_terms = [t.lower() for t in search_terms if len(t) > 1]
|
| 175 |
for line in lines:
|
| 176 |
if "connect" in line.lower() and any(t in line.lower() for t in target_terms):
|
| 177 |
relevant_lines.append(line.strip())
|
| 178 |
|
| 179 |
clean_text = simplify_schematic_text("\n".join(relevant_lines))
|
| 180 |
-
return f"להלן
|
| 181 |
|
| 182 |
return raw_content
|
| 183 |
return ""
|
|
@@ -198,7 +196,7 @@ class Message(BaseModel):
|
|
| 198 |
class ChatCompletionRequest(BaseModel):
|
| 199 |
messages: List[Message]
|
| 200 |
max_tokens: Optional[int] = 1024
|
| 201 |
-
temperature: Optional[float] = 0.
|
| 202 |
stream: Optional[bool] = False
|
| 203 |
|
| 204 |
@app.on_event("startup")
|
|
@@ -215,19 +213,20 @@ async def chat_completions(request: ChatCompletionRequest):
|
|
| 215 |
save_message("user", last_user_msg.content)
|
| 216 |
context = query_knowledge_base(last_user_msg.content)
|
| 217 |
|
|
|
|
| 218 |
sys_msg = (
|
| 219 |
-
"תפקידך: טכנאי מומחה לפרויקט 'בית חכם תלם'.\n"
|
| 220 |
-
"הנחיות
|
| 221 |
-
"1.
|
| 222 |
-
"2.
|
| 223 |
-
"3.
|
| 224 |
-
"4. הע
|
| 225 |
)
|
| 226 |
|
| 227 |
if context:
|
| 228 |
-
sys_msg += f"\n---
|
| 229 |
else:
|
| 230 |
-
sys_msg += "\n(לא נמצא מידע ספציפי
|
| 231 |
|
| 232 |
messages_payload = [msg.dict() for msg in request.messages]
|
| 233 |
|
|
|
|
| 22 |
logging.basicConfig(level=logging.INFO)
|
| 23 |
logger = logging.getLogger(__name__)
|
| 24 |
|
| 25 |
+
app = FastAPI(title="Hebrew Smart Home Technician", version="10.2.0")
|
| 26 |
|
| 27 |
app.add_middleware(
|
| 28 |
CORSMiddleware,
|
|
|
|
| 34 |
|
| 35 |
client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)
|
| 36 |
|
| 37 |
+
# --- מילון מונחים לחיפוש ---
|
| 38 |
SEARCH_MAP = {
|
| 39 |
"בקר": ["ESP32", "Controller", "Main Board", "DevKit"],
|
| 40 |
"מסך": ["Nextion", "Display", "Screen", "HMI", "Nextion Screen"],
|
|
|
|
| 89 |
Cleans up the English schematic text and translates key terms to Hebrew
|
| 90 |
for better readability in the chat.
|
| 91 |
"""
|
|
|
|
| 92 |
text = re.sub(r'\([A-Za-z0-9_\-]+\)', '', text)
|
| 93 |
|
|
|
|
| 94 |
text = text.replace("D16_or_RX2", "RX2")
|
| 95 |
text = text.replace("D17_or_TX2", "TX2")
|
| 96 |
text = text.replace("3V3", "3.3V")
|
| 97 |
|
|
|
|
| 98 |
replacements = {
|
| 99 |
"Level Shifter": "ממיר רמות",
|
| 100 |
"Student Board": "לוח תלמיד",
|
|
|
|
| 107 |
}
|
| 108 |
|
| 109 |
for eng, heb in replacements.items():
|
|
|
|
| 110 |
text = re.sub(r'\b' + re.escape(eng) + r'\b', heb, text)
|
| 111 |
|
| 112 |
+
text = text.replace("Pin Pin", "פין")
|
|
|
|
| 113 |
text = text.replace("פין פין", "פין")
|
| 114 |
text = re.sub(r'\s+', ' ', text).strip()
|
| 115 |
|
|
|
|
| 122 |
search_terms = expand_query(query)
|
| 123 |
logger.info(f"🔍 Searching for: {search_terms}")
|
| 124 |
|
|
|
|
| 125 |
is_general_schematic_query = any(x in query for x in ["הכל", "כל החיבורים", "שרטוט", "מה מחובר", "לאן", "פינים"])
|
| 126 |
+
is_definition_query = any(x in query for x in ["מה זה", "הסבר", "מידע על", "תאר"])
|
| 127 |
+
|
| 128 |
results = []
|
| 129 |
seen_ids = set()
|
| 130 |
|
|
|
|
| 135 |
if row_id not in seen_ids:
|
| 136 |
score = 1
|
| 137 |
if "Schematic" in content:
|
| 138 |
+
score += 100
|
| 139 |
elif term.lower() in topic.lower():
|
| 140 |
score += 10
|
| 141 |
results.append((score, content))
|
| 142 |
seen_ids.add(row_id)
|
| 143 |
|
| 144 |
+
# Fallback logic
|
| 145 |
if not results and is_general_schematic_query:
|
| 146 |
cursor.execute("SELECT id, content, topic FROM knowledge WHERE content LIKE '%Schematic%'")
|
| 147 |
row = cursor.fetchone()
|
|
|
|
| 155 |
if results:
|
| 156 |
raw_content = results[0][1]
|
| 157 |
|
| 158 |
+
# אם זה תוכן של שרטוט, ננקה אותו
|
| 159 |
if "Schematic" in raw_content:
|
| 160 |
lines = raw_content.split('\n')
|
| 161 |
relevant_lines = []
|
| 162 |
|
| 163 |
+
# אם זו שאלת הגדרה כללית ("מה זה הפרויקט?"), אל תסנן שורות, תחזיר הכל
|
| 164 |
+
if is_definition_query and not is_general_schematic_query:
|
| 165 |
+
return simplify_schematic_text(raw_content)
|
| 166 |
+
|
| 167 |
if is_general_schematic_query:
|
| 168 |
for line in lines:
|
| 169 |
if "connect" in line.lower():
|
| 170 |
relevant_lines.append(line.strip())
|
| 171 |
else:
|
|
|
|
| 172 |
target_terms = [t.lower() for t in search_terms if len(t) > 1]
|
| 173 |
for line in lines:
|
| 174 |
if "connect" in line.lower() and any(t in line.lower() for t in target_terms):
|
| 175 |
relevant_lines.append(line.strip())
|
| 176 |
|
| 177 |
clean_text = simplify_schematic_text("\n".join(relevant_lines))
|
| 178 |
+
return f"להלן המידע הטכני שנמצא:\n{clean_text}"
|
| 179 |
|
| 180 |
return raw_content
|
| 181 |
return ""
|
|
|
|
| 196 |
class ChatCompletionRequest(BaseModel):
|
| 197 |
messages: List[Message]
|
| 198 |
max_tokens: Optional[int] = 1024
|
| 199 |
+
temperature: Optional[float] = 0.3 # קצת יותר יצירתיות למשפטים
|
| 200 |
stream: Optional[bool] = False
|
| 201 |
|
| 202 |
@app.on_event("startup")
|
|
|
|
| 213 |
save_message("user", last_user_msg.content)
|
| 214 |
context = query_knowledge_base(last_user_msg.content)
|
| 215 |
|
| 216 |
+
# --- השינוי הגדול: הנחיות "אנושיות" יותר ---
|
| 217 |
sys_msg = (
|
| 218 |
+
"תפקידך: טכנאי מומחה וידידותי לפרויקט 'בית חכם תלם'.\n"
|
| 219 |
+
"הנחיות:\n"
|
| 220 |
+
"1. ענה בעברית ברורה ובמשפטים מלאים.\n"
|
| 221 |
+
"2. השתמש במידע הטכני המצורף למטה כדי לענות.\n"
|
| 222 |
+
"3. אם המשתמש שואל על חיבורים, הסבר לו מה מחובר למה (למשל: 'המסך מחובר לפין RX בבקר'). אל תזרוק סתם שמות של פינים.\n"
|
| 223 |
+
"4. אם המידע לא קיים בהקשר, אמור זאת בנימוס.\n"
|
| 224 |
)
|
| 225 |
|
| 226 |
if context:
|
| 227 |
+
sys_msg += f"\n--- מידע טכני מהמערכת ---\n{context}\n------------------------------------"
|
| 228 |
else:
|
| 229 |
+
sys_msg += "\n(לא נמצא מידע ספציפי במאגר על נושא זה. נסה לענות על בסיס ידע כללי אם זה רלוונטי, או בקש מהמשתמש לפרט)."
|
| 230 |
|
| 231 |
messages_payload = [msg.dict() for msg in request.messages]
|
| 232 |
|