-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai_cli.py
More file actions
1529 lines (1320 loc) · 63 KB
/
Copy pathai_cli.py
File metadata and controls
1529 lines (1320 loc) · 63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Simple Signal CLI - A stylish local AI inference command-line interface
Provides a terminal-based AI assistant with beautiful output and interactive chat mode.
"""
import json
import os
import random
import re
import sys
import threading
import time
from datetime import datetime
from typing import Optional, List, Dict, Any
def load_env_file():
"""Load environment variables from .env file if it exists"""
# 1. Try local/script directory
for path in [os.getcwd(), os.path.dirname(__file__)]:
env_path = os.path.join(path, '.env')
if os.path.exists(env_path):
try:
with open(env_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
parts = line.split('=', 1)
if len(parts) == 2:
key = parts[0].strip()
val = parts[1].strip().strip('"\'')
if key not in os.environ:
os.environ[key] = val
except Exception:
pass
# 2. Try specific fallback path for Website Project backend
fallback_path = r"C:\Users\Falab\OneDrive\Documents\Website Project\backend\.env"
if os.path.exists(fallback_path):
try:
with open(fallback_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
parts = line.split('=', 1)
if len(parts) == 2:
key = parts[0].strip()
val = parts[1].strip().strip('"\'')
if key not in os.environ:
os.environ[key] = val
except Exception:
pass
# Load environment variables on startup
load_env_file()
# Optional ML dependencies are imported lazily so the desktop backend can bind
# its web server before loading heavyweight local-model libraries.
torch = None
torch_directml = None
AutoTokenizer = None
AutoModelForCausalLM = None
HAS_TORCH = False
HAS_DML = False
HAS_TRANSFORMERS = False
def ensure_torch() -> bool:
"""Load PyTorch only when local model inference actually needs it."""
global torch, HAS_TORCH
if HAS_TORCH and torch is not None:
return True
try:
import torch as torch_module
torch = torch_module
HAS_TORCH = True
return True
except ImportError:
HAS_TORCH = False
return False
def ensure_directml() -> bool:
"""Load torch-directml lazily for callers that explicitly need it."""
global torch_directml, HAS_DML
if HAS_DML and torch_directml is not None:
return True
try:
import torch_directml as torch_directml_module
torch_directml = torch_directml_module
HAS_DML = torch_directml.is_available()
return HAS_DML
except ImportError:
HAS_DML = False
return False
def ensure_transformers() -> bool:
"""Load Transformers only after API backends and config checks are done."""
global AutoTokenizer, AutoModelForCausalLM, HAS_TRANSFORMERS
if HAS_TRANSFORMERS and AutoTokenizer is not None and AutoModelForCausalLM is not None:
return True
try:
from transformers import AutoTokenizer as tokenizer_cls, AutoModelForCausalLM as model_cls
AutoTokenizer = tokenizer_cls
AutoModelForCausalLM = model_cls
HAS_TRANSFORMERS = True
return True
except ImportError:
HAS_TRANSFORMERS = False
return False
def has_transformers() -> bool:
return ensure_transformers()
class SimpleSignalAI:
"""Main AI inference engine with CLI interface"""
def __init__(self, model_path: Optional[str] = None):
self.model_path = model_path
self.tokenizer = None
self.model = None
self.config = self._load_config()
# Set up compute device: CUDA (NVIDIA GPU) -> CPU
# Note: DirectML (AMD GPU) is disabled for local PyTorch loading because the DirectML compiler
# has known bugs with Qwen/Llama architectures, resulting in random gibberish.
# AMD users should run the LM Studio local server (Vulkan/DirectML backend) which runs flawlessly.
self.device = "cpu"
self.is_api = False
self.api_url = None
self.selected_model = None
self.force_local = False
if self.model_path:
cleaned = self.model_path.strip('"\'')
if cleaned.startswith("http://") or cleaned.startswith("https://"):
self.is_api = True
self.api_url = cleaned
def _load_config(self) -> Dict[str, Any]:
"""Load configuration from config.json or use defaults"""
config_path = os.path.join(os.path.dirname(__file__), 'config.json')
if os.path.exists(config_path):
try:
with open(config_path, 'r') as f:
return json.load(f)
except Exception:
pass
# Default configuration
return {
"model": {
"path": None, # Set to actual model path if available
"max_length": 2048,
"temperature": 0.7,
"top_p": 0.9,
"repetition_penalty": 1.0
},
"chat": {
"system_prompt": "You are Simple Signal AI, a helpful local assistant.",
"max_tokens": 512
},
"output": {
"theme": "dark", # dark, light, cyberpunk
"verbose": True
}
}
def _save_config(self):
"""Save configuration to config.json"""
config_path = os.path.join(os.path.dirname(__file__), 'config.json')
try:
with open(config_path, 'w', encoding='utf-8') as f:
json.dump(self.config, f, indent=2)
except Exception:
pass
def _check_lm_studio(self) -> Optional[str]:
"""Check if LM Studio is running locally on localhost or 127.0.0.1"""
import urllib.request
import urllib.error
# Load API token from environment if available
api_token = os.environ.get("LM_API_TOKEN") or os.environ.get("SIGNAL_SHARE_LM_STUDIO_API_TOKEN")
for host in ["localhost", "127.0.0.1"]:
# Query the OpenAI-compatible models endpoint. LM Studio logs root
# requests as unexpected even when it returns 200.
test_url = f"http://{host}:1234/v1/models"
url = f"http://{host}:1234/v1"
try:
req = urllib.request.Request(test_url)
if api_token:
req.add_header("Authorization", f"Bearer {api_token}")
with urllib.request.urlopen(req, timeout=1.5) as response:
if response.status in [200, 401]:
return url
except urllib.error.HTTPError as e:
if e.code in [200, 401]:
# 401 means running but requires token
return url
except Exception:
pass
return None
def _check_llama_cpp(self) -> Optional[str]:
"""Check if llama.cpp server is running locally on localhost or 127.0.0.1"""
import urllib.request
import urllib.error
for host in ["localhost", "127.0.0.1"]:
# Query the health endpoint of llama-server (returns 200 or 401 if running)
test_url = f"http://{host}:8080/health"
url = f"http://{host}:8080/v1"
try:
req = urllib.request.Request(test_url)
with urllib.request.urlopen(req, timeout=1.0) as response:
if response.status in [200, 204, 401]:
return url
except urllib.error.HTTPError as e:
if e.code in [200, 204, 401]:
return url
except Exception:
# Fallback: try root port
try:
req = urllib.request.Request(f"http://{host}:8080/")
with urllib.request.urlopen(req, timeout=1.0) as response:
if response.status in [200, 401]:
return url
except Exception:
pass
return None
def _call_api(self, messages: List[Dict[str, str]], max_tokens: Optional[int] = None) -> str:
"""Call the OpenAI-compatible API endpoint"""
import urllib.request
import json
# Normalize url
if self.api_url.endswith("/chat/completions"):
url = self.api_url
else:
url = f"{self.api_url}/chat/completions"
headers = {"Content-Type": "application/json"}
# Load API token from environment if available
api_token = os.environ.get("LM_API_TOKEN") or os.environ.get("SIGNAL_SHARE_LM_STUDIO_API_TOKEN")
if api_token:
headers["Authorization"] = f"Bearer {api_token}"
payload = {
"messages": messages,
"temperature": self.config["model"].get("temperature", 0.7),
"max_tokens": max_tokens or self.config["chat"]["max_tokens"],
"top_p": self.config["model"].get("top_p", 0.9)
}
if getattr(self, "selected_model", None):
payload["model"] = self.selected_model
try:
data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
with urllib.request.urlopen(req, timeout=30.0) as response:
res_data = json.loads(response.read().decode("utf-8"))
return res_data["choices"][0]["message"]["content"]
except Exception as e:
print(f"\n❌ API Error: {e}")
return "Error: Could not retrieve response from API."
def load_model(self):
"""Load the AI model (API or local HF/GGUF format)"""
# 1. Check if we already detected API from model_path
if self.is_api:
print(f"🌐 Connected to remote API: {self.api_url}\n")
return True
# 2. Check if local LM Studio or llama.cpp is running
if not self.force_local:
lm_url = self._check_lm_studio()
if lm_url:
self.is_api = True
self.api_url = lm_url
print(f"🌐 Connected via GPU acceleration to LM Studio: {self.api_url}\n")
return True
llama_url = self._check_llama_cpp()
if llama_url:
self.is_api = True
self.api_url = llama_url
print(f"🌐 Connected via GPU acceleration to llama.cpp: {self.api_url}\n")
return True
# 3. Fallback to local model loading via transformers
if self.model_path is None:
print("ℹ️ No model path specified. Please set MODEL_PATH environment variable.")
return False
if not ensure_transformers():
print("\n⚠️ Transformers library not installed. Running in demo mode.\n")
return False
if not ensure_torch():
print("\n⚠️ PyTorch library not installed. Running in demo mode.\n")
return False
try:
self.device = "cuda" if torch.cuda.is_available() else "cpu"
model_dir = self.model_path
gguf_file = None
# Clean path quotes if any
model_dir = model_dir.strip('"\'')
# Detect if pointing to a GGUF file or a directory containing a GGUF file
if os.path.isfile(model_dir) and model_dir.endswith('.gguf'):
gguf_file = os.path.basename(model_dir)
model_dir = os.path.dirname(model_dir)
elif os.path.isdir(model_dir):
files = os.listdir(model_dir)
gguf_files = [f for f in files if f.endswith('.gguf')]
if gguf_files:
gguf_file = gguf_files[0]
device_map = "auto" if str(self.device) in ["cuda", "cpu"] else None
if gguf_file:
# Check for gguf package dependency
try:
import gguf
except ImportError:
print("\n⚠️ GGUF models require the 'gguf' package. Installing it now...\n")
import subprocess
import sys
subprocess.run([sys.executable, "-m", "pip", "install", "gguf"], check=True)
print(f"🔄 Loading GGUF model: {gguf_file} from {model_dir}")
self.tokenizer = AutoTokenizer.from_pretrained(model_dir, gguf_file=gguf_file)
self.model = AutoModelForCausalLM.from_pretrained(
model_dir,
gguf_file=gguf_file,
device_map=device_map,
torch_dtype=torch.float16 if (HAS_TORCH and torch.cuda.is_available()) else torch.float32
)
else:
print(f"🔄 Loading model from: {model_dir}")
self.tokenizer = AutoTokenizer.from_pretrained(model_dir)
self.model = AutoModelForCausalLM.from_pretrained(
model_dir,
device_map=device_map,
torch_dtype=torch.float16 if (HAS_TORCH and torch.cuda.is_available()) else torch.float32
)
# Move model to custom device (e.g. DirectML) if not handled by device_map="auto"
if str(self.device) not in ["cpu", "cuda"] and self.device is not None:
print(f"📦 Moving model to acceleration device: {self.device}...")
self.model = self.model.to(self.device)
print("✅ Model loaded successfully!\n")
return True
except Exception as e:
print(f"❌ Error loading model: {e}\n")
return False
def generate(self, prompt: str, max_tokens: Optional[int] = None) -> str:
"""Generate text from the model"""
if self.is_api:
messages = [
{"role": "system", "content": self.config["chat"]["system_prompt"]},
{"role": "user", "content": prompt}
]
return self._call_api(messages, max_tokens)
if self.model is None:
# Demo mode - simple response
demo_responses = [
"This is a demo response. To use real AI inference, install transformers and set MODEL_PATH.",
"I'm Simple Signal AI! I can help you with various tasks once properly configured.",
"Hello! I'm your local AI assistant. Try asking me something!"
]
return demo_responses[0]
try:
messages = [
{"role": "system", "content": self.config["chat"]["system_prompt"]},
{"role": "user", "content": prompt}
]
# Apply chat template if available, fallback to simple format
try:
full_prompt = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
except Exception:
full_prompt = f"{messages[0]['content']}\n\n{messages[1]['content']}"
inputs = self.tokenizer(full_prompt, return_tensors="pt")
# Move inputs to device (e.g. DirectML) if accelerating
if str(self.device) != "cpu" and self.device is not None:
inputs = {k: v.to(self.device) for k, v in inputs.items()}
# Generate
temp = self.config["model"].get("temperature", 0.7)
top_p = self.config["model"].get("top_p", 0.9)
do_sample = temp > 0.0
output = self.model.generate(
**inputs,
max_new_tokens=max_tokens or self.config["chat"]["max_tokens"],
do_sample=do_sample,
temperature=temp,
top_p=top_p
)
# Decode only the generated tokens
input_length = inputs["input_ids"].shape[-1]
new_tokens = output[0][input_length:]
response = self.tokenizer.decode(new_tokens, skip_special_tokens=True)
return response.strip()
except Exception as e:
print(f"❌ Generation error: {e}")
return "Error generating response."
def chat(self, messages: List[Dict[str, str]]) -> str:
"""Process a conversation and generate response"""
if self.is_api:
chat_messages = []
has_system = any(msg.get("role") == "system" for msg in messages)
if not has_system:
chat_messages.append({"role": "system", "content": self.config["chat"]["system_prompt"]})
chat_messages.extend(messages)
return self._call_api(chat_messages, self.config["chat"]["max_tokens"])
if self.model is None:
return "Demo mode: Please install transformers and load a model for real inference."
try:
# Apply chat template if available, fallback to simple format
try:
chat_messages = []
has_system = any(msg.get("role") == "system" for msg in messages)
if not has_system:
chat_messages.append({"role": "system", "content": self.config["chat"]["system_prompt"]})
chat_messages.extend(messages)
full_prompt = self.tokenizer.apply_chat_template(chat_messages, tokenize=False, add_generation_prompt=True)
except Exception:
prompt_parts = []
for msg in messages:
role = msg.get("role", "user")
content = msg.get("content", "")
prefix = {"system": "SYS ", "user": "USR ", "assistant": "ASSISTANT "}.get(role, "USR ")
prompt_parts.append(f"{prefix}{content}")
full_prompt = "\n\n".join(prompt_parts)
full_prompt += "\n\nASSISTANT: "
inputs = self.tokenizer(full_prompt, return_tensors="pt", truncation=True, max_length=self.config["model"]["max_length"])
# Move inputs to device (e.g. DirectML) if accelerating
if str(self.device) != "cpu" and self.device is not None:
inputs = {k: v.to(self.device) for k, v in inputs.items()}
temp = self.config["model"].get("temperature", 0.7)
top_p = self.config["model"].get("top_p", 0.9)
do_sample = temp > 0.0
output = self.model.generate(
**inputs,
max_new_tokens=self.config["chat"]["max_tokens"],
do_sample=do_sample,
temperature=temp,
top_p=top_p
)
# Decode only the generated tokens
input_length = inputs["input_ids"].shape[-1]
new_tokens = output[0][input_length:]
response = self.tokenizer.decode(new_tokens, skip_special_tokens=True)
return response.strip()
except Exception as e:
print(f"❌ Chat error: {e}")
return "Error processing conversation."
from typing import Tuple
def format_latex_math(text: str) -> str:
"""Format LaTeX mathematical expressions in text into pretty Unicode representations."""
greek_letters = {
r'\alpha': 'α', r'\beta': 'β', r'\gamma': 'γ', r'\delta': 'δ', r'\epsilon': 'ε',
r'\zeta': 'ζ', r'\eta': 'η', r'\theta': 'θ', r'\iota': 'ι', r'\kappa': 'κ',
r'\lambda': 'λ', r'\mu': 'μ', r'\nu': 'ν', r'\xi': 'ξ', r'\pi': 'π',
r'\rho': 'ρ', r'\sigma': 'σ', r'\tau': 'τ', r'\upsilon': 'υ', r'\phi': 'φ',
r'\chi': 'χ', r'\psi': 'ψ', r'\omega': 'ω',
r'\Delta': 'Δ', r'\Sigma': 'Σ', r'\Omega': 'Ω', r'\Theta': 'Θ', r'\Pi': 'Π',
r'\Phi': 'Φ', r'\Psi': 'Ψ', r'\Gamma': 'Γ', r'\Lambda': 'Λ'
}
math_symbols = {
r'\sum': '∑', r'\prod': '∏', r'\int': '∫', r'\sqrt': '√', r'\infty': '∞',
r'\approx': '≈', r'\neq': '≠', r'\le': '≤', r'\ge': '≥', r'\pm': '±',
r'\times': '×', r'\div': '÷', r'\cdot': '·', r'\partial': '∂', r'\nabla': '∇',
r'\in': '∈', r'\notin': '∉', r'\forall': '∀', r'\exists': '∃', r'\to': '→',
r'\left': '', r'\right': ''
}
superscripts = {
'0': '⁰', '1': '¹', '2': '²', '3': '³', '4': '⁴', '5': '⁵', '6': '⁶', '7': '⁷', '8': '⁸', '9': '⁹',
'+': '⁺', '-': '⁻', '=': '⁼', '(': '⁽', ')': '⁾', 'n': 'ⁿ', 'x': 'ˣ', 'y': 'ʸ', 'z': 'ᶻ', 'i': 'ⁱ',
'j': 'ʲ', 'r': 'ʳ', 't': 'ᵗ', 'a': 'ᵃ', 'b': 'ᵇ', 'c': 'ᶜ', 'd': 'ᵈ', 'e': 'ᵉ', 'f': 'ᶠ', 'g': 'ᵍ',
'h': 'ʰ', 'k': 'ᵏ', 'l': 'ˡ', 'm': 'ᵐ', 'o': 'ᵒ', 'p': 'ᵖ', 's': 'ˢ', 'u': 'ᵘ', 'v': 'ᵛ', 'w': 'ʷ'
}
subscripts = {
'0': '₀', '1': '₁', '2': '₂', '3': '₃', '4': '₄', '5': '₅', '6': '₆', '7': '₇', '8': '₈', '9': '₉',
'+': '₊', '-': '₋', '=': '₌', '(': '₍', ')': '₎', 'a': 'ₐ', 'e': 'ₑ', 'h': 'ₕ', 'i': 'ᵢ', 'j': 'ⱼ',
'k': 'ₖ', 'l': 'ₗ', 'm': 'ₘ', 'n': 'ₙ', 'o': 'ₒ', 'p': 'ₚ', 'r': 'ᵣ', 's': 'ₛ', 't': 'ₜ', 'u': 'ᵤ',
'v': 'ᵥ', 'x': 'ₓ'
}
def convert_script(val: str, mapping: dict) -> str:
return "".join(mapping.get(char, char) for char in val)
def process_math_block(match) -> str:
expr = match.group(1)
# 1. Replace Greek letters and math symbols
for key, val in greek_letters.items():
expr = expr.replace(key, val)
for key, val in math_symbols.items():
expr = expr.replace(key, val)
# 2. Replace superscripts: ^{content}
expr = re.sub(r'\^\{([^}]+)\}', lambda m: convert_script(m.group(1), superscripts), expr)
# Replace single character superscripts: ^c
expr = re.sub(r'\^(\w|\+|-|=)', lambda m: convert_script(m.group(1), superscripts), expr)
# 3. Replace subscripts: _{content}
expr = re.sub(r'\_\{([^}]+)\}', lambda m: convert_script(m.group(1), subscripts), expr)
# Replace single character subscripts: _c
expr = re.sub(r'\_(\w|\+|-|=)', lambda m: convert_script(m.group(1), subscripts), expr)
# 4. Clean up fractions
expr = re.sub(r'\\frac\{([^}]+)\}\{([^}]+)\}', r'(\1/\2)', expr)
return expr
# Process double dollar blocks first
text = re.sub(r'\$\$(.*?)\$\$', process_math_block, text, flags=re.DOTALL)
# Process single dollar blocks
text = re.sub(r'\$(.*?)\$', process_math_block, text)
# Process brackets and parentheses blocks
text = re.sub(r'\\\\\[(.*?)\\\\\]', process_math_block, text, flags=re.DOTALL)
text = re.sub(r'\\\[(.*?)\\\]', process_math_block, text, flags=re.DOTALL)
text = re.sub(r'\\\\\((.*?)\\\\\)', process_math_block, text, flags=re.DOTALL)
text = re.sub(r'\\\((.*?)\\\)', process_math_block, text, flags=re.DOTALL)
return text
def find_empty(board: List[List[int]]) -> Optional[Tuple[int, int]]:
"""Find an empty cell in the Sudoku board."""
for r in range(9):
for c in range(9):
if board[r][c] == 0:
return r, c
return None
def is_valid(board: List[List[int]], row: int, col: int, num: int) -> bool:
"""Check if placing num at board[row][col] is valid."""
# Check row and column
for i in range(9):
if board[row][i] == num or board[i][col] == num:
return False
# Check 3x3 box
start_row = (row // 3) * 3
start_col = (col // 3) * 3
for i in range(3):
for j in range(3):
if board[start_row + i][start_col + j] == num:
return False
return True
def solve_sudoku(board: List[List[int]]) -> bool:
"""Solve the Sudoku board using backtracking."""
empty = find_empty(board)
if not empty:
return True
row, col = empty
nums = list(range(1, 10))
random.shuffle(nums)
for num in nums:
if is_valid(board, row, col, num):
board[row][col] = num
if solve_sudoku(board):
return True
board[row][col] = 0
return False
def generate_sudoku(size: int = 9) -> Tuple[List[List[int]], List[List[int]]]:
"""Generate a valid Sudoku puzzle and its solution."""
if size != 9:
raise ValueError("Only 9x9 supported.")
board = [[0] * size for _ in range(size)]
# Fill diagonal boxes first (independent of each other)
def fill_box(r, c):
nums = list(range(1, 10))
random.shuffle(nums)
for i in range(3):
for j in range(3):
board[r + i][c + j] = nums[i * 3 + j]
fill_box(0, 0)
fill_box(3, 3)
fill_box(6, 6)
# Solve the rest of the board
solve_sudoku(board)
# Save the solution
solution = [row[:] for row in board]
# Remove digits to create puzzle (remove ~50% of digits)
cells_to_remove = random.sample(range(size**2), int(size**2 * 0.50))
for idx in cells_to_remove:
r, c = divmod(idx, size)
board[r][c] = 0
return board, solution
def is_solution_valid(board: List[List[int]]) -> bool:
"""Check if the completed board is a valid solution."""
# Check rows
for row in board:
if sorted(row) != list(range(1, 10)):
return False
# Check columns
for col_idx in range(9):
col = [board[row_idx][col_idx] for row_idx in range(9)]
if sorted(col) != list(range(1, 10)):
return False
# Check 3x3 boxes
for r in range(0, 9, 3):
for c in range(0, 9, 3):
box = []
for i in range(3):
for j in range(3):
box.append(board[r + i][c + j])
if sorted(box) != list(range(1, 10)):
return False
return True
def play_sudoku_curses(stdscr, puzzle: List[List[int]], solution: List[List[int]]):
"""Play Sudoku in curses mode."""
import curses
curses.curs_set(0)
curses.start_color()
curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) # original numbers
curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK) # user numbers
curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLUE) # cursor selection
curses.init_pair(4, curses.COLOR_GREEN, curses.COLOR_BLACK) # success
curses.init_pair(5, curses.COLOR_RED, curses.COLOR_BLACK) # error
current_board = [row[:] for row in puzzle]
is_original = [[puzzle[r][c] != 0 for c in range(9)] for r in range(9)]
row, col = 0, 0
while True:
stdscr.clear()
stdscr.addstr(1, 2, "🎮 SUDOKU GAME CLI", curses.color_pair(1) | curses.A_BOLD)
stdscr.addstr(2, 2, "Use arrow keys to move, 1-9 to fill, Backspace/0 to clear, 'q' to quit.")
stdscr.addstr(3, 2, "Press 's' to submit and check solution.")
# Draw background grid
stdscr.addstr(4, 2, "╔═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╗")
for r in range(9):
stdscr.addstr(5 + r*2, 2, "║ │ │ ║ │ │ ║ │ │ ║")
if r < 8:
if (r + 1) % 3 == 0:
stdscr.addstr(6 + r*2, 2, "╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣")
else:
stdscr.addstr(6 + r*2, 2, "╟───┼───┼───╫───┼───┼───╫───┼───┼───╢")
stdscr.addstr(22, 2, "╚═══╧═══╧═══╩═══╧═══╧═══╩═══╧═══╧═══╝")
# Draw values
for r in range(9):
for c in range(9):
val = current_board[r][c]
val_str = str(val) if val != 0 else "."
if r == row and c == col:
attr = curses.color_pair(3) | curses.A_BOLD
else:
attr = curses.color_pair(1) if is_original[r][c] else curses.color_pair(2)
stdscr.addstr(5 + r*2, 4 + c*4, val_str, attr)
stdscr.refresh()
key = stdscr.getch()
if key == ord('q'):
break
elif key == curses.KEY_UP and row > 0:
row -= 1
elif key == curses.KEY_DOWN and row < 8:
row += 1
elif key == curses.KEY_LEFT and col > 0:
col -= 1
elif key == curses.KEY_RIGHT and col < 8:
col += 1
elif ord('1') <= key <= ord('9'):
if not is_original[row][col]:
current_board[row][col] = int(chr(key))
elif key in [ord('0'), curses.KEY_BACKSPACE, 127, 8]:
if not is_original[row][col]:
current_board[row][col] = 0
elif key == ord('s'):
if is_solution_valid(current_board):
stdscr.addstr(24, 2, "🎉 CONGRATULATIONS! You solved the Sudoku correctly!", curses.color_pair(4) | curses.A_BOLD)
stdscr.addstr(25, 2, "Press any key to exit.")
stdscr.refresh()
stdscr.getch()
break
else:
stdscr.addstr(24, 2, "❌ Not quite correct yet! Keep trying.", curses.color_pair(5) | curses.A_BOLD)
stdscr.addstr(25, 2, "Press any key to continue.")
stdscr.refresh()
stdscr.getch()
def play_sudoku_text(puzzle: List[List[int]], solution: List[List[int]]):
"""Play Sudoku in text mode."""
current_board = [row[:] for row in puzzle]
is_original = [[puzzle[r][c] != 0 for c in range(9)] for r in range(9)]
def print_board():
print("\n ╔═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╗")
for r in range(9):
if r > 0:
if r % 3 == 0:
print(" ╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣")
else:
print(" ╟───┼───┼───╫───┼───┼───╫───┼───┼───╢")
row_chars = []
for c in range(9):
val = current_board[r][c]
val_str = str(val) if val != 0 else "."
if is_original[r][c]:
row_chars.append(f"\033[94m{val_str}\033[0m")
elif val != 0:
row_chars.append(f"\033[92m{val_str}\033[0m")
else:
row_chars.append(val_str)
print(f" ║ {row_chars[0]} │ {row_chars[1]} │ {row_chars[2]} ║ {row_chars[3]} │ {row_chars[4]} │ {row_chars[5]} ║ {row_chars[6]} │ {row_chars[7]} │ {row_chars[8]} ║")
print(" ╚═══╧═══╧═══╩═══╧═══╧═══╩═══╧═══╧═══╝")
while True:
print_board()
print("\nCommands:")
print(" - Fill cell: 'r c v' (row column value, e.g. '1 1 5' for row 1, col 1, value 5)")
print(" - Clear cell: 'r c 0' (e.g. '1 1 0')")
print(" - 'submit' to check solution")
print(" - 'quit' to exit game")
try:
cmd = input("\nEnter command: ").strip().lower()
if cmd == 'quit':
break
elif cmd == 'submit':
if is_solution_valid(current_board):
print("\n🎉 CONGRATULATIONS! You solved the Sudoku correctly!\n")
break
else:
print("\n❌ Not quite correct yet! Keep trying.\n")
else:
parts = cmd.split()
if len(parts) == 3:
r, c, v = int(parts[0]) - 1, int(parts[1]) - 1, int(parts[2])
if 0 <= r < 9 and 0 <= c < 9 and 0 <= v <= 9:
if is_original[r][c]:
print("\n⚠️ Cannot modify original puzzle cell!\n")
else:
current_board[r][c] = v
else:
print("\n⚠️ Invalid values! Row/Col should be 1-9, Value 0-9.\n")
else:
print("\n⚠️ Invalid command format! Use 'row col value' (e.g. '1 2 5') or 'submit' or 'quit'.\n")
except KeyboardInterrupt:
print("\nGame exited.")
break
except Exception:
print("\n⚠️ Error parsing command. Try again.\n")
class ThinkingSpinner:
"""A CLI spinner that runs in a background thread to indicate thinking or loading"""
def __init__(self, prefix: str = "🤖 ", prompt_color: str = "", text_color: str = "", message: str = "Thinking..."):
self.prefix = prefix
self.prompt_color = prompt_color
self.text_color = text_color
self.message = message
self.stop_event = threading.Event()
self.thread = None
def _spin(self):
chars = ["/", "-", "\\", "|"]
reset = "\033[0m"
i = 0
while not self.stop_event.is_set():
char = chars[i % len(chars)]
sys.stdout.write(f"\r{self.prompt_color}{self.prefix}AI:{reset} {self.text_color}{self.message} {char}{reset}")
sys.stdout.flush()
i += 1
time.sleep(0.1)
# Clear the spinner line
sys.stdout.write("\r\033[K")
sys.stdout.flush()
def start(self):
self.stop_event.clear()
self.thread = threading.Thread(target=self._spin, daemon=True)
self.thread.start()
def stop(self):
if self.thread:
self.stop_event.set()
self.thread.join(timeout=1.0)
def __enter__(self):
self.start()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.stop()
class CLIInterface:
"""Command-line interface with styling"""
THEMES = {
"dark": {
"prompt_prefix": "🤖 ",
"user_prefix": "👤 ",
"separator": "─" * 60,
"info": "ℹ️ ",
"success": "✅ ",
"error": "❌ ",
"warning": "⚠️ ",
"bg_color": "",
"text_color": "\033[38;5;253m",
"prompt_color": "\033[1;38;5;111m",
"user_color": "\033[38;5;244m",
"accent_color": "\033[38;5;111m"
},
"light": {
"prompt_prefix": "🤖 ",
"user_prefix": "👤 ",
"separator": "─" * 60,
"info": "ℹ️ ",
"success": "✅ ",
"error": "❌ ",
"warning": "⚠️ ",
"bg_color": "",
"text_color": "\033[38;5;255m",
"prompt_color": "\033[1;38;5;231m",
"user_color": "\033[38;5;252m",
"accent_color": "\033[38;5;250m"
},
"cyberpunk": {
"prompt_prefix": "🔮 ",
"user_prefix": "⚡ ",
"separator": "░▒▓" * 20,
"info": "⚡ ",
"success": "✨ ",
"error": "🚨 ",
"warning": "⚠️ ",
"bg_color": "",
"text_color": "\033[38;5;226m",
"prompt_color": "\033[1;38;5;201m",
"user_color": "\033[38;5;51m",
"accent_color": "\033[38;5;201m"
},
"matrix": {
"prompt_prefix": "📟 ",
"user_prefix": "💾 ",
"separator": "═" * 60,
"info": "[SYS] ",
"success": "[RUN] ",
"error": "[ERR] ",
"warning": "[WRN] ",
"bg_color": "",
"text_color": "\033[38;5;47m",
"prompt_color": "\033[1;38;5;46m",
"user_color": "\033[38;5;28m",
"accent_color": "\033[38;5;46m"
},
"sunset": {
"prompt_prefix": "🌅 ",
"user_prefix": "👤 ",
"separator": "─" * 60,
"info": "🌅 ",
"success": "🍊 ",
"error": "🔥 ",
"warning": "⚡ ",
"bg_color": "",
"text_color": "\033[38;5;220m",
"prompt_color": "\033[1;38;5;202m",
"user_color": "\033[38;5;208m",
"accent_color": "\033[38;5;202m"
},
"ocean": {
"prompt_prefix": "🌊 ",
"user_prefix": "⛵ ",
"separator": "≈" * 60,
"info": "🐬 ",
"success": "🌊 ",
"error": "🚨 ",
"warning": "⚠️ ",
"bg_color": "",
"text_color": "\033[38;5;153m",
"prompt_color": "\033[1;38;5;33m",
"user_color": "\033[38;5;75m",
"accent_color": "\033[38;5;39m"
},
"forest": {
"prompt_prefix": "🌿 ",
"user_prefix": "🌲 ",
"separator": "─" * 60,
"info": "🌿 ",
"success": "🍃 ",
"error": "🍂 ",
"warning": "⚠️ ",
"bg_color": "",
"text_color": "\033[38;5;107m",
"prompt_color": "\033[1;38;5;34m",
"user_color": "\033[38;5;94m",
"accent_color": "\033[38;5;71m"
},
"dracula": {
"prompt_prefix": "🧛 ",
"user_prefix": "🦇 ",
"separator": "─" * 60,
"info": "🔮 ",
"success": "✨ ",
"error": "🩸 ",
"warning": "⚠️ ",
"bg_color": "",
"text_color": "\033[38;5;231m",
"prompt_color": "\033[1;38;5;141m",
"user_color": "\033[38;5;212m",
"accent_color": "\033[38;5;117m"
}
}
def __init__(self, ai: SimpleSignalAI):
self.ai = ai
self.theme_name = ai.config["output"]["theme"]
self.theme = self.THEMES.get(self.theme_name, self.THEMES["dark"])
def print_header(self):
"""Print the application header"""
accent = self.theme.get("accent_color", "")
reset = "\033[0m"
print("\n" + accent + self.theme["separator"] + reset)
print(f"{self.theme['success']} " + accent + "Simple Signal CLI v1.0" + reset)
print(f"{self.theme['info']} " + accent + "Local AI Inference Interface" + reset)
print(accent + self.theme["separator"] + reset)
def print_footer(self):
"""Print the application footer"""
accent = self.theme.get("accent_color", "")
reset = "\033[0m"
print(accent + self.theme["separator"] + reset)
print(f"{self.theme['info']} Type 'quit' or press Ctrl+C to exit")
print(accent + self.theme["separator"] + reset + "\n")
def _show_help(self):
"""Show list of commands and summary of the program"""
accent = self.theme.get("accent_color", "")
text_color = self.theme.get("text_color", "")
reset = "\033[0m"
print("\n" + accent + self.theme["separator"] + reset)
print(f"{self.theme['success']} " + accent + "Simple Signal CLI - Help & Summary" + reset)
print(accent + self.theme["separator"] + reset)