joz88 commited on
Commit
46bf5ec
·
verified ·
1 Parent(s): def3274

Update app.py from anycoder

Browse files
Files changed (1) hide show
  1. app.py +28 -56
app.py CHANGED
@@ -4,7 +4,6 @@ import time
4
  import random
5
  import hashlib
6
  import datetime
7
- import asyncio
8
  from dataclasses import dataclass, field, asdict
9
  from typing import Optional, List, Dict, Any, Callable
10
  from enum import Enum
@@ -65,7 +64,7 @@ class HardwareToken:
65
  def is_valid(self) -> bool:
66
  try:
67
  return datetime.datetime.fromisoformat(self.expires_at) > datetime.datetime.now()
68
- except:
69
  return False
70
 
71
  def has_permission(self, perm: str) -> bool:
@@ -80,9 +79,9 @@ class McpTool:
80
  icon: str = "🔧"
81
  execute_fn: Optional[Callable] = None
82
 
83
- async def execute(self) -> str:
84
  if self.execute_fn:
85
- return await self.execute_fn()
86
  return f"Tool '{self.name}' executed successfully"
87
 
88
  @dataclass
@@ -277,7 +276,7 @@ class SecureBleLeManager:
277
 
278
 
279
  class EmobilityAiAgent:
280
- """AI Agent with MCP architecture and HuggingFace TinyAgent"""
281
 
282
  def __init__(self):
283
  self.registered_tools: List[McpTool] = []
@@ -310,10 +309,10 @@ class EmobilityAiAgent:
310
  categories[tool.category].append(tool)
311
  return categories
312
 
313
- async def ask_agent(self, prompt: str, context: str = "") -> str:
 
314
  self.conversation_history.append({"role": "user", "content": prompt})
315
 
316
- # Simulated AI response with context awareness
317
  prompt_lower = prompt.lower()
318
  if any(kw in prompt_lower for kw in ["batterie", "bms", "soc", "soh", "zellspannung"]):
319
  response = (
@@ -331,7 +330,7 @@ class EmobilityAiAgent:
331
  "🚗 **OBD-II Diagnose-Ergebnis:**\n\n"
332
  "- **Protokoll:** ISO 15765-4 (CAN 500k)\n"
333
  "- **Fehlercodes (DTCs):** Keine aktiven DTCs\n"
334
- "- ** readiness Monitors:** Alle bestanden\n"
335
  "- **Emission-Status:** Bereit\n\n"
336
  "✅ Fahrzeug-ECU meldet keinen Fehler."
337
  )
@@ -507,7 +506,6 @@ def handle_mcp_execute(tool_id: str):
507
 
508
  tool = tools_map[tool_id]
509
 
510
- # Execute tool with simulated results
511
  if tool_id == "get_bms_status":
512
  result = f"SoH: 96.8%, ΔV: 12mV, Isolationswiderstand: 1400kΩ. Nominal."
513
  elif tool_id == "run_sys_audit":
@@ -540,14 +538,14 @@ def handle_mcp_execute(tool_id: str):
540
  return f"{tool.icon} **{tool.name}**\n\n{result}"
541
 
542
  def handle_ai_chat(message, history):
543
- # Convert gradio history format
544
- response = asyncio.run(ai_agent.ask_agent(message))
545
  audit_logger.log("ai_agent", "info", "tinyagent", f"KI-Anfrage: {message[:50]}...")
546
  return response
547
 
548
  def handle_create_token(permissions, sil_level):
549
  perms = [p.strip() for p in permissions.split(",") if p.strip()]
550
- token = token_manager.create_token(perms, sil_level)
551
  audit_logger.log("security", "info", "token_mgr", f"Token erstellt: {token.token_id}", asdict(token))
552
  return json.dumps(asdict(token), indent=2, ensure_ascii=False)
553
 
@@ -564,8 +562,12 @@ def handle_verify_token(token_json):
564
  return f"❌ Fehler bei Token-Verifikation: {str(e)}"
565
 
566
  def handle_factory_reset(level, reason, backup):
567
- sil_map = {"SIL1 (Diagnose)": 1, "SIL2 (Konfiguration)": 2, "SIL3 (Firmware)": 3, "SIL4 (Sicherheitskritisch)": 4}
568
- level_map = {"Soft (App-Daten)": ResetLevel.SOFT, "Standard (App+Cache)": ResetLevel.STANDARD, "Hard (Alles außer MDM)": ResetLevel.HARD, "Factory (Vollständig)": ResetLevel.FACTORY}
 
 
 
 
569
 
570
  reset_lvl = level_map.get(level, ResetLevel.SOFT)
571
  required_sil = 3 if reset_lvl in [ResetLevel.HARD, ResetLevel.FACTORY] else 1
@@ -636,6 +638,9 @@ def handle_add_mcp_tool(tool_id, tool_name, tool_desc, tool_category):
636
  updated_ids = [t.id for t in ai_agent.registered_tools]
637
  return f"✅ Tool '{tool_name}' ({tool_id}) in Kategorie '{tool_category}' registriert.", gr.Dropdown(choices=updated_ids)
638
 
 
 
 
639
 
640
  # ============================================================
641
  # GRADIO 6 APPLICATION
@@ -653,9 +658,6 @@ custom_theme = gr.themes.Soft(
653
  button_primary_background_fill="*primary_600",
654
  button_primary_background_fill_hover="*primary_700",
655
  block_title_text_weight="600",
656
- body_background_fill="#0a0a0a",
657
- block_background_fill="#141414",
658
- block_border_color="#2a2a2a",
659
  )
660
 
661
  with gr.Blocks() as demo:
@@ -664,7 +666,7 @@ with gr.Blocks() as demo:
664
  """
665
  # 🔧 Honeywell CT45P XP — E-Mobility Service Werkstatt
666
  ### UHAL Edge Workspace | Android 11 | NDK/SDK/AgentSDK/PowerTools
667
-
668
  [Built with anycoder](https://huggingface.co/spaces/akhaliq/anycoder)
669
  """
670
  )
@@ -672,6 +674,8 @@ with gr.Blocks() as demo:
672
  # System status bar
673
  with gr.Row():
674
  status_box = gr.JSON(label="System Status", value=json.loads(handle_get_system_status()), height=120)
 
 
675
 
676
  with gr.Tabs():
677
 
@@ -684,12 +688,12 @@ with gr.Blocks() as demo:
684
  with gr.Row():
685
  with gr.Column(scale=1):
686
  gr.Markdown("#### 📷 Barcode Scanner (N6700)")
687
- scan_btn = gr.Button("Hardware-Scan auslösen", variant="primary", icon="camera")
688
  scan_result = gr.Code(language="json", label="Scan-Ergebnis", lines=8)
689
 
690
  with gr.Column(scale=1):
691
  gr.Markdown("#### 🚗 OBD-II Diagnose (PowerTools)")
692
- obd_btn = gr.Button("OBD-II Diagnose starten", variant="primary", icon="car")
693
  obd_result = gr.Code(language="json", label="OBD-Ergebnis", lines=8)
694
 
695
  with gr.Row():
@@ -706,7 +710,7 @@ with gr.Blocks() as demo:
706
  with gr.Row():
707
  with gr.Column(scale=1):
708
  gr.Markdown("#### 💳 NFC Smart Card")
709
- nfc_btn = gr.Button("NFC Tap-to-Identify", variant="primary", icon="credit_card")
710
  nfc_result = gr.Code(language="json", label="NFC-Ergebnis", lines=10)
711
 
712
  with gr.Column(scale=1):
@@ -730,7 +734,7 @@ with gr.Blocks() as demo:
730
  with gr.Row():
731
  with gr.Column(scale=1):
732
  gr.Markdown("#### 🔵 BLE Peripheral Scan")
733
- ble_scan_btn = gr.Button("BLE LE Scan starten", variant="primary", icon="bluetooth")
734
  ble_scan_result = gr.Code(language="json", label="BLE Geräte", lines=15)
735
 
736
  with gr.Column(scale=1):
@@ -776,7 +780,7 @@ with gr.Blocks() as demo:
776
  label="Tool auswählen",
777
  info="Wähle ein MCP-Tool zur Ausführung",
778
  )
779
- mcp_execute_btn = gr.Button("Tool ausführen", variant="primary", icon="play")
780
  mcp_result = gr.Textbox(label="Ausführungsergebnis", lines=6, max_lines=15)
781
 
782
  with gr.Column(scale=3):
@@ -837,7 +841,6 @@ with gr.Blocks() as demo:
837
  "BMS Zellspannungs-Analyse",
838
  "Isolationswiderstand prüfen",
839
  ],
840
- cache_examples=False,
841
  )
842
 
843
  with gr.Column(scale=2):
@@ -899,35 +902,4 @@ with gr.Blocks() as demo:
899
  sil_input = gr.Slider(
900
  minimum=1, maximum=4, value=1, step=1,
901
  label="SIL-Level",
902
- info="1=Diagnose, 2=Konfiguration, 3=Firmware, 4=Sicherheitskritisch",
903
- )
904
- create_token_btn = gr.Button("Hardware-Token erstellen", variant="primary")
905
- token_result = gr.Code(language="json", label="Erstelltes Token", lines=12)
906
-
907
- with gr.Row():
908
- with gr.Column():
909
- gr.Markdown("#### 🔍 Token verifizieren")
910
- verify_input = gr.Code(language="json", label="Token JSON einfügen", lines=10, placeholder="Füge ein Token JSON ein...")
911
- verify_btn = gr.Button("Token verifizieren", variant="secondary")
912
- verify_result = gr.Textbox(label="Verifikationsergebnis", lines=5)
913
-
914
- create_token_btn.click(handle_create_token, inputs=[perm_input, sil_input], outputs=token_result)
915
- verify_btn.click(handle_verify_token, inputs=verify_input, outputs=verify_result)
916
-
917
- # ============================================================
918
- # TAB 6: FACTORY RESET
919
- # ============================================================
920
- with gr.Tab("⚠️ Factory Reset"):
921
- gr.Markdown("### Sicherer Factory Reset — Hardware-Authentifiziert & Audit-Logged")
922
- gr.Markdown("> ⚠️ **WARNUNG:** Factory Reset erfordert SIL-Level 3+ und erstellt automatisch ein Backup.")
923
-
924
- with gr.Row():
925
- with gr.Column(scale=1):
926
- reset_level = gr.Radio(
927
- choices=["Soft (App-Daten)", "Standard (App+Cache)", "Hard (Alles außer MDM)", "Factory (Vollständig)"],
928
- label="Reset-Level",
929
- value="Soft (App-Daten)",
930
- )
931
- reset_reason = gr.Textbox(label="Grund für Reset", placeholder="z.B. Fahrzeug-Übergabe, Fehlerbehebung...", lines=2)
932
- reset_backup = gr.Checkbox(label="Backup vor Reset erstellen", value=True)
933
- reset
 
4
  import random
5
  import hashlib
6
  import datetime
 
7
  from dataclasses import dataclass, field, asdict
8
  from typing import Optional, List, Dict, Any, Callable
9
  from enum import Enum
 
64
  def is_valid(self) -> bool:
65
  try:
66
  return datetime.datetime.fromisoformat(self.expires_at) > datetime.datetime.now()
67
+ except Exception:
68
  return False
69
 
70
  def has_permission(self, perm: str) -> bool:
 
79
  icon: str = "🔧"
80
  execute_fn: Optional[Callable] = None
81
 
82
+ def execute(self) -> str:
83
  if self.execute_fn:
84
+ return self.execute_fn()
85
  return f"Tool '{self.name}' executed successfully"
86
 
87
  @dataclass
 
276
 
277
 
278
  class EmobilityAiAgent:
279
+ """AI Agent with MCP architecture — synchronous to avoid asyncio issues"""
280
 
281
  def __init__(self):
282
  self.registered_tools: List[McpTool] = []
 
309
  categories[tool.category].append(tool)
310
  return categories
311
 
312
+ def ask_agent(self, prompt: str, context: str = "") -> str:
313
+ """Synchronous agent — avoids asyncio.run() inside Gradio's event loop"""
314
  self.conversation_history.append({"role": "user", "content": prompt})
315
 
 
316
  prompt_lower = prompt.lower()
317
  if any(kw in prompt_lower for kw in ["batterie", "bms", "soc", "soh", "zellspannung"]):
318
  response = (
 
330
  "🚗 **OBD-II Diagnose-Ergebnis:**\n\n"
331
  "- **Protokoll:** ISO 15765-4 (CAN 500k)\n"
332
  "- **Fehlercodes (DTCs):** Keine aktiven DTCs\n"
333
+ "- **Readiness Monitors:** Alle bestanden\n"
334
  "- **Emission-Status:** Bereit\n\n"
335
  "✅ Fahrzeug-ECU meldet keinen Fehler."
336
  )
 
506
 
507
  tool = tools_map[tool_id]
508
 
 
509
  if tool_id == "get_bms_status":
510
  result = f"SoH: 96.8%, ΔV: 12mV, Isolationswiderstand: 1400kΩ. Nominal."
511
  elif tool_id == "run_sys_audit":
 
538
  return f"{tool.icon} **{tool.name}**\n\n{result}"
539
 
540
  def handle_ai_chat(message, history):
541
+ """ChatInterface handler — synchronous to avoid event loop conflicts"""
542
+ response = ai_agent.ask_agent(message)
543
  audit_logger.log("ai_agent", "info", "tinyagent", f"KI-Anfrage: {message[:50]}...")
544
  return response
545
 
546
  def handle_create_token(permissions, sil_level):
547
  perms = [p.strip() for p in permissions.split(",") if p.strip()]
548
+ token = token_manager.create_token(perms, int(sil_level))
549
  audit_logger.log("security", "info", "token_mgr", f"Token erstellt: {token.token_id}", asdict(token))
550
  return json.dumps(asdict(token), indent=2, ensure_ascii=False)
551
 
 
562
  return f"❌ Fehler bei Token-Verifikation: {str(e)}"
563
 
564
  def handle_factory_reset(level, reason, backup):
565
+ level_map = {
566
+ "Soft (App-Daten)": ResetLevel.SOFT,
567
+ "Standard (App+Cache)": ResetLevel.STANDARD,
568
+ "Hard (Alles außer MDM)": ResetLevel.HARD,
569
+ "Factory (Vollständig)": ResetLevel.FACTORY,
570
+ }
571
 
572
  reset_lvl = level_map.get(level, ResetLevel.SOFT)
573
  required_sil = 3 if reset_lvl in [ResetLevel.HARD, ResetLevel.FACTORY] else 1
 
638
  updated_ids = [t.id for t in ai_agent.registered_tools]
639
  return f"✅ Tool '{tool_name}' ({tool_id}) in Kategorie '{tool_category}' registriert.", gr.Dropdown(choices=updated_ids)
640
 
641
+ def handle_refresh_status():
642
+ return json.loads(handle_get_system_status())
643
+
644
 
645
  # ============================================================
646
  # GRADIO 6 APPLICATION
 
658
  button_primary_background_fill="*primary_600",
659
  button_primary_background_fill_hover="*primary_700",
660
  block_title_text_weight="600",
 
 
 
661
  )
662
 
663
  with gr.Blocks() as demo:
 
666
  """
667
  # 🔧 Honeywell CT45P XP — E-Mobility Service Werkstatt
668
  ### UHAL Edge Workspace | Android 11 | NDK/SDK/AgentSDK/PowerTools
669
+
670
  [Built with anycoder](https://huggingface.co/spaces/akhaliq/anycoder)
671
  """
672
  )
 
674
  # System status bar
675
  with gr.Row():
676
  status_box = gr.JSON(label="System Status", value=json.loads(handle_get_system_status()), height=120)
677
+ refresh_status_btn = gr.Button("🔄 Status aktualisieren", size="sm")
678
+ refresh_status_btn.click(handle_refresh_status, outputs=status_box)
679
 
680
  with gr.Tabs():
681
 
 
688
  with gr.Row():
689
  with gr.Column(scale=1):
690
  gr.Markdown("#### 📷 Barcode Scanner (N6700)")
691
+ scan_btn = gr.Button("Hardware-Scan auslösen", variant="primary")
692
  scan_result = gr.Code(language="json", label="Scan-Ergebnis", lines=8)
693
 
694
  with gr.Column(scale=1):
695
  gr.Markdown("#### 🚗 OBD-II Diagnose (PowerTools)")
696
+ obd_btn = gr.Button("OBD-II Diagnose starten", variant="primary")
697
  obd_result = gr.Code(language="json", label="OBD-Ergebnis", lines=8)
698
 
699
  with gr.Row():
 
710
  with gr.Row():
711
  with gr.Column(scale=1):
712
  gr.Markdown("#### 💳 NFC Smart Card")
713
+ nfc_btn = gr.Button("NFC Tap-to-Identify", variant="primary")
714
  nfc_result = gr.Code(language="json", label="NFC-Ergebnis", lines=10)
715
 
716
  with gr.Column(scale=1):
 
734
  with gr.Row():
735
  with gr.Column(scale=1):
736
  gr.Markdown("#### 🔵 BLE Peripheral Scan")
737
+ ble_scan_btn = gr.Button("BLE LE Scan starten", variant="primary")
738
  ble_scan_result = gr.Code(language="json", label="BLE Geräte", lines=15)
739
 
740
  with gr.Column(scale=1):
 
780
  label="Tool auswählen",
781
  info="Wähle ein MCP-Tool zur Ausführung",
782
  )
783
+ mcp_execute_btn = gr.Button("Tool ausführen", variant="primary")
784
  mcp_result = gr.Textbox(label="Ausführungsergebnis", lines=6, max_lines=15)
785
 
786
  with gr.Column(scale=3):
 
841
  "BMS Zellspannungs-Analyse",
842
  "Isolationswiderstand prüfen",
843
  ],
 
844
  )
845
 
846
  with gr.Column(scale=2):
 
902
  sil_input = gr.Slider(
903
  minimum=1, maximum=4, value=1, step=1,
904
  label="SIL-Level",
905
+ info="1=Diagnose, 2=Konfiguration, 3=Firmware,