THEZYZSTUDIO commited on
Commit
fcd518f
·
verified ·
1 Parent(s): dc9482e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +6 -38
app.py CHANGED
@@ -58,15 +58,15 @@ def _build_search_sources(query: str) -> list[dict]:
58
  return [
59
  {
60
  "name": "DuckDuckGo Instant",
61
- "cmd": f"curl -s 'https://api.duckduckgo.com/?q={q}&format=json&no_html=1&skip_disambig=1' | python3 -c \"import sys,json; d=json.load(sys.stdin); ans=d.get('AbstractText',''); rels=d.get('RelatedTopics',[]); print('ANSWER:',ans if ans else 'no direct answer'); [print('-',r.get('Text','')[:250]) for r in rels[:8] if isinstance(r,dict) and r.get('Text')]\""
62
  },
63
  {
64
  "name": "Google News RSS",
65
- "cmd": f"curl -sL {CURL_HEADERS} 'https://news.google.com/rss/search?q={q_raw}&hl=en&gl=US&ceid=US:en' | python3 -c \"import sys,re; xml=sys.stdin.read(); titles=re.findall(r'<title><![CDATA[(.*?)]]></title>|<title>(.*?)</title>',xml); descs=re.findall(r'<description>(.*?)</description>',xml); clean=lambda s:re.sub('<[^>]+>','',s); results=[(a or b).strip() for a,b in titles if (a or b).strip()][1:9]; [print(str(i+1)+'. '+t[:180]) for i,t in enumerate(results)]\""
66
  },
67
  {
68
  "name": "Wikipedia English",
69
- "cmd": f"curl -s 'https://en.wikipedia.org/api/rest_v1/page/summary/{q}' | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('title','')+'\\n'+d.get('extract','')[:1500])\" 2>/dev/null || curl -s 'https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={q}&format=json&srlimit=5' | python3 -c \"import sys,json; d=json.load(sys.stdin); [print(str(i+1)+'. '+r['title']+': '+re.sub('<[^>]+>','',r.get('snippet',''))[:200]) for i,r in enumerate(d.get('query',{}).get('search',[]))]\" 2>/dev/null"
70
  },
71
  {
72
  "name": "DuckDuckGo HTML",
@@ -78,7 +78,7 @@ def _build_search_sources(query: str) -> list[dict]:
78
  },
79
  {
80
  "name": "Reddit Search",
81
- "cmd": f"curl -sL {CURL_HEADERS} -H 'Accept: application/json' 'https://www.reddit.com/search.json?q={q}&sort=new&limit=8&type=link' | python3 -c \"import sys,json; d=json.load(sys.stdin); posts=d.get('data',{}).get('children',[]); [print(str(i+1)+'. '+p['data'].get('title','')+'\\n r/'+p['data'].get('subreddit','')+' Score:'+str(p['data'].get('score',''))+'\\n '+p['data'].get('selftext','')[:200]) for i,p in enumerate(posts[:6])]\""
82
  },
83
  {
84
  "name": "HackerNews",
@@ -120,10 +120,9 @@ def _is_empty_result(stdout: str) -> bool:
120
  "{}",
121
  "error",
122
  "not found",
123
- "ANSWER: no",
124
  ]
125
  s = stdout.strip().lower()
126
- # إذا النتيجة كلها علامات "لا يوجد"
127
  meaningful_lines = [l for l in s.split('\n') if l.strip() and not any(sig in l for sig in empty_signals)]
128
  if len(meaningful_lines) < 1:
129
  return True
@@ -202,45 +201,34 @@ def run_command_smart(cmd: str, timeout: int = 45) -> dict:
202
  ينفذ الأمر — إذا كان curl بحث وفشل/فرغ → يجرب مصادر بديلة تلقائياً
203
  يرجع النتيجة الأولى التي تحتوي معلومات حقيقية
204
  """
205
- # نفذ الأمر الأصلي أولاً
206
  res = run_raw_command(cmd, timeout=timeout)
207
  stdout = res["stdout"].strip()
208
 
209
- # إذا نجح وفيه نتائج → ارجع مباشرة
210
  if res["returncode"] == 0 and not _is_empty_result(stdout):
211
  return res
212
 
213
- # هل هو أمر curl بحث؟
214
  is_curl_search = "curl" in cmd and any(x in cmd for x in [
215
  "duckduckgo", "google", "bing", "wikipedia", "reddit",
216
  "hackernews", "hn.algolia", "arxiv", "news", "search"
217
  ])
218
 
219
  if not is_curl_search:
220
- # ليس بحثاً → ارجع النتيجة كما هي
221
  return res
222
 
223
- # استخرج كلمات البحث
224
  query = _extract_query_from_cmd(cmd)
225
  if not query or len(query) < 3:
226
- # حاول تستخرج من النص العام
227
  words = [w for w in cmd.split() if len(w) > 3 and not w.startswith('-')
228
  and 'http' not in w and 'python3' not in w and 'curl' not in w]
229
  query = ' '.join(words[:5]) if words else ""
230
 
231
  if not query:
232
- return res # لا نعرف نبحث عن إيش
233
 
234
- # جرب المصادر البديلة واحدة واحدة
235
  sources = _build_search_sources(query)
236
  tried_names = []
237
  all_results = []
238
 
239
- # الأمر الأصلي فشل → نبدأ من البدائل
240
- original_failed_msg = f"[المصدر الأصلي: خطأ/فارغ] "
241
-
242
  for source in sources:
243
- # تجنب تكرار نفس النوع إذا كان في الأمر الأصلي
244
  src_name = source["name"]
245
  if any(x in cmd.lower() for x in [src_name.lower().split()[0]]):
246
  tried_names.append(f"⏭️ {src_name} (مجرب)")
@@ -251,14 +239,12 @@ def run_command_smart(cmd: str, timeout: int = 45) -> dict:
251
  src_out = src_res["stdout"].strip()
252
 
253
  if not _is_empty_result(src_out):
254
- # وجدنا نتائج!
255
  combined_header = (
256
  f"[تعذر الحصول على نتائج من المصدر الأصلي]\n"
257
  f"[البديل المستخدم: {src_name}]\n"
258
  f"{'='*50}\n"
259
  )
260
  all_results.append(src_out)
261
- # جرب مصدر ثانٍ لنقارن
262
  for source2 in sources:
263
  if source2["name"] != src_name:
264
  s2 = run_raw_command(source2["cmd"], timeout=15)
@@ -276,7 +262,6 @@ def run_command_smart(cmd: str, timeout: int = 45) -> dict:
276
  "_fallback_used": src_name,
277
  }
278
 
279
- # كل المصادر فشلت — ارجع ما عندنا مع رسالة واضحة
280
  return {
281
  "stdout": f"[لم تُرجع أي مصادر نتائج لـ: {query}]\nالمصادر التي جربتها: {', '.join(tried_names[:5])}",
282
  "stderr": res["stderr"],
@@ -333,12 +318,10 @@ async def handle_action(ws: WebSocket, msg: dict):
333
  "ts": int(time.time()*1000), "auto": True, "label": label})
334
  return frame
335
 
336
- # ── SCREENSHOT ──
337
  if action == "screenshot":
338
  frame = capture_screen(scale=0.8, quality=75)
339
  await send({"type": "screenshot", "data": frame, "ts": int(time.time()*1000)})
340
 
341
- # ── TERMINAL — الأهم ──────────────────────────────
342
  elif action == "terminal":
343
  cmd = data.get("cmd", "")
344
  timeout = int(data.get("timeout", 45))
@@ -347,7 +330,6 @@ async def handle_action(ws: WebSocket, msg: dict):
347
  "stderr": "no command", "returncode": -1})
348
  return
349
 
350
- # استخدم run_command_smart — يجرب بدائل تلقائياً
351
  res = run_command_smart(cmd, timeout=timeout)
352
 
353
  await send({
@@ -360,16 +342,13 @@ async def handle_action(ws: WebSocket, msg: dict):
360
  "sources_tried": res.get("_sources_tried", []),
361
  })
362
 
363
- # screenshot تلقائي
364
  await auto_shot(f"بعد: {cmd[:45]}", delay=0.3)
365
 
366
- # ── MOUSE MOVE ──
367
  elif action == "mouse_move":
368
  x, y = int(data.get("x", 0)), int(data.get("y", 0))
369
  xdo(["mousemove", str(x), str(y)])
370
  await send({"type": "ack", "action": "mouse_move"})
371
 
372
- # ── MOUSE CLICK ──
373
  elif action == "mouse_click":
374
  x, y = int(data.get("x", 0)), int(data.get("y", 0))
375
  btn_num = {"left": "1", "middle": "2", "right": "3"}.get(data.get("button","left"), "1")
@@ -382,7 +361,6 @@ async def handle_action(ws: WebSocket, msg: dict):
382
  await send({"type": "ack", "action": "mouse_click"})
383
  await auto_shot("بعد النقر", 0.4)
384
 
385
- # ── KEYBOARD TYPE ──
386
  elif action == "keyboard_type":
387
  text = data.get("text", "")
388
  if text:
@@ -390,7 +368,6 @@ async def handle_action(ws: WebSocket, msg: dict):
390
  await send({"type": "ack", "action": "keyboard_type"})
391
  await auto_shot("بعد الكتابة", 0.3)
392
 
393
- # ── KEYBOARD HOTKEY ──
394
  elif action == "keyboard_hotkey":
395
  keys = data.get("keys", [])
396
  if keys:
@@ -398,14 +375,12 @@ async def handle_action(ws: WebSocket, msg: dict):
398
  await send({"type": "ack", "action": "keyboard_hotkey"})
399
  await auto_shot("بعد الاختصار", 0.4)
400
 
401
- # ── KEYBOARD PRESS ──
402
  elif action == "keyboard_press":
403
  key = data.get("key", "")
404
  if key:
405
  xdo(["key", "--clearmodifiers", key])
406
  await send({"type": "ack", "action": "keyboard_press"})
407
 
408
- # ── CLIPBOARD ──
409
  elif action == "clipboard_write":
410
  proc = subprocess.Popen(["xclip", "-selection", "clipboard"],
411
  stdin=subprocess.PIPE,
@@ -417,7 +392,6 @@ async def handle_action(ws: WebSocket, msg: dict):
417
  res = run_raw_command("xclip -selection clipboard -o", timeout=5)
418
  await send({"type": "clipboard_content", "text": res["stdout"]})
419
 
420
- # ── SCROLL ──
421
  elif action == "scroll":
422
  x, y = int(data.get("x", 0)), int(data.get("y", 0))
423
  clicks = int(data.get("clicks", 3))
@@ -427,7 +401,6 @@ async def handle_action(ws: WebSocket, msg: dict):
427
  xdo(["click", btn])
428
  await send({"type": "ack", "action": "scroll"})
429
 
430
- # ── OPEN APP ──
431
  elif action == "open_app":
432
  app_cmd = data.get("cmd", "")
433
  if app_cmd:
@@ -439,7 +412,6 @@ async def handle_action(ws: WebSocket, msg: dict):
439
  else:
440
  await send({"type": "ack", "action": "open_app"})
441
 
442
- # ── DRAG ──
443
  elif action == "mouse_drag":
444
  x1,y1 = int(data.get("x1",0)), int(data.get("y1",0))
445
  x2,y2 = int(data.get("x2",0)), int(data.get("y2",0))
@@ -451,7 +423,6 @@ async def handle_action(ws: WebSocket, msg: dict):
451
  xdo(["mouseup", "1"])
452
  await send({"type": "ack", "action": "mouse_drag"})
453
 
454
- # ── STREAM ──
455
  elif action == "start_stream":
456
  global stream_active, stream_fps, stream_quality, stream_scale
457
  stream_fps = int(data.get("fps", 3))
@@ -466,7 +437,6 @@ async def handle_action(ws: WebSocket, msg: dict):
466
  stream_active = False
467
  await send({"type": "ack", "action": "stop_stream"})
468
 
469
- # ── SCREEN INFO ──
470
  elif action == "screen_info":
471
  res = run_raw_command("xdotool getdisplaygeometry", timeout=5)
472
  try: parts = res["stdout"].strip().split(); w,h = int(parts[0]),int(parts[1])
@@ -523,7 +493,6 @@ async def rest_terminal(body: dict):
523
  @app.get("/health")
524
  async def health():
525
  display = run_raw_command("xdotool getdisplaygeometry", 4)
526
- # Test multi-source search
527
  test = run_command_smart("curl -s 'https://api.duckduckgo.com/?q=test&format=json&no_html=1'", 15)
528
  return {
529
  "status": "ok",
@@ -535,7 +504,6 @@ async def health():
535
 
536
  @app.get("/search/{query}")
537
  async def quick_search(query: str):
538
- """اختبار سريع للبحث"""
539
  res = run_command_smart(
540
  f"curl -s 'https://api.duckduckgo.com/?q={urllib.parse.quote_plus(query)}&format=json&no_html=1'",
541
  timeout=30
 
58
  return [
59
  {
60
  "name": "DuckDuckGo Instant",
61
+ "cmd": f"curl -s 'https://api.duckduckgo.com/?q={q}&format=json&no_html=1&skip_disambig=1' | python3 -c \"import sys,json; d=json.load(sys.stdin); ans=d.get('AbstractText',''); rels=d.get('RelatedTopics',[]); print('ANSWER:',ans if ans else 'no direct answer'); [print('-',r.get('Text','')[:250]) for r in rels if isinstance(r,dict) and r.get('Text')]\""
62
  },
63
  {
64
  "name": "Google News RSS",
65
+ "cmd": f"curl -sL {CURL_HEADERS} 'https://news.google.com/rss/search?q={q_raw}&hl=en&gl=US&ceid=US:en' | python3 -c \"import sys,re; xml=sys.stdin.read(); titles=re.findall(r'<title><!\\[CDATA\\[(.*?)\\]\\]></title>|<title>(.*?)</title>',xml); descs=re.findall(r'<description>(.*?)</description>',xml); clean=lambda s:re.sub('<[^>]+>','',s); results=[(a or b).strip() for a,b in titles if (a or b).strip()][1:9]; [print(str(i+1)+'. '+t[:180]) for i,t in enumerate(results)]\""
66
  },
67
  {
68
  "name": "Wikipedia English",
69
+ "cmd": f"curl -s 'https://en.wikipedia.org/api/rest_v1/page/summary/{q}' | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('title','')+'\\n'+d.get('extract','')[:1500])\" 2>/dev/null || curl -s 'https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={q}&format=json&srlimit=5' | python3 -c \"import sys,json; d=json.load(sys.stdin); [print(str(i+1)+'. '+r['title']+': '+re.sub('<[^>]+>','',r.get('snippet',''))[:200]) for i,r in enumerate(d.get('query',{{}}).get('search',[]))]\" 2>/dev/null"
70
  },
71
  {
72
  "name": "DuckDuckGo HTML",
 
78
  },
79
  {
80
  "name": "Reddit Search",
81
+ "cmd": f"curl -sL {CURL_HEADERS} -H 'Accept: application/json' 'https://www.reddit.com/search.json?q={q}&sort=new&limit=8&type=link' | python3 -c \"import sys,json; d=json.load(sys.stdin); posts=d.get('data',{{}}).get('children',[]); [print(str(i+1)+'. '+p['data'].get('title','')+'\\n r/'+p['data'].get('subreddit','')+' Score:'+str(p['data'].get('score',''))+'\\n '+p['data'].get('selftext','')[:200]) for i,p in enumerate(posts[:6])]\""
82
  },
83
  {
84
  "name": "HackerNews",
 
120
  "{}",
121
  "error",
122
  "not found",
123
+ "answer: no",
124
  ]
125
  s = stdout.strip().lower()
 
126
  meaningful_lines = [l for l in s.split('\n') if l.strip() and not any(sig in l for sig in empty_signals)]
127
  if len(meaningful_lines) < 1:
128
  return True
 
201
  ينفذ الأمر — إذا كان curl بحث وفشل/فرغ → يجرب مصادر بديلة تلقائياً
202
  يرجع النتيجة الأولى التي تحتوي معلومات حقيقية
203
  """
 
204
  res = run_raw_command(cmd, timeout=timeout)
205
  stdout = res["stdout"].strip()
206
 
 
207
  if res["returncode"] == 0 and not _is_empty_result(stdout):
208
  return res
209
 
 
210
  is_curl_search = "curl" in cmd and any(x in cmd for x in [
211
  "duckduckgo", "google", "bing", "wikipedia", "reddit",
212
  "hackernews", "hn.algolia", "arxiv", "news", "search"
213
  ])
214
 
215
  if not is_curl_search:
 
216
  return res
217
 
 
218
  query = _extract_query_from_cmd(cmd)
219
  if not query or len(query) < 3:
 
220
  words = [w for w in cmd.split() if len(w) > 3 and not w.startswith('-')
221
  and 'http' not in w and 'python3' not in w and 'curl' not in w]
222
  query = ' '.join(words[:5]) if words else ""
223
 
224
  if not query:
225
+ return res
226
 
 
227
  sources = _build_search_sources(query)
228
  tried_names = []
229
  all_results = []
230
 
 
 
 
231
  for source in sources:
 
232
  src_name = source["name"]
233
  if any(x in cmd.lower() for x in [src_name.lower().split()[0]]):
234
  tried_names.append(f"⏭️ {src_name} (مجرب)")
 
239
  src_out = src_res["stdout"].strip()
240
 
241
  if not _is_empty_result(src_out):
 
242
  combined_header = (
243
  f"[تعذر الحصول على نتائج من المصدر الأصلي]\n"
244
  f"[البديل المستخدم: {src_name}]\n"
245
  f"{'='*50}\n"
246
  )
247
  all_results.append(src_out)
 
248
  for source2 in sources:
249
  if source2["name"] != src_name:
250
  s2 = run_raw_command(source2["cmd"], timeout=15)
 
262
  "_fallback_used": src_name,
263
  }
264
 
 
265
  return {
266
  "stdout": f"[لم تُرجع أي مصادر نتائج لـ: {query}]\nالمصادر التي جربتها: {', '.join(tried_names[:5])}",
267
  "stderr": res["stderr"],
 
318
  "ts": int(time.time()*1000), "auto": True, "label": label})
319
  return frame
320
 
 
321
  if action == "screenshot":
322
  frame = capture_screen(scale=0.8, quality=75)
323
  await send({"type": "screenshot", "data": frame, "ts": int(time.time()*1000)})
324
 
 
325
  elif action == "terminal":
326
  cmd = data.get("cmd", "")
327
  timeout = int(data.get("timeout", 45))
 
330
  "stderr": "no command", "returncode": -1})
331
  return
332
 
 
333
  res = run_command_smart(cmd, timeout=timeout)
334
 
335
  await send({
 
342
  "sources_tried": res.get("_sources_tried", []),
343
  })
344
 
 
345
  await auto_shot(f"بعد: {cmd[:45]}", delay=0.3)
346
 
 
347
  elif action == "mouse_move":
348
  x, y = int(data.get("x", 0)), int(data.get("y", 0))
349
  xdo(["mousemove", str(x), str(y)])
350
  await send({"type": "ack", "action": "mouse_move"})
351
 
 
352
  elif action == "mouse_click":
353
  x, y = int(data.get("x", 0)), int(data.get("y", 0))
354
  btn_num = {"left": "1", "middle": "2", "right": "3"}.get(data.get("button","left"), "1")
 
361
  await send({"type": "ack", "action": "mouse_click"})
362
  await auto_shot("بعد النقر", 0.4)
363
 
 
364
  elif action == "keyboard_type":
365
  text = data.get("text", "")
366
  if text:
 
368
  await send({"type": "ack", "action": "keyboard_type"})
369
  await auto_shot("بعد الكتابة", 0.3)
370
 
 
371
  elif action == "keyboard_hotkey":
372
  keys = data.get("keys", [])
373
  if keys:
 
375
  await send({"type": "ack", "action": "keyboard_hotkey"})
376
  await auto_shot("بعد الاختصار", 0.4)
377
 
 
378
  elif action == "keyboard_press":
379
  key = data.get("key", "")
380
  if key:
381
  xdo(["key", "--clearmodifiers", key])
382
  await send({"type": "ack", "action": "keyboard_press"})
383
 
 
384
  elif action == "clipboard_write":
385
  proc = subprocess.Popen(["xclip", "-selection", "clipboard"],
386
  stdin=subprocess.PIPE,
 
392
  res = run_raw_command("xclip -selection clipboard -o", timeout=5)
393
  await send({"type": "clipboard_content", "text": res["stdout"]})
394
 
 
395
  elif action == "scroll":
396
  x, y = int(data.get("x", 0)), int(data.get("y", 0))
397
  clicks = int(data.get("clicks", 3))
 
401
  xdo(["click", btn])
402
  await send({"type": "ack", "action": "scroll"})
403
 
 
404
  elif action == "open_app":
405
  app_cmd = data.get("cmd", "")
406
  if app_cmd:
 
412
  else:
413
  await send({"type": "ack", "action": "open_app"})
414
 
 
415
  elif action == "mouse_drag":
416
  x1,y1 = int(data.get("x1",0)), int(data.get("y1",0))
417
  x2,y2 = int(data.get("x2",0)), int(data.get("y2",0))
 
423
  xdo(["mouseup", "1"])
424
  await send({"type": "ack", "action": "mouse_drag"})
425
 
 
426
  elif action == "start_stream":
427
  global stream_active, stream_fps, stream_quality, stream_scale
428
  stream_fps = int(data.get("fps", 3))
 
437
  stream_active = False
438
  await send({"type": "ack", "action": "stop_stream"})
439
 
 
440
  elif action == "screen_info":
441
  res = run_raw_command("xdotool getdisplaygeometry", timeout=5)
442
  try: parts = res["stdout"].strip().split(); w,h = int(parts[0]),int(parts[1])
 
493
  @app.get("/health")
494
  async def health():
495
  display = run_raw_command("xdotool getdisplaygeometry", 4)
 
496
  test = run_command_smart("curl -s 'https://api.duckduckgo.com/?q=test&format=json&no_html=1'", 15)
497
  return {
498
  "status": "ok",
 
504
 
505
  @app.get("/search/{query}")
506
  async def quick_search(query: str):
 
507
  res = run_command_smart(
508
  f"curl -s 'https://api.duckduckgo.com/?q={urllib.parse.quote_plus(query)}&format=json&no_html=1'",
509
  timeout=30