-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathultra_intelligent_chatbot.py
More file actions
3172 lines (2756 loc) · 155 KB
/
ultra_intelligent_chatbot.py
File metadata and controls
3172 lines (2756 loc) · 155 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
"""
ULTRA INTELLIGENT CHATBOT - WORLD CLASS CONVERSATIONAL AI
This is the most advanced AI possible - understands typos, gives suggestions,
provides ChatGPT-like experience specialized for Manhattan Power Grid
"""
import os
import json
import asyncio
import time
from typing import Dict, List, Any, Optional, Tuple
from datetime import datetime
try:
from openai import OpenAI
import openai
except ImportError:
OpenAI = None
openai = None
from dataclasses import dataclass
import re
from difflib import SequenceMatcher, get_close_matches
# Try to import Levenshtein, fallback if not available
try:
import Levenshtein
except ImportError:
# Fallback implementation
class Levenshtein:
@staticmethod
def distance(s1, s2):
if len(s1) < len(s2):
return Levenshtein.distance(s2, s1)
if len(s2) == 0:
return len(s1)
previous_row = list(range(len(s2) + 1))
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
# Initialize OpenAI client
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
openai_client = None
if OPENAI_API_KEY and OpenAI:
try:
openai_client = OpenAI(api_key=OPENAI_API_KEY)
print("[ULTRA CHATBOT] OpenAI client initialized successfully")
except Exception as e:
print(f"[ULTRA CHATBOT] Failed to initialize OpenAI client: {e}")
openai_client = None
else:
print("[ULTRA CHATBOT] OpenAI not available - API key missing or package not installed")
class UltraIntelligentChatbot:
"""The most advanced conversational AI possible - like ChatGPT but specialized"""
def __init__(self, integrated_system, ml_engine, v2g_manager, flask_app):
self.integrated_system = integrated_system
self.ml_engine = ml_engine
self.v2g_manager = v2g_manager
self.flask_app = flask_app
# ADVANCED CONVERSATION MEMORY & CONTEXT
self.conversation_history = []
self.last_suggestions = [] # Track recent suggestions for context
self.pending_confirmations = {} # Track pending confirmations
self.conversation_context = {} # Track conversation state
self.conversation_context = {
'last_mentioned_location': None,
'last_mentioned_substation': None,
'last_action': None,
'conversation_topics': [],
'entity_references': {}, # Track "it", "that", "the station" etc.
'session_entities': set(), # All entities mentioned in session
}
# ULTIMATE WORLD-CLASS COMMAND KNOWLEDGE BASE
self.command_knowledge = {
# Substation commands
'substation_commands': [
'turn off times square', 'turn on times square', 'disable times square',
'turn off central park', 'turn on central park', 'disable central park',
'turn off wall street', 'turn on wall street', 'disable wall street',
'turn off broadway', 'turn on broadway', 'disable broadway',
'shut down substation', 'power off substation', 'restart substation',
'substation status', 'check substation', 'substation health'
],
# Location/Map commands
'location_commands': [
'show times square', 'show central park', 'show wall street', 'show broadway',
'map times square', 'location of times square', 'where is times square',
'zoom to times square', 'highlight times square', 'focus on times square',
'show me the map', 'display location', 'map view', 'coordinates'
],
# EV Charging Station commands
'ev_charging_commands': [
'show charging near', 'show ev near', 'show ev station near', 'show charging station near',
'ev charging near', 'charging near', 'ev stations near', 'charging stations near',
'show chargers near', 'chargers near', 'ev charger near', 'charging for'
],
# Map control commands (zoom, camera, view)
'map_control_commands': [
'zoom in', 'zoom out', 'zoom in more', 'zoom out more', 'reset zoom',
'bird view', 'top view', 'aerial view', 'birds eye',
'tilt camera', 'angle view', '3d view', 'tilted view',
'show overview', 'overview mode'
],
# WORLD-CLASS ROUTE & NAVIGATION COMMANDS
'route_commands': [
'route from', 'route to', 'path from', 'path to', 'directions from', 'directions to',
'navigate from', 'navigate to', 'how to get from', 'how to get to',
'shortest route', 'fastest route', 'best route', 'optimal route',
'distance from', 'distance to', 'how far from', 'how far to'
],
# ADVANCED VISUALIZATION COMMANDS
# POWER GRID VISUALIZATION COMMANDS (World-Class Feature)
'power_grid_visualization_commands': [
'show power grid', 'visualize grid', 'display grid', 'grid overlay',
'show substations', 'visualize substations', 'substation map', 'power network',
'show grid status', 'grid health', 'power distribution', 'electrical network',
'show connections', 'power lines', 'transmission lines', 'grid topology'
],
# INTELLIGENCE & ANALYSIS COMMANDS
'intelligence_commands': [
'analyze route', 'optimize route', 'find best location', 'suggest placement',
'predict demand', 'forecast load', 'assess coverage', 'evaluate efficiency',
'identify bottlenecks', 'find gaps', 'detect patterns', 'recommend actions'
],
# V2G commands
'v2g_commands': [
'activate v2g', 'turn on v2g', 'enable v2g', 'start v2g',
'deactivate v2g', 'turn off v2g', 'disable v2g', 'stop v2g', 'shutdown v2g',
'v2g status', 'vehicle to grid', 'electric vehicles', 'ev status',
'charge vehicles', 'discharge vehicles', 'v2g capacity'
],
# System analysis
'analysis_commands': [
'analyze system', 'system status', 'grid status', 'overview',
'health check', 'system report', 'performance analysis',
'power grid analysis', 'infrastructure status', 'diagnostics'
],
# Emergency commands
'emergency_commands': [
'emergency', 'help', 'shutdown everything', 'emergency stop',
'crisis mode', 'emergency response', 'urgent', 'critical'
]
}
# TYPO CORRECTION PATTERNS
self.common_typos = {
# Location typos
'times squar': 'times square',
'time square': 'times square',
'times squere': 'times square',
'tims square': 'times square',
'times sqaure': 'times square',
'central pak': 'central park',
'centrel park': 'central park',
'central prak': 'central park',
'wal street': 'wall street',
'wall st': 'wall street',
'broadwy': 'broadway',
'brodway': 'broadway',
# Charging/Station typos
'charing': 'charging',
'chargin': 'charging',
'chraging': 'charging',
'chagring': 'charging',
'staion': 'station',
'sattion': 'station',
'sttion': 'station',
'statoin': 'station',
# Command typos
'turn of': 'turn off',
'trun off': 'turn off',
'turnn off': 'turn off',
'turn on': 'turn on',
'trun on': 'turn on',
'sho me': 'show me',
'shwo me': 'show me',
'show mi': 'show me',
'activate': 'activate',
'activat': 'activate',
'analys': 'analyze',
'analize': 'analyze',
'statu': 'status',
'satatus': 'status',
'systme': 'system',
'sytem': 'system',
# Confirmation typos
'confrim': 'confirm',
'confrm': 'confirm',
'comfirm': 'confirm',
'cofirm': 'confirm',
'cancle': 'cancel',
'cancl': 'cancel',
'cansel': 'cancel',
# Vehicle/spawn typos
'stat vehicles': 'start vehicles',
'strart vehicles': 'start vehicles',
'strat vehicles': 'start vehicles',
'start vehicels': 'start vehicles',
'start vehi': 'start vehicles',
'start vehic': 'start vehicles',
'strt vehicles': 'start vehicles',
'satrt vehicles': 'start vehicles',
'sart vehicles': 'start vehicles',
'startvehicles': 'start vehicles',
'start veh': 'start vehicles',
'spwan vehicles': 'spawn vehicles',
'spawn vehicels': 'spawn vehicles',
'strart': 'start',
'strat': 'start',
'spwan': 'spawn'
}
# Complete Manhattan power grid locations from your REAL backend system
self.manhattan_locations = {
'times square': {
'name': 'Times Square',
'coords': [-73.9857, 40.7580],
'type': 'commercial',
'substation': 'Times Square',
'capacity_mva': 850,
'aliases': ['times sq', 'time square', 'times squere', 'tims square', 'ts'],
'description': 'Major commercial hub - 850MVA capacity'
},
'penn station': {
'name': 'Penn Station',
'coords': [-73.9904, 40.7505],
'type': 'transport',
'substation': 'Penn Station',
'capacity_mva': 900,
'aliases': ['penn', 'penn st', 'pennsylv', 'pennsylvania'],
'description': 'Major transport hub - 900MVA capacity'
},
'grand central': {
'name': 'Grand Central',
'coords': [-73.9772, 40.7527],
'type': 'transport',
'substation': 'Grand Central',
'capacity_mva': 1000,
'aliases': ['grand', 'central', 'gc', 'grand central station'],
'description': 'Largest substation - 1000MVA capacity'
},
'chelsea': {
'name': 'Chelsea',
'coords': [-73.9969, 40.7439],
'type': 'residential',
'substation': 'Chelsea',
'capacity_mva': 600,
'aliases': ['chel', 'chelsea area'],
'description': 'Residential area - 600MVA capacity'
},
'murray hill': {
'name': 'Murray Hill',
'coords': [-73.9816, 40.7486],
'type': 'residential',
'substation': 'Murray Hill',
'capacity_mva': 650,
'aliases': ['murray', 'murrayhill', 'mur hill'],
'description': 'Residential area - 650MVA capacity'
},
'turtle bay': {
'name': 'Turtle Bay',
'coords': [-73.9665, 40.7519],
'type': 'mixed',
'substation': 'Turtle Bay',
'capacity_mva': 700,
'aliases': ['turtle', 'turtlebay', 'tb'],
'description': 'Mixed use area - 700MVA capacity'
},
'hells kitchen': {
'name': 'Hells Kitchen',
'coords': [-73.9897, 40.7648],
'type': 'residential',
'substation': "Hell's Kitchen",
'capacity_mva': 750,
'aliases': ['hells', 'hell kitchen', 'hk', 'clinton'],
'description': 'Residential area - 750MVA capacity'
},
'midtown east': {
'name': 'Midtown East',
'coords': [-73.9735, 40.7549],
'type': 'commercial',
'substation': 'Midtown East',
'capacity_mva': 800,
'aliases': ['midtown', 'mideast', 'me'],
'description': 'Commercial district - 800MVA capacity'
},
'central park': {
'name': 'Central Park',
'coords': [-73.9654, 40.7829],
'type': 'park',
'substation': 'Central Park',
'capacity_mva': 400,
'aliases': ['cp', 'central', 'park'],
'description': 'Central Park area - 400MVA capacity'
},
# MAJOR STREETS & AVENUES
'broadway': {
'name': 'Broadway',
'coords': [-73.9857, 40.7580],
'type': 'street',
'substation': 'Times Square',
'aliases': ['broadway ave', 'great white way'],
'description': 'Famous street running through Times Square'
},
'fifth avenue': {
'name': 'Fifth Avenue',
'coords': [-73.9772, 40.7527],
'type': 'street',
'substation': 'Grand Central',
'aliases': ['5th ave', '5th avenue', 'fifth ave'],
'description': 'Luxury shopping avenue'
},
'madison avenue': {
'name': 'Madison Avenue',
'coords': [-73.9735, 40.7549],
'type': 'street',
'substation': 'Midtown East',
'aliases': ['madison ave', 'mad ave'],
'description': 'Advertising and business district'
},
'park avenue': {
'name': 'Park Avenue',
'coords': [-73.9735, 40.7549],
'type': 'street',
'substation': 'Midtown East',
'aliases': ['park ave'],
'description': 'Prestigious avenue'
},
'lexington avenue': {
'name': 'Lexington Avenue',
'coords': [-73.9665, 40.7519],
'type': 'street',
'substation': 'Turtle Bay',
'aliases': ['lex ave', 'lexington ave'],
'description': 'Major north-south avenue'
},
# FAMOUS LANDMARKS & BUILDINGS
'empire state building': {
'name': 'Empire State Building',
'coords': [-73.9857, 40.7484],
'type': 'landmark',
'substation': 'Murray Hill',
'aliases': ['empire state', 'esb'],
'description': 'Iconic Art Deco skyscraper'
},
'chrysler building': {
'name': 'Chrysler Building',
'coords': [-73.9753, 40.7516],
'type': 'landmark',
'substation': 'Turtle Bay',
'aliases': ['chrysler'],
'description': 'Art Deco masterpiece'
},
'flatiron building': {
'name': 'Flatiron Building',
'coords': [-73.9897, 40.7411],
'type': 'landmark',
'substation': 'Chelsea',
'aliases': ['flatiron', 'flat iron'],
'description': 'Triangular-shaped historic building'
},
'madison square garden': {
'name': 'Madison Square Garden',
'coords': [-73.9934, 40.7505],
'type': 'venue',
'substation': 'Penn Station',
'aliases': ['msg', 'the garden'],
'description': 'Famous sports and entertainment arena'
},
# EV CHARGING STATIONS
'times square garage': {
'name': 'Times Square EV Garage',
'coords': [-73.9857, 40.7580],
'type': 'ev_station',
'substation': 'Times Square',
'aliases': ['times square ev', 'ts garage'],
'description': 'EV charging station with 20 ports'
},
'penn station hub': {
'name': 'Penn Station EV Hub',
'coords': [-73.9904, 40.7505],
'type': 'ev_station',
'substation': 'Penn Station',
'aliases': ['penn ev', 'penn hub'],
'description': 'EV charging hub with 20 ports'
},
'grand central charging': {
'name': 'Grand Central EV Charging',
'coords': [-73.9772, 40.7527],
'type': 'ev_station',
'substation': 'Grand Central',
'aliases': ['grand central ev', 'gc charging'],
'description': 'EV charging at Grand Central - 20 ports'
},
'bryant park station': {
'name': 'Bryant Park EV Station',
'coords': [-73.9832, 40.7536],
'type': 'ev_station',
'substation': 'Midtown East',
'aliases': ['bryant park ev', 'bp station'],
'description': 'EV charging at Bryant Park - 20 ports'
},
'columbus circle ev': {
'name': 'Columbus Circle EV',
'coords': [-73.9819, 40.7681],
'type': 'ev_station',
'substation': 'Hells Kitchen',
'aliases': ['columbus ev', 'cc ev'],
'description': 'EV charging at Columbus Circle - 20 ports'
},
'murray hill garage': {
'name': 'Murray Hill EV Garage',
'coords': [-73.9816, 40.7486],
'type': 'ev_station',
'substation': 'Murray Hill',
'aliases': ['murray hill ev', 'mh garage'],
'description': 'EV charging in Murray Hill - 20 ports'
},
'turtle bay charging': {
'name': 'Turtle Bay EV Charging',
'coords': [-73.9665, 40.7519],
'type': 'ev_station',
'substation': 'Turtle Bay',
'aliases': ['turtle bay ev', 'tb charging'],
'description': 'EV charging in Turtle Bay - 20 ports'
},
'midtown east station': {
'name': 'Midtown East EV Station',
'coords': [-73.9735, 40.7549],
'type': 'ev_station',
'substation': 'Midtown East',
'aliases': ['midtown east ev', 'me station'],
'description': 'EV charging in Midtown East - 20 ports'
},
# DISTRICTS & NEIGHBORHOODS
'garment district': {
'name': 'Garment District',
'coords': [-73.9897, 40.7548],
'type': 'district',
'substation': 'Hells Kitchen',
'aliases': ['garment', 'fashion district'],
'description': 'Fashion and textile industry center'
},
'koreatown': {
'name': 'Koreatown',
'coords': [-73.9882, 40.7486],
'type': 'district',
'substation': 'Murray Hill',
'aliases': ['k-town', 'korea town'],
'description': 'Korean cultural district'
},
'diamond district': {
'name': 'Diamond District',
'coords': [-73.9799, 40.7589],
'type': 'district',
'substation': 'Times Square',
'aliases': ['diamond', 'jewelry district'],
'description': 'Diamond and jewelry trading center'
},
# TRANSPORTATION HUBS
'port authority': {
'name': 'Port Authority Bus Terminal',
'coords': [-73.9902, 40.7570],
'type': 'transport',
'substation': 'Times Square',
'aliases': ['port authority', 'pabt', 'bus terminal'],
'description': 'Major bus terminal'
},
'subway stations': {
'name': 'NYC Subway Network',
'coords': [-73.9857, 40.7580],
'type': 'transport',
'substation': 'Times Square',
'aliases': ['subway', 'metro', 'mta'],
'description': 'NYC subway system'
},
# PARKS & OPEN SPACES
'bryant park': {
'name': 'Bryant Park',
'coords': [-73.9832, 40.7536],
'type': 'park',
'substation': 'Midtown East',
'aliases': ['bryant'],
'description': 'Popular midtown park'
},
'madison square park': {
'name': 'Madison Square Park',
'coords': [-73.9881, 40.7424],
'type': 'park',
'substation': 'Chelsea',
'aliases': ['madison square', 'mad sq park'],
'description': 'Historic park with Shake Shack'
},
'columbus circle': {
'name': 'Columbus Circle',
'coords': [-73.9819, 40.7681],
'type': 'landmark',
'substation': 'Hells Kitchen',
'aliases': ['columbus', 'cc'],
'description': 'Traffic circle and landmark'
},
# SHOPPING & ENTERTAINMENT
'herald square': {
'name': 'Herald Square',
'coords': [-73.9876, 40.7505],
'type': 'commercial',
'substation': 'Penn Station',
'aliases': ['herald', 'macys'],
'description': 'Shopping district with Macys flagship'
},
'lincoln center': {
'name': 'Lincoln Center',
'coords': [-73.9832, 40.7697],
'type': 'venue',
'substation': 'Hells Kitchen',
'aliases': ['lincoln', 'performing arts'],
'description': 'Performing arts complex'
},
# TRAFFIC & INFRASTRUCTURE
'traffic lights': {
'name': 'Traffic Light Network',
'coords': [-73.9857, 40.7580],
'type': 'infrastructure',
'substation': 'Times Square',
'aliases': ['traffic', 'lights', 'signals'],
'description': 'NYC traffic light system - 3,481 controlled lights'
},
'power grid': {
'name': 'Manhattan Power Grid',
'coords': [-73.9857, 40.7580],
'type': 'infrastructure',
'substation': 'Times Square',
'aliases': ['grid', 'power system', 'electrical grid'],
'description': 'Complete Manhattan electrical infrastructure'
}
}
# Initialize dynamic system state
self.system_state = {
'substations': {},
'failed_substations': [],
'v2g_enabled_substations': [],
'last_updated': None
}
print("[ULTRA CHATBOT] Initialized with MAXIMUM conversational intelligence!")
async def _update_system_state(self):
"""Update system state from backend APIs"""
try:
import requests
# Get current system status
system_response = requests.get("http://127.0.0.1:5000/api/status", timeout=5)
v2g_response = requests.get("http://127.0.0.1:5000/api/v2g/status", timeout=5)
if system_response.status_code == 200:
system_data = system_response.json()
substations = system_data.get('substations', {})
self.system_state['substations'] = substations
self.system_state['failed_substations'] = [
name for name, info in substations.items()
if info.get('status') == 'failed'
]
if v2g_response.status_code == 200:
v2g_data = v2g_response.json()
self.system_state['v2g_enabled_substations'] = v2g_data.get('enabled_substations', [])
self.system_state['last_updated'] = datetime.now()
print(f"[ULTRA CHATBOT] System updated: {len(self.system_state['failed_substations'])} failed substations, {len(self.system_state['v2g_enabled_substations'])} V2G enabled")
except Exception as e:
print(f"[ULTRA CHATBOT] Failed to update system state: {e}")
async def chat(self, user_input: str, user_id: str = 'web_user') -> Dict[str, Any]:
"""Ultra intelligent chat processing - understands everything like ChatGPT"""
print(f"[ULTRA CHATBOT] Processing: '{user_input}' from user: '{user_id}'")
# SPECIAL HANDLING: Skip greeting for system scenario completion messages
if user_id == 'system' and any(phrase in user_input.lower() for phrase in ['scenario just completed', 'scenario complete', 'acknowledge this restoration', 'acknowledge this dramatic scenario']):
print(f"[ULTRA CHATBOT] Detected scenario completion message from system - providing brief acknowledgment")
# Provide very brief acknowledgment without greeting
if 'v2g' in user_input.lower() and 'restored' in user_input.lower():
response_text = "✅ V2G scenario completed successfully!"
elif 'blackout' in user_input.lower() and 'crisis' in user_input.lower():
response_text = "🚨 Blackout scenario complete. System requires manual restoration."
else:
response_text = "✅ Scenario acknowledged."
return {
'success': True,
'text': response_text,
'scenario_acknowledgment': True,
'timestamp': datetime.now().isoformat()
}
# Update system state first to understand current situation
await self._update_system_state()
# Add to conversation history
self.conversation_history.append({"role": "user", "content": user_input})
# CRITICAL FIX: Handle numbered responses referring to previous suggestions
numbered_response = self._detect_numbered_response(user_input.strip())
if numbered_response:
print(f"[ULTRA CHATBOT] Detected numbered response: {numbered_response}")
return await self._handle_numbered_response(numbered_response)
# CRITICAL FIX: Handle confirmation responses
confirmation_response = self._detect_confirmation_response(user_input.strip())
if confirmation_response:
print(f"[ULTRA CHATBOT] Detected confirmation response: {confirmation_response}")
return await self._handle_confirmation_response(confirmation_response)
# Handle map control commands (zoom, camera, view)
map_command_response = self._handle_map_command(user_input.strip())
if map_command_response:
print(f"[ULTRA CHATBOT] Detected map command: {user_input.strip()}")
return map_command_response
try:
# ENHANCED INTELLIGENCE: First, understand what the user REALLY wants
understanding = await self._deep_understanding(user_input)
# If understanding is unclear, ask for clarification intelligently
if understanding['needs_clarification']:
return understanding['clarification_response']
# STEP 1: Intelligent typo correction and preprocessing
simple_commands = ['hi', 'hello', 'hey', 'greetings', 'status', 'help', 'v2g', 'yes', 'no', 'ok', 'cancel']
if user_input.lower().strip() in simple_commands or len(user_input.strip()) <= 3:
corrected_input = user_input # Don't autocorrect simple commands
corrections_made = []
else:
corrected_input, corrections_made = self._intelligent_typo_correction(user_input)
# STEP 2: Fuzzy command matching with context awareness
best_match, confidence = self._fuzzy_command_matching(corrected_input)
# ENHANCED: Handle greetings more naturally
if any(greeting in corrected_input.lower() for greeting in ['hi', 'hello', 'hey', 'greetings', 'good morning', 'good afternoon']):
greeting_text = """# 👋 Manhattan Power Grid AI
**I control** substations, time, temperature & scenarios via natural language.
**Quick Start:**
• `"turn off times square"` • `"set time to 8"` • `"morning rush"` • `"status"`
Type **`help`** for all commands | Just ask naturally! 🚀"""
return {
'original_input': user_input,
'corrected_input': corrected_input,
'corrections_made': corrections_made,
'best_match': None,
'confidence': 1.0,
'intent': 'greeting',
'success': True,
'text': greeting_text,
'suggestions': self._track_suggestions([
"help",
"set time for 8",
"morning rush",
"status"
]),
'timestamp': datetime.now().isoformat()
}
# ENHANCED: Subsection-based help system
# Check for general help command
if corrected_input.lower().strip() in ['help', 'commands', 'what can you do', 'show commands', 'list commands']:
help_menu = """# 📚 **Help Menu**
| Section | What It Does |
|---------|--------------|
| 🔌 **Grid** | Substations on/off |
| 🕐 **Time** | Set time (auto-spawns traffic) |
| 🌡️ **Temperature** | Adjust temp |
| 🎯 **Scenarios** | Pre-configured tests |
| 🗺️ **Navigation** | Find locations |
| ⚡ **V2G** | Emergency power |
| 📊 **Analysis** | System status |
| 💡 **Examples** | Quick workflows |
**Type:** `"help grid"`, `"help time"`, `"help scenarios"`, etc.
Or just ask naturally! 🚀"""
return {
'original_input': user_input,
'corrected_input': corrected_input,
'corrections_made': corrections_made,
'best_match': None,
'confidence': 1.0,
'intent': 'help_menu',
'success': True,
'text': help_menu,
'suggestions': self._track_suggestions([
"help grid",
"help scenarios",
"help time"
]),
'timestamp': datetime.now().isoformat()
}
# Handle section-specific help commands
help_section_result = self._handle_help_section(corrected_input, user_input, corrections_made)
if help_section_result:
return help_section_result
# STEP 3: Enhanced context understanding
intent, entities = self._understand_context_enhanced(corrected_input, understanding)
# STEP 4: Generate intelligent response with safety checks
response = await self._generate_ultra_intelligent_response_enhanced(
user_input, corrected_input, corrections_made,
best_match, confidence, intent, entities, understanding
)
# Add to conversation history
self.conversation_history.append({
"role": "assistant",
"content": response.get('text', 'Response generated')
})
return response
except Exception as e:
print(f"[ULTRA CHATBOT ERROR] {str(e)}")
return await self._fallback_intelligent_response(user_input, str(e))
async def _deep_understanding(self, user_input: str) -> Dict[str, Any]:
"""Deep contextual understanding - like ChatGPT"""
text_lower = user_input.lower().strip()
# Check for unclear/ambiguous inputs that need clarification
unclear_patterns = [
# Too vague
r'^(it|that|this|show|turn)$',
r'^(do|can|will|should)\s*(it|that|this)?\s*$',
r'^(what|where|how|when|why)\s*$',
# Incomplete commands
r'^(turn|show|activate|disable)\s*(me|it)?\s*$',
r'^(where|what)\s+is\s*$',
r'^(can|could|will|would)\s+you\s*$'
]
needs_clarification = any(re.match(pattern, text_lower) for pattern in unclear_patterns)
if needs_clarification:
# Generate intelligent clarification based on what they said
suggestions = []
if any(word in text_lower for word in ['turn', 'off', 'on', 'disable', 'activate']):
suggestions = [
"turn off times square substation",
"turn on penn station substation",
"activate v2g system",
"disable murray hill substation"
]
clarification = "I understand you want to control something. Could you be more specific? For example:"
elif any(word in text_lower for word in ['show', 'display', 'see', 'view']):
suggestions = [
"show power network of times square",
"show me central park location",
"display system status",
"show all substations"
]
clarification = "I understand you want to see something. What would you like me to show you? For example:"
elif any(word in text_lower for word in ['where', 'location', 'find']):
suggestions = [
"where is times square substation?",
"show me penn station location",
"find murray hill on map"
]
clarification = "I can help you find locations! What are you looking for? For example:"
else:
suggestions = [
"show power network of times square",
"turn off penn station substation",
"what's the system status?",
"where is central park?"
]
clarification = "I'd be happy to help! Could you be more specific about what you'd like me to do? Here are some examples:"
return {
'needs_clarification': True,
'clarification_response': {
'original_input': user_input,
'corrected_input': user_input,
'corrections_made': [],
'intent': 'clarification_needed',
'success': True,
'text': f"{clarification}",
'suggestions': self._track_suggestions(suggestions),
'timestamp': datetime.now().isoformat()
}
}
return {'needs_clarification': False}
def _handle_help_section(self, corrected_input: str, user_input: str, corrections_made: list) -> Optional[Dict[str, Any]]:
"""Handle section-specific help requests"""
lower_input = corrected_input.lower().strip()
# Define help sections with their content
help_sections = {
'grid': {
'title': '🔌 **Power Grid Control**',
'content': """**Commands:**
• `"turn off times square"` - Fail substation
• `"restore central park"` - Restore substation
• `"restore all"` - Turn everything back on
**Major Substations:** Times Square, Central Park, Penn Station, Murray Hill, Midtown East
Type `"help"` to return.""",
'suggestions': ["turn off times square", "restore all", "help"]
},
'time': {
'title': '🕐 **Time Control**',
'content': """**Commands:** `"set time to 8"`, `"set time for 18"`
**Traffic Auto-Spawns by Time:**
| Time | Vehicles | Time | Vehicles |
|------|----------|------|----------|
| 0-5 AM | 10-20 | 11-14 PM | 70-90 |
| 5-7 AM | 40-60 | 14-17 PM | 75-95 |
| 7-9 AM 🚗 | 85-100 | 17-19 PM 🚗 | 90-100 |
| 9-11 AM | 60-80 | 19-24 PM | 20-85 |
Type `"help"` to return.""",
'suggestions': ["set time to 8", "set time for 18", "help"]
},
'temperature': {
'title': '🌡️ **Temperature Control**',
'content': """**Commands:** `"set temperature to 98"`, `"temp 72"`
**Impact:** 60-75°F ❄️ Normal | 75-90°F ☀️ Warm | 90-105°F 🔥 Heatwave | 105-120°F ☢️ Crisis
Higher temps = more AC load.
Type `"help"` to return.""",
'suggestions': ["set temperature to 98", "set temp to 72", "help"]
},
'scenarios': {
'title': '🎯 **Test Scenarios**',
'content': """**Time/Weather Scenarios** (set time + temp + vehicles):
| Scenario | Time | Temp | Vehicles |
|----------|------|------|----------|
| 🌅 **morning rush** | 8 AM | 75°F | 100 |
| 🌆 **evening rush** | 6 PM | 80°F | 120 |
| ☀️ **normal day** | 12 PM | 72°F | 60 |
| 🔥 **heatwave crisis** | 3 PM | 98°F | 90 |
| ☢️ **catastrophic heat** | 2 PM | 115°F | 100 |
| 🌙 **late night** | 3 AM | 65°F | 15 |
**Emergency Scenarios** (different - test grid resilience):
• 🔌 **blackout scenario** - Fails multiple substations, tests emergency response
• ⚡ **v2g scenario** - Tests Vehicle-to-Grid emergency power restoration
**Why different?** Time scenarios control environment. Emergency scenarios test system failures.
Type `"help"` to return.""",
'suggestions': ["morning rush", "blackout scenario", "help"]
},
'navigation': {
'title': '🗺️ **Map Navigation**',
'content': """**Commands:**
• `"show me central park"` - Show location
• `"zoom to times square"` - Focus area
• `"where is penn station"` - Find place
**Locations:** Central Park, Times Square, Penn Station, Rockefeller Center, Broadway, Empire State
Type `"help"` to return.""",
'suggestions': ["show me central park", "zoom to times square", "help"]
},
'v2g': {
'title': '⚡ **V2G Emergency System**',
'content': """Emergency power from EVs with ≥70% battery.
**Commands:**
• `"activate v2g rescue"` - Start emergency response
• `"v2g status"` - Check capacity
Auto-suggested during blackouts.
Type `"help"` to return.""",
'suggestions': ["activate v2g rescue", "v2g status", "help"]
},
'analysis': {
'title': '📊 **System Analysis**',
'content': """**Commands:**
• `"status"` - Full system status
• `"analyze grid"` - Grid performance
• `"show substation status"` - Substation info
**Shows:** Substations, traffic lights, vehicles, EVs, charging, power load (MW), health
Type `"help"` to return.""",
'suggestions': ["status", "analyze grid", "help"]
},
'examples': {
'title': '💡 **Quick Workflows**',
'content': """**Morning Test:** `set time for 8` → `status`
**Heatwave:** `set temperature to 115` → `catastrophic heat`
**Emergency:** `turn off times square` → `activate v2g rescue`
**Navigation:** `show me central park` → `zoom to times square`
**Natural language works:** `"Show me what's happening at times square"` ✓
Type `"help"` to return.""",
'suggestions': ["morning rush", "status", "help"]
}
}
# Check if input matches any help section
for section_key, section_data in help_sections.items():
# Match patterns like "help grid", "help time control", "grid help", etc.
if (f'help {section_key}' in lower_input or
f'{section_key} help' in lower_input or
(section_key in lower_input and 'help' in lower_input)):
return {
'original_input': user_input,
'corrected_input': corrected_input,
'corrections_made': corrections_made,
'best_match': None,
'confidence': 1.0,
'intent': f'help_{section_key}',
'success': True,
'text': f"{section_data['title']}\n\n{section_data['content']}",
'suggestions': self._track_suggestions(section_data['suggestions']),
'timestamp': datetime.now().isoformat()
}
return None
def _understand_context_enhanced(self, text: str, understanding: Dict[str, Any]) -> Tuple[str, Dict[str, Any]]:
"""Enhanced context understanding with better natural language processing"""
# Use the existing context understanding but enhance it
original_intent, original_entities = self._understand_context(text)
# Enhanced entity extraction for natural language
text_lower = text.lower()
enhanced_entities = original_entities.copy()
# Better location extraction
location_patterns = [
r'(?:show|find|where|locate).*?(?:me\s+)?([\w\s]+?)(?:\s+(?:on|in|at|substation|location|map))?$',
r'(?:power\s+network\s+of|grid\s+of|network\s+for)\s+([\w\s]+?)(?:\s+substation)?$',
r'([\w\s]+?)\s+(?:substation|location|area|place)(?:\s+on\s+map)?$'
]
for pattern in location_patterns:
match = re.search(pattern, text_lower)
if match and 'location_data' not in enhanced_entities:
location = match.group(1).strip()