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="9.
|
| 27 |
|
| 28 |
app.add_middleware(
|
| 29 |
CORSMiddleware,
|
|
@@ -43,7 +43,7 @@ SEARCH_MAP = {
|
|
| 43 |
"מסך": ["Nextion", "LCD1", "HMI", "Display"],
|
| 44 |
"שרטוט": ["Schematic", "Connections", "Pin", "Net"],
|
| 45 |
"חיבור": ["Connect", "Wire", "Signal"],
|
| 46 |
-
"חיבןר": ["Connect", "Wire", "Signal"],
|
| 47 |
"תקלה": ["Error", "Problem", "Fix", "Issue"],
|
| 48 |
"לא עובד": ["Power", "Voltage", "GND", "Disconnect"],
|
| 49 |
"זרם": ["ACS712", "Sensor", "Current"],
|
|
@@ -63,14 +63,12 @@ def init_db():
|
|
| 63 |
try:
|
| 64 |
with open(JSON_SOURCE, 'r', encoding='utf-8') as f:
|
| 65 |
data = json.load(f)
|
| 66 |
-
count = 0
|
| 67 |
for item in data:
|
| 68 |
if isinstance(item, dict) and 'content' in item:
|
| 69 |
cursor.execute('INSERT INTO knowledge (topic, content) VALUES (?, ?)',
|
| 70 |
(item.get('topic', 'General'), item['content']))
|
| 71 |
-
count += 1
|
| 72 |
conn.commit()
|
| 73 |
-
logger.info(f"✅ Loaded
|
| 74 |
except Exception as e:
|
| 75 |
logger.error(f"❌ Error loading JSON: {e}")
|
| 76 |
conn.close()
|
|
@@ -97,16 +95,23 @@ def filter_schematic_context(full_context: str, query_terms: List[str]) -> str:
|
|
| 97 |
|
| 98 |
target_terms = [t.lower() for t in query_terms if len(t) > 1]
|
| 99 |
|
|
|
|
|
|
|
| 100 |
for line in lines:
|
| 101 |
line_lower = line.lower()
|
| 102 |
-
#
|
| 103 |
if "connect" in line_lower and any(t in line_lower for t in target_terms):
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
if not relevant_lines:
|
| 107 |
return full_context
|
| 108 |
|
| 109 |
-
|
|
|
|
| 110 |
|
| 111 |
def query_knowledge_base(query: str) -> Tuple[str, List[str]]:
|
| 112 |
conn = sqlite3.connect(DB_FILE)
|
|
@@ -123,7 +128,6 @@ def query_knowledge_base(query: str) -> Tuple[str, List[str]]:
|
|
| 123 |
for row_id, content, topic in rows:
|
| 124 |
if row_id not in seen_ids:
|
| 125 |
score = 1
|
| 126 |
-
|
| 127 |
is_schematic = "Schematic" in content or "Connections" in content
|
| 128 |
is_tech_query = any(x in query for x in ["שרטוט", "חיבור", "פין", "לאן", "מחובר", "מסך"])
|
| 129 |
|
|
@@ -166,8 +170,8 @@ class Message(BaseModel):
|
|
| 166 |
|
| 167 |
class ChatCompletionRequest(BaseModel):
|
| 168 |
messages: List[Message]
|
| 169 |
-
max_tokens: Optional[int] =
|
| 170 |
-
temperature: Optional[float] = 0.
|
| 171 |
stream: Optional[bool] = False
|
| 172 |
|
| 173 |
@app.on_event("startup")
|
|
@@ -204,18 +208,17 @@ async def chat_completions(request: ChatCompletionRequest):
|
|
| 204 |
|
| 205 |
context = ""
|
| 206 |
if last_user_msg:
|
| 207 |
-
save_message("user", last_user_msg.content)
|
| 208 |
context, _ = query_knowledge_base(last_user_msg.content)
|
| 209 |
|
| 210 |
-
# --- הנחיה מתוקנת לסיכום ודיוק ---
|
| 211 |
if context:
|
| 212 |
sys_msg = (
|
| 213 |
-
"תפקידך: טכנאי מומחה המסביר על מערכת 'בית חכם'.\n"
|
| 214 |
"הנחיות לתשובה:\n"
|
| 215 |
-
"1. **ענה בעברית בלבד**.
|
| 216 |
-
"2. **סיכום:**
|
| 217 |
-
"3.
|
| 218 |
-
"4.
|
| 219 |
f"\nמידע טכני גולמי לשימושך:\n{context}"
|
| 220 |
)
|
| 221 |
else:
|
|
@@ -234,11 +237,11 @@ async def chat_completions(request: ChatCompletionRequest):
|
|
| 234 |
gen_kwargs = dict(
|
| 235 |
inputs=prompt_ids,
|
| 236 |
max_new_tokens=request.max_tokens,
|
| 237 |
-
temperature=0.
|
| 238 |
top_p=0.9,
|
| 239 |
do_sample=True,
|
| 240 |
pad_token_id=tokenizer.eos_token_id,
|
| 241 |
-
repetition_penalty=1.2 #
|
| 242 |
)
|
| 243 |
|
| 244 |
if request.stream:
|
|
@@ -253,7 +256,7 @@ async def chat_completions(request: ChatCompletionRequest):
|
|
| 253 |
if text:
|
| 254 |
full_text += text
|
| 255 |
yield f"data: {json.dumps({'choices': [{'delta': {'content': text}}]}, ensure_ascii=False)}\n\n"
|
| 256 |
-
save_message("assistant", full_text)
|
| 257 |
yield "data: [DONE]\n\n"
|
| 258 |
|
| 259 |
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.8.0")
|
| 27 |
|
| 28 |
app.add_middleware(
|
| 29 |
CORSMiddleware,
|
|
|
|
| 43 |
"מסך": ["Nextion", "LCD1", "HMI", "Display"],
|
| 44 |
"שרטוט": ["Schematic", "Connections", "Pin", "Net"],
|
| 45 |
"חיבור": ["Connect", "Wire", "Signal"],
|
| 46 |
+
"חיבןר": ["Connect", "Wire", "Signal"],
|
| 47 |
"תקלה": ["Error", "Problem", "Fix", "Issue"],
|
| 48 |
"לא עובד": ["Power", "Voltage", "GND", "Disconnect"],
|
| 49 |
"זרם": ["ACS712", "Sensor", "Current"],
|
|
|
|
| 63 |
try:
|
| 64 |
with open(JSON_SOURCE, 'r', encoding='utf-8') as f:
|
| 65 |
data = json.load(f)
|
|
|
|
| 66 |
for item in data:
|
| 67 |
if isinstance(item, dict) and 'content' in item:
|
| 68 |
cursor.execute('INSERT INTO knowledge (topic, content) VALUES (?, ?)',
|
| 69 |
(item.get('topic', 'General'), item['content']))
|
|
|
|
| 70 |
conn.commit()
|
| 71 |
+
logger.info(f"✅ Loaded items from database.json")
|
| 72 |
except Exception as e:
|
| 73 |
logger.error(f"❌ Error loading JSON: {e}")
|
| 74 |
conn.close()
|
|
|
|
| 95 |
|
| 96 |
target_terms = [t.lower() for t in query_terms if len(t) > 1]
|
| 97 |
|
| 98 |
+
seen_lines = set() # Deduplication set
|
| 99 |
+
|
| 100 |
for line in lines:
|
| 101 |
line_lower = line.lower()
|
| 102 |
+
# Filter for schematic lines containing relevant terms
|
| 103 |
if "connect" in line_lower and any(t in line_lower for t in target_terms):
|
| 104 |
+
# Clean up line (remove extra whitespace)
|
| 105 |
+
clean_line = line.strip()
|
| 106 |
+
if clean_line not in seen_lines:
|
| 107 |
+
relevant_lines.append(clean_line)
|
| 108 |
+
seen_lines.add(clean_line)
|
| 109 |
|
| 110 |
if not relevant_lines:
|
| 111 |
return full_context
|
| 112 |
|
| 113 |
+
# Limit to top 5 relevant lines to prevent overwhelming the model
|
| 114 |
+
return "רשימת חיבורים רלוונטית (חלקית):\n" + "\n".join(relevant_lines[:5])
|
| 115 |
|
| 116 |
def query_knowledge_base(query: str) -> Tuple[str, List[str]]:
|
| 117 |
conn = sqlite3.connect(DB_FILE)
|
|
|
|
| 128 |
for row_id, content, topic in rows:
|
| 129 |
if row_id not in seen_ids:
|
| 130 |
score = 1
|
|
|
|
| 131 |
is_schematic = "Schematic" in content or "Connections" in content
|
| 132 |
is_tech_query = any(x in query for x in ["שרטוט", "חיבור", "פין", "לאן", "מחובר", "מסך"])
|
| 133 |
|
|
|
|
| 170 |
|
| 171 |
class ChatCompletionRequest(BaseModel):
|
| 172 |
messages: List[Message]
|
| 173 |
+
max_tokens: Optional[int] = 300 # LIMIT TOKENS to stop runaway loops
|
| 174 |
+
temperature: Optional[float] = 0.25
|
| 175 |
stream: Optional[bool] = False
|
| 176 |
|
| 177 |
@app.on_event("startup")
|
|
|
|
| 208 |
|
| 209 |
context = ""
|
| 210 |
if last_user_msg:
|
| 211 |
+
threading.Thread(target=save_message, args=("user", last_user_msg.content)).start()
|
| 212 |
context, _ = query_knowledge_base(last_user_msg.content)
|
| 213 |
|
|
|
|
| 214 |
if context:
|
| 215 |
sys_msg = (
|
| 216 |
+
"תפקידך: טכנאי מומחה המסביר על מערכת 'בית חכם תלם'.\n"
|
| 217 |
"הנחיות לתשובה:\n"
|
| 218 |
+
"1. **ענה בעברית בלבד**.\n"
|
| 219 |
+
"2. **סיכום קצר:** קרא את רשימת החיבורים וכתוב משפט אחד ��מסכם את החיבורים העיקריים (כמו RX, TX, 5V).\n"
|
| 220 |
+
"3. **אל תקריא את כל הרשימה!** תן רק את המידע החשוב ביותר.\n"
|
| 221 |
+
"4. דוגמה לתשובה טובה: 'המסך מחובר לבקר בפיני התקשורת RX ו-TX וכן למתח 5V'.\n"
|
| 222 |
f"\nמידע טכני גולמי לשימושך:\n{context}"
|
| 223 |
)
|
| 224 |
else:
|
|
|
|
| 237 |
gen_kwargs = dict(
|
| 238 |
inputs=prompt_ids,
|
| 239 |
max_new_tokens=request.max_tokens,
|
| 240 |
+
temperature=0.25,
|
| 241 |
top_p=0.9,
|
| 242 |
do_sample=True,
|
| 243 |
pad_token_id=tokenizer.eos_token_id,
|
| 244 |
+
repetition_penalty=1.2 # Stronger penalty to kill loops
|
| 245 |
)
|
| 246 |
|
| 247 |
if request.stream:
|
|
|
|
| 256 |
if text:
|
| 257 |
full_text += text
|
| 258 |
yield f"data: {json.dumps({'choices': [{'delta': {'content': text}}]}, ensure_ascii=False)}\n\n"
|
| 259 |
+
threading.Thread(target=save_message, args=("assistant", full_text)).start()
|
| 260 |
yield "data: [DONE]\n\n"
|
| 261 |
|
| 262 |
return StreamingResponse(stream_generator(), media_type="text/event-stream; charset=utf-8")
|