Spaces:
Sleeping
Sleeping
Update server.py
Browse files
server.py
CHANGED
|
@@ -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="
|
| 27 |
|
| 28 |
app.add_middleware(
|
| 29 |
CORSMiddleware,
|
|
@@ -37,13 +37,13 @@ model = None
|
|
| 37 |
tokenizer = None
|
| 38 |
device = "cpu"
|
| 39 |
|
| 40 |
-
# --- מילון מונחים
|
| 41 |
SEARCH_MAP = {
|
| 42 |
"בקר": ["ESP32", "U2", "Controller"],
|
| 43 |
"מסך": ["Nextion", "LCD1", "HMI", "Display"],
|
| 44 |
"שרטוט": ["Schematic", "Connections", "Pin", "Net"],
|
| 45 |
"חיבור": ["Connect", "Wire", "Signal"],
|
| 46 |
-
"תקלה": ["Error", "Problem", "Fix"],
|
| 47 |
"לא עובד": ["Power", "Voltage", "GND", "Disconnect"],
|
| 48 |
"זרם": ["ACS712", "Sensor", "Current"],
|
| 49 |
"מתח": ["3.3V", "5V", "VIN", "Power"],
|
|
@@ -90,31 +90,10 @@ def expand_query(query: str) -> List[str]:
|
|
| 90 |
search_terms.add(f"Pin {w}")
|
| 91 |
return list(search_terms)
|
| 92 |
|
| 93 |
-
def
|
| 94 |
-
"""מחזיר רק שורות רלוונטיות מהשרטוט כדי לא לבלבל את המודל"""
|
| 95 |
-
lines = full_context.split('\n')
|
| 96 |
-
relevant_lines = []
|
| 97 |
-
|
| 98 |
-
# מילים שחובה שיהיו בשורה כדי שהיא תיחשב
|
| 99 |
-
target_terms = [t.lower() for t in query_terms if len(t) > 1 and t.lower() not in ["connect", "pin", "to"]]
|
| 100 |
-
|
| 101 |
-
for line in lines:
|
| 102 |
-
line_lower = line.lower()
|
| 103 |
-
if "schematic connections" in line_lower:
|
| 104 |
-
continue # מדלג על הכותרת כדי לא לחזור עליה
|
| 105 |
-
|
| 106 |
-
# אם השורה מכילה את הרכיב המבוקש (למשל LCD1)
|
| 107 |
-
if any(t in line_lower for t in target_terms):
|
| 108 |
-
relevant_lines.append(line.strip())
|
| 109 |
-
|
| 110 |
-
if not relevant_lines:
|
| 111 |
-
return full_context
|
| 112 |
-
|
| 113 |
-
return "\n".join(relevant_lines)
|
| 114 |
-
|
| 115 |
-
def query_knowledge_base(query: str) -> Tuple[str, List[str]]:
|
| 116 |
conn = sqlite3.connect(DB_FILE)
|
| 117 |
cursor = conn.cursor()
|
|
|
|
| 118 |
search_terms = expand_query(query)
|
| 119 |
logger.info(f"🔍 Searching for: {search_terms}")
|
| 120 |
|
|
@@ -127,15 +106,14 @@ def query_knowledge_base(query: str) -> Tuple[str, List[str]]:
|
|
| 127 |
for row_id, content, topic in rows:
|
| 128 |
if row_id not in seen_ids:
|
| 129 |
score = 1
|
| 130 |
-
is_schematic = "Schematic" in content or "Connections" in content
|
| 131 |
-
is_tech_query = any(x in query for x in ["שרטוט", "חיבור", "פין", "לאן", "מחובר"])
|
| 132 |
|
| 133 |
-
|
|
|
|
| 134 |
score += 100
|
| 135 |
elif term.lower() in topic.lower():
|
| 136 |
score += 10
|
| 137 |
|
| 138 |
-
#
|
| 139 |
numbers_in_query = [int(s) for s in query.split() if s.isdigit()]
|
| 140 |
for num in numbers_in_query:
|
| 141 |
if str(num) in content:
|
|
@@ -143,18 +121,15 @@ def query_knowledge_base(query: str) -> Tuple[str, List[str]]:
|
|
| 143 |
|
| 144 |
results.append((score, content))
|
| 145 |
seen_ids.add(row_id)
|
|
|
|
| 146 |
conn.close()
|
| 147 |
|
| 148 |
results.sort(key=lambda x: x[0], reverse=True)
|
| 149 |
|
|
|
|
| 150 |
if results:
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
# סינון חכם: שולח למודל רק את השורות הרלוונטיות לרכיב
|
| 154 |
-
filtered = filter_schematic_context(best_content, search_terms)
|
| 155 |
-
return filtered, search_terms
|
| 156 |
-
return best_content, search_terms
|
| 157 |
-
return "", search_terms
|
| 158 |
|
| 159 |
def save_message(role: str, content: str):
|
| 160 |
try:
|
|
@@ -171,8 +146,8 @@ class Message(BaseModel):
|
|
| 171 |
|
| 172 |
class ChatCompletionRequest(BaseModel):
|
| 173 |
messages: List[Message]
|
| 174 |
-
max_tokens: Optional[int] =
|
| 175 |
-
temperature: Optional[float] = 0.
|
| 176 |
stream: Optional[bool] = False
|
| 177 |
|
| 178 |
@app.on_event("startup")
|
|
@@ -209,21 +184,22 @@ async def chat_completions(request: ChatCompletionRequest):
|
|
| 209 |
|
| 210 |
context = ""
|
| 211 |
if last_user_msg:
|
| 212 |
-
|
| 213 |
-
context
|
| 214 |
|
|
|
|
| 215 |
if context:
|
| 216 |
sys_msg = (
|
| 217 |
-
"אתה מהנדס
|
| 218 |
-
"הנחיות
|
| 219 |
-
"1.
|
| 220 |
-
"2.
|
| 221 |
-
"3.
|
| 222 |
-
"4.
|
| 223 |
-
f"\n
|
| 224 |
)
|
| 225 |
else:
|
| 226 |
-
sys_msg = "אתה עוזר חכם לפרויקט תלם. ענה בעברית."
|
| 227 |
|
| 228 |
if request.messages[0].role == "system":
|
| 229 |
request.messages[0].content = sys_msg
|
|
@@ -238,11 +214,11 @@ async def chat_completions(request: ChatCompletionRequest):
|
|
| 238 |
gen_kwargs = dict(
|
| 239 |
inputs=prompt_ids,
|
| 240 |
max_new_tokens=request.max_tokens,
|
| 241 |
-
temperature=0.
|
| 242 |
top_p=0.9,
|
| 243 |
do_sample=True,
|
| 244 |
pad_token_id=tokenizer.eos_token_id,
|
| 245 |
-
repetition_penalty=1.1 #
|
| 246 |
)
|
| 247 |
|
| 248 |
if request.stream:
|
|
@@ -257,7 +233,7 @@ async def chat_completions(request: ChatCompletionRequest):
|
|
| 257 |
if text:
|
| 258 |
full_text += text
|
| 259 |
yield f"data: {json.dumps({'choices': [{'delta': {'content': text}}]}, ensure_ascii=False)}\n\n"
|
| 260 |
-
|
| 261 |
yield "data: [DONE]\n\n"
|
| 262 |
|
| 263 |
return StreamingResponse(stream_generator(), media_type="text/event-stream; charset=utf-8")
|
|
|
|
| 23 |
logging.basicConfig(level=logging.INFO)
|
| 24 |
logger = logging.getLogger(__name__)
|
| 25 |
|
| 26 |
+
app = FastAPI(title="Hebrew Smart Home Technician", version="9.5.0")
|
| 27 |
|
| 28 |
app.add_middleware(
|
| 29 |
CORSMiddleware,
|
|
|
|
| 37 |
tokenizer = None
|
| 38 |
device = "cpu"
|
| 39 |
|
| 40 |
+
# --- מילון מונחים לחיפוש והבנה ---
|
| 41 |
SEARCH_MAP = {
|
| 42 |
"בקר": ["ESP32", "U2", "Controller"],
|
| 43 |
"מסך": ["Nextion", "LCD1", "HMI", "Display"],
|
| 44 |
"שרטוט": ["Schematic", "Connections", "Pin", "Net"],
|
| 45 |
"חיבור": ["Connect", "Wire", "Signal"],
|
| 46 |
+
"תקלה": ["Error", "Problem", "Fix", "Issue"],
|
| 47 |
"לא עובד": ["Power", "Voltage", "GND", "Disconnect"],
|
| 48 |
"זרם": ["ACS712", "Sensor", "Current"],
|
| 49 |
"מתח": ["3.3V", "5V", "VIN", "Power"],
|
|
|
|
| 90 |
search_terms.add(f"Pin {w}")
|
| 91 |
return list(search_terms)
|
| 92 |
|
| 93 |
+
def query_knowledge_base(query: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
conn = sqlite3.connect(DB_FILE)
|
| 95 |
cursor = conn.cursor()
|
| 96 |
+
|
| 97 |
search_terms = expand_query(query)
|
| 98 |
logger.info(f"🔍 Searching for: {search_terms}")
|
| 99 |
|
|
|
|
| 106 |
for row_id, content, topic in rows:
|
| 107 |
if row_id not in seen_ids:
|
| 108 |
score = 1
|
|
|
|
|
|
|
| 109 |
|
| 110 |
+
# בונוס עצום לשרטוט אם נשאל על חיבורים
|
| 111 |
+
if "Schematic" in content and any(x in query for x in ["שרטוט", "חיבור", "פין", "לאן", "מחובר", "מסך"]):
|
| 112 |
score += 100
|
| 113 |
elif term.lower() in topic.lower():
|
| 114 |
score += 10
|
| 115 |
|
| 116 |
+
# בונוס למספרים (למשל פין 18)
|
| 117 |
numbers_in_query = [int(s) for s in query.split() if s.isdigit()]
|
| 118 |
for num in numbers_in_query:
|
| 119 |
if str(num) in content:
|
|
|
|
| 121 |
|
| 122 |
results.append((score, content))
|
| 123 |
seen_ids.add(row_id)
|
| 124 |
+
|
| 125 |
conn.close()
|
| 126 |
|
| 127 |
results.sort(key=lambda x: x[0], reverse=True)
|
| 128 |
|
| 129 |
+
# מחזיר רק את התוצאה הכי טובה כדי לא לבלבל את המודל עם עודף מידע
|
| 130 |
if results:
|
| 131 |
+
return results[0][1]
|
| 132 |
+
return ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
def save_message(role: str, content: str):
|
| 135 |
try:
|
|
|
|
| 146 |
|
| 147 |
class ChatCompletionRequest(BaseModel):
|
| 148 |
messages: List[Message]
|
| 149 |
+
max_tokens: Optional[int] = 512
|
| 150 |
+
temperature: Optional[float] = 0.2
|
| 151 |
stream: Optional[bool] = False
|
| 152 |
|
| 153 |
@app.on_event("startup")
|
|
|
|
| 184 |
|
| 185 |
context = ""
|
| 186 |
if last_user_msg:
|
| 187 |
+
save_message("user", last_user_msg.content)
|
| 188 |
+
context = query_knowledge_base(last_user_msg.content)
|
| 189 |
|
| 190 |
+
# --- הנחיה מתקנת (Corrective System Prompt) ---
|
| 191 |
if context:
|
| 192 |
sys_msg = (
|
| 193 |
+
"אתה מהנדס בכיר המסביר לתלמידים על פרויקט 'בית חכם תלם'.\n"
|
| 194 |
+
"הנחיות קריטיות:\n"
|
| 195 |
+
"1. דבר אך ורק בעברית טבעית ותקנית. אל תשתמש במילים באנגלית באמצע משפט (כמו 'crucial' או 'pins').\n"
|
| 196 |
+
"2. אל תעתיק את רשימת החיבורים כמו שהיא! קרא את המידע, הבן אותו, וסכם אותו במשפט הסבר.\n"
|
| 197 |
+
"3. דוגמה: אם כתוב 'LCD1 Pin RX connects to U4', כתוב: 'המסך מחובר לבקר בקווי התקשורת (RX/TX) דרך ממיר רמות'.\n"
|
| 198 |
+
"4. אם שואלים על רכיב ספציפי, ציין לאן הוא מחובר ואת מספרי הפינים החשובים.\n"
|
| 199 |
+
f"\nמידע טכני (מקור בלבד):\n{context}"
|
| 200 |
)
|
| 201 |
else:
|
| 202 |
+
sys_msg = "אתה עוזר חכם לפרויקט תלם. ענה בעברית בלבד. אם אין לך מידע, אמור זאת בנימוס."
|
| 203 |
|
| 204 |
if request.messages[0].role == "system":
|
| 205 |
request.messages[0].content = sys_msg
|
|
|
|
| 214 |
gen_kwargs = dict(
|
| 215 |
inputs=prompt_ids,
|
| 216 |
max_new_tokens=request.max_tokens,
|
| 217 |
+
temperature=0.2, # נמוך כדי להיצמד להנחיות
|
| 218 |
top_p=0.9,
|
| 219 |
do_sample=True,
|
| 220 |
pad_token_id=tokenizer.eos_token_id,
|
| 221 |
+
repetition_penalty=1.1 # חובה כדי למנוע לופים
|
| 222 |
)
|
| 223 |
|
| 224 |
if request.stream:
|
|
|
|
| 233 |
if text:
|
| 234 |
full_text += text
|
| 235 |
yield f"data: {json.dumps({'choices': [{'delta': {'content': text}}]}, ensure_ascii=False)}\n\n"
|
| 236 |
+
save_message("assistant", full_text)
|
| 237 |
yield "data: [DONE]\n\n"
|
| 238 |
|
| 239 |
return StreamingResponse(stream_generator(), media_type="text/event-stream; charset=utf-8")
|