File size: 37,124 Bytes
770f5f7
 
169dbe5
402fdca
839c46d
 
 
 
 
 
 
 
 
560c73e
 
 
 
1a61bb7
 
1a4edd5
 
 
b678600
1a4edd5
839c46d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a4edd5
 
839c46d
 
 
4c6a845
839c46d
 
 
 
 
169dbe5
 
1a61bb7
 
 
 
 
 
 
4c6a845
 
 
1a61bb7
62eeda6
 
 
 
 
 
 
997c7aa
aec34f1
 
997c7aa
292372c
3fe3655
292372c
b678600
8416c88
402fdca
 
 
 
 
 
997c7aa
 
402fdca
 
 
 
 
 
997c7aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
402fdca
997c7aa
402fdca
997c7aa
402fdca
 
 
 
997c7aa
 
402fdca
 
62eeda6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdfde99
 
 
 
 
 
 
 
 
 
 
 
 
62eeda6
bdfde99
 
 
 
62eeda6
 
 
 
 
 
 
 
 
 
 
 
 
bdfde99
 
1a4edd5
 
62eeda6
bdfde99
292372c
 
 
62eeda6
 
292372c
 
bdfde99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a4edd5
 
 
 
 
1a61bb7
169dbe5
 
 
1a61bb7
 
 
169dbe5
 
4c6a845
169dbe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a61bb7
839c46d
 
 
 
 
 
 
 
c152ad6
8097a9d
930c640
 
 
 
839c46d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c152ad6
8097a9d
c152ad6
 
 
 
 
 
 
 
 
 
 
8097a9d
 
 
 
 
 
 
c152ad6
 
 
 
 
 
8097a9d
 
839c46d
 
 
62faa72
 
 
 
 
 
e5dc535
62eeda6
839c46d
 
 
 
 
169dbe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
839c46d
62eeda6
3a2eaed
839c46d
 
997c7aa
 
62eeda6
839c46d
 
 
 
997c7aa
839c46d
 
62eeda6
839c46d
5511924
839c46d
 
 
5511924
 
62eeda6
839c46d
f699477
 
62eeda6
997c7aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a4edd5
 
62eeda6
839c46d
1a61bb7
 
7d40ba4
1a61bb7
 
7d40ba4
1a61bb7
 
839c46d
3a2eaed
169dbe5
 
1a61bb7
 
4c6a845
839c46d
3a2eaed
62faa72
0fb4a4f
62faa72
3a2eaed
62faa72
62eeda6
169dbe5
1a61bb7
169dbe5
 
 
997c7aa
839c46d
997c7aa
839c46d
 
 
 
 
 
 
 
 
3a2eaed
839c46d
 
 
 
 
 
 
 
e5dc535
839c46d
62eeda6
839c46d
 
 
 
 
c152ad6
 
 
 
839c46d
 
 
 
 
 
 
 
 
 
 
4c6a845
839c46d
 
 
 
 
 
 
 
 
 
4c6a845
839c46d
 
 
 
 
bad15d2
 
 
 
 
839c46d
 
 
 
 
 
 
 
 
 
 
 
 
4c6a845
839c46d
 
 
 
 
 
 
 
 
5511924
 
 
 
 
839c46d
5511924
 
839c46d
 
5511924
 
839c46d
 
 
 
 
 
560c73e
 
 
 
839c46d
 
 
 
 
 
 
f699477
839c46d
 
 
f699477
839c46d
 
 
 
 
f699477
 
 
cd53d09
560c73e
 
 
 
a509fbe
 
 
560c73e
0ac5c98
b34c7b3
a509fbe
 
 
 
 
560c73e
a509fbe
 
62faa72
 
 
4411fd0
 
 
62faa72
560c73e
62faa72
 
 
c152ad6
8097a9d
ead2b78
8097a9d
 
560c73e
 
b34c7b3
560c73e
 
b34c7b3
 
560c73e
c152ad6
997c7aa
7d40ba4
 
 
 
 
 
 
 
 
c152ad6
7d40ba4
 
 
 
 
 
62faa72
 
 
 
7d40ba4
62faa72
5511924
 
 
 
62faa72
 
5511924
c152ad6
 
 
 
b34c7b3
 
 
 
997c7aa
c152ad6
62faa72
 
 
 
 
 
 
 
5511924
62faa72
 
 
 
 
 
 
5511924
62faa72
 
0fb4a4f
62faa72
 
 
 
 
 
 
 
4c6a845
62faa72
 
 
 
 
 
0fb4a4f
62faa72
 
 
 
 
2f3fad7
62faa72
 
 
 
 
b56832d
62faa72
 
 
c152ad6
cd53d09
b34c7b3
839c46d
 
 
 
 
 
62faa72
839c46d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b34c7b3
 
 
 
 
839c46d
 
bad15d2
839c46d
 
 
 
1a61bb7
839c46d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c6a845
839c46d
 
 
 
 
 
 
 
 
 
1ed2e33
 
 
4c6a845
1ed2e33
 
 
 
839c46d
 
 
 
c152ad6
839c46d
 
 
 
 
c152ad6
839c46d
 
 
 
 
 
 
 
560c73e
5511924
839c46d
bad15d2
839c46d
bad15d2
 
62faa72
 
 
 
 
62eeda6
 
4c6a845
 
62eeda6
62faa72
62eeda6
839c46d
 
 
 
 
 
 
bad15d2
560c73e
 
c152ad6
62faa72
 
839c46d
6c56d96
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
import os
import gradio as gr
import openai
from numpy._core.defchararray import endswith, isdecimal, startswith
from openai import OpenAI
from dotenv import load_dotenv
from pathlib import Path
from time import sleep
import audioread
import queue
import threading
from glob import glob
import copy
import base64
import json
from PIL import Image
from io import BytesIO
from pydantic import BaseModel
import pprint
import pandas as pd
import yfinance as yf
from datetime import datetime, timedelta
import pytz


load_dotenv(override=True)
key = os.getenv('OPENAI_API_KEY')
users = os.getenv('LOGNAME')
unames = users.split(',')
pwds = os.getenv('PASSWORD')
pwdList = pwds.split(',')

site = os.getenv('SITE')
if site == 'local':
    dp = Path('./data')
    dp.mkdir(exist_ok=True)
    dataDir = './data/'
else:
    dp = Path('/data')
    dp.mkdir(exist_ok=True)
    dataDir = '/data/'
stock_data_path = dataDir + 'Stocks.txt'


speak_file = dataDir + "speek.wav"

# client = OpenAI(api_key = key)

#digits = ['zero: ','one: ','two: ','three: ','four: ','five: ','six: ','seven: ','eight: ','nine: ']

abbrevs = {'St. ' : 'Saint ', 'Mr. ': 'mister ', 'Mrs. ':'mussus ', 'Mr. ':'mister ', 'Ms. ':'mizz '}

special_chat_types = ['math', 'logic']

class Step(BaseModel):
    explanation: str
    output: str

class MathReasoning(BaseModel):
    steps: list[Step]
    final_answer: str

def Client():
    return OpenAI(api_key = key)

def test_plot_df():
    data = {
        "month": ['2024-01','2024-02','2024-03'],
        "value": [22.4, 30.1, 25.6]
        }
    return pd.DataFrame(data)

def md(txt):
    return str(txt).replace('```', ' ').replace('  ', '&nbsp;&nbsp;').replace('  ', '&nbsp;&nbsp;').replace('  ', '&nbsp;&nbsp;').replace('\n','<br>')
    # return txt

def etz_now():
    eastern = pytz.timezone('US/Eastern')
    ltime = datetime.now(eastern)
    return ltime

def date_from_utime(utime):
    ts = int(utime)
    dt = datetime.utcfromtimestamp(ts)
    eastern = pytz.timezone('US/Eastern')
    return dt.astimezone(eastern).strftime('%Y-%m-%d')

def stock_list():
    rv = ''
    with open(stock_data_path, 'rt') as fp:
        lines = fp.readlines()
        for line in lines:
            (name, symbol, shares) = line.rstrip().split(',')
            name = name.strip()
            symbol = symbol.strip()
            rv += f'{symbol}  {name}\n'
    return rv

def get_stock_news(search_symbol):
    name_list = []
    fuzzy = True
    with open(stock_data_path, 'rt') as fp:
        lines = fp.readlines()
        for line in lines:
            (name, symbol, shares) = line.rstrip().split(',')
            name = name.strip()
            name_list.append(name)
    search_term = search_symbol.strip().upper()
    if search_symbol in name_list:
        fuzzy = False
    try:
        news = yf.Search(search_term, news_count=5, enable_fuzzy_query=fuzzy).news
    except:
        return f'No results for search term {search_term}, check spelling'
    rv = ''
    for item in news:
        rv += f'Title: {item["title"]}\n'
        rv += f'Publisher: {item["publisher"]}\n'
        rv += f'Date published: {date_from_utime(item["providerPublishTime"])}\n'
        rv += f'Link: [URL]({item["link"]})\n\n'
    return rv

def stock_history_df(num_weeks):
    values = []
    dates = []
    xmax = 0
    for offset in range(num_weeks+1):
        (value, date) = get_stock_report(False, offset)
        date = date[5:]
        values.append(value)
        dates.append(date)
        if float(value) > xmax:
            xmax = float(value)
    values.reverse()
    dates.reverse()
    data = {
        "date": dates,
        "value" : values
        }
    return (pd.DataFrame(data), f'{int(xmax + 10000)}')

def get_stock_report(verbose = True, offset = 0):
    try:
        stock_data = {}
        global stock_data_path
        error_msg = ''
        with open(stock_data_path, 'rt') as fp:
            lines = fp.readlines()
        for line in lines:
            (name, symbol, shares) = line.rstrip().split(',')
            name = name.strip()
            symbol = symbol.strip()
            shares = shares.strip()
            stock_data[symbol] = {"symbol": symbol, "name": name, "shares": shares, "closing": '0'}
        for symbol in stock_data.keys():
            (closing_price, closing_date) = get_last_closing(symbol, offset)
            if closing_price == 0:
                error_msg += f'Error getting closing for {symbol}\n'
            stock_data[symbol]['closing'] = f'{closing_price:.2f}'
        total_value = 0.0
        if verbose:
            rv = f'At closing on {closing_date}:\n'
            for item in stock_data.values():
                rv += str(item) + '\n'
                total_value += float(item['closing']) * float(item['shares'])
            rv += (f'\nTotal value = {total_value:.2f}\n')
            if len(error_msg) > 0:
                rv += error_msg
            rv += f'Eastern time is: {etz_now()}'
        else:
            for item in stock_data.values():
                total_value += float(item['closing']) * float(item['shares'])
            return (total_value, closing_date)
    except:
        rv = 'Error getting stock report'
    return rv

def get_last_closing(symbol, offset=0, timeout=10):
    try:
        etime = etz_now()
        if etime.hour >= 16:
            etime = etime + timedelta(days=1)
        if offset > 0:
            etime = etime - timedelta(weeks=offset)
        five_days_ago = etime - timedelta(days=6)
        end = etime.strftime('%Y-%m-%d')
        start = five_days_ago.strftime('%Y-%m-%d')
        df = yf.download(symbol,
                        start = start,
                        end = end,
                        progress = False,
                        timeout=timeout,
                        )
        # print(df)
        closing_date = 'unknown'
        data_top = df.tail(1)
        for row in data_top.index:
            closing_date = row.strftime('%Y-%m-%d')
            # print(closing_date)
        return (df.iat[-1,1], closing_date)
    except:
        return (0.0, "0000-00-00")

def create_stock_data_file(txt):
    with open(stock_data_path, 'wt') as fp:
        fp.write(txt)

def solve(prompt, chatType):
    tokens_in = 0
    tokens_out = 0
    tokens = 0
    if chatType == 'math':
        instruction = "You are a helpful math tutor. Guide the user through the solution step by step."
    elif chatType == "logic":
        instruction = "you are an expert in logic and reasoning.  Guide the user through the solution step by step"
    try:
        completion = Client().beta.chat.completions.parse(
            model = 'gpt-4o-2024-08-06',
            messages = [
                {"role": "system", "content": instruction},
                {"role": "user", "content": prompt}
            ],
            response_format=MathReasoning,
            max_tokens = 2000
        )

        tokens_in = completion.usage.prompt_tokens
        tokens_out = completion.usage.completion_tokens
        tokens = completion.usage.total_tokens
        msg = completion.choices[0].message 
        if msg.parsed:
            dr = msg.parsed.model_dump()
            response = pprint.pformat(dr)
        elif msg.refusal:
            response = msg.refusal

    except Exception as e:
        if type(e) == openai.LengthFinishReasonError:
            response = 'Too many tokens' 
        else:
            response = str(e)
    return (response, tokens_in, tokens_out, tokens)

def genUsageStats(do_reset=False):
    result = []
    ttotal4o_in = 0
    ttotal4o_out = 0
    ttotal4mini_in = 0
    ttotal4mini_out = 0
    totalAudio = 0
    totalSpeech = 0
    totalImages = 0
    totalHdImages = 0
    if do_reset:
        dudPath = dataDir + '_speech.txt'
        if os.path.exists(dudPath):
            os.remove(dudPath)
    for user in unames:
        tokens4o_in = 0
        tokens4o_out = 0
        tokens4mini_in = 0
        tokens4mini_out = 0
        fp = dataDir + user + '_log.txt'
        if os.path.exists(fp):
            accessOk = False
            for i in range(3):
                try:
                    with open(fp) as f:
                        dataList = f.readlines()
                    if do_reset:
                        os.remove(fp)
                    else:
                        for line in dataList:
                            (u, t) = line.split(':')
                            (t, m) = t.split('-')
                            (tin, tout) = t.split('/')
                            incount = int(tin)
                            outcount = int(tout)
                            if 'mini' in m:
                                tokens4mini_in += incount
                                tokens4mini_out += outcount
                                ttotal4mini_in += incount
                                ttotal4mini_out += outcount
                            else:
                                tokens4o_in += incount
                                tokens4o_out += outcount
                                ttotal4o_in += incount
                                ttotal4o_out += outcount
                    accessOk = True
                    break
                except:
                    sleep(3)
            if not accessOk:
                return f'File access failed reading stats for user: {user}'
        userAudio = 0
        fp = dataDir + user + '_audio.txt'
        if os.path.exists(fp):
            accessOk = False
            for i in range(3):
                try:
                    with open(fp) as f:
                        dataList = f.readlines()
                    if do_reset:
                        os.remove(fp)
                    else:
                        for line in dataList:
                            (dud, len) = line.split(':')
                            userAudio += int(len)
                        totalAudio += int(userAudio)
                    accessOk = True
                    break
                except:
                    sleep(3)
            if not accessOk:
                return f'File access failed reading audio stats for user: {user}'
        userSpeech = 0
        fp = dataDir + user + '_speech.txt'
        if os.path.exists(fp):
            accessOk = False
            for i in range(3):
                try:
                    with open(fp) as f:
                        dataList = f.readlines()
                    if do_reset:
                        os.remove(fp)
                    else:
                        for line in dataList:
                            (dud, len) = line.split(':')
                            userSpeech += int(len)
                        totalSpeech += int(userSpeech)
                    accessOk = True
                    break
                except:
                    sleep(3)
            if not accessOk:
                return f'File access failed reading speech stats for user: {user}'
        user_images = 0
        user_hd_images = 0
        fp = image_count_path(user)
        if os.path.exists(fp):
            accessOk = False
            for i in range(3):
                try:
                    with open(fp) as f:
                        dataList = f.readlines()
                    if do_reset:
                        os.remove(fp)
                    else:
                        for line in dataList:
                            x = line.strip()
                            if x == 'hd':
                                user_hd_images += 1
                                totalHdImages += 1
                            else:
                                user_images += 1
                                totalImages += 1
                    accessOk = True
                    break
                except:
                    sleep(3)
            if not accessOk:
                return f'File access failed reading image gen stats for user: {user}'
        result.append([user, f'{tokens4mini_in}/{tokens4mini_out}', f'{tokens4o_in}/{tokens4o_out}', f'audio:{userAudio}',f'speech:{userSpeech}', f'images:{user_images}/{user_hd_images}'])
    result.append(['totals', f'{ttotal4mini_in}/{ttotal4mini_out}', f'{ttotal4o_in}/{ttotal4o_out}', f'audio:{totalAudio}',f'speech:{totalSpeech}', f'images:{totalImages}/{totalHdImages}'])
    return result       

def new_conversation(user):
    clean_up(user)  # .wav files
    flist = glob(f'{dataDir}{user}.png')
    flist.extend(glob(f'{dataDir}{user}_image.b64'))
    for fpath in flist:
        if os.path.exists(fpath):
            os.remove(fpath)
    return [None, [], gr.Markdown(value='', label='Dialog', container=True), gr.Image(visible=False, value=None),  gr.Image(visible=False, value=None), '',
            gr.LinePlot(visible=False)]

def updatePassword(txt):
    password = txt.lower().strip()
    return [password, "*********"]

# def parse_math(txt):
#     ref = 0
#     loc = txt.find(r'\(')
#     if loc == -1:
#         return txt
#     while (True):
#         loc2 = txt[ref:].find(r'\)')
#         if loc2 == -1:
#             break
#         loc = txt[ref:].find(r'\(')
#         if loc > -1:
#             loc2 += 2
#             slice = txt[ref:][loc:loc2]
#             frag = lconv.convert(slice)
#             txt = txt[:loc+ref] + frag + txt[loc2+ref:]
#             ref = len(txt[ref:loc]) + len(frag)
#     return txt

def chat(prompt, user_window, pwd_window, past, response, gptModel, uploaded_image_file='', plot=None):
    image_gen_model = 'gpt-4o-2024-08-06'
    user_window = user_window.lower().strip()
    isBoss = False
    if not response:
        response = ''
    plot = gr.LinePlot(visible=False)
    if user_window == unames[0] and pwd_window == pwdList[0]:
        isBoss = True
        if prompt == 'stats':
            response = genUsageStats()
            return [past, md(response), None, gptModel, uploaded_image_file, plot]
        if prompt == 'reset':
            response = genUsageStats(True)
            return [past, response, None, gptModel, uploaded_image_file, plot]
        if prompt.startswith('gpt4'):
            gptModel = 'gpt-4o-2024-08-06'
            prompt = prompt[5:]
        if prompt.startswith("clean"):
            user = prompt[6:]
            response = f'cleaned all .wav and .b64 files for {user}'
            final_clean_up(user, True)
            return [past, response, None, gptModel, uploaded_image_file, plot]
        if prompt.startswith('files'):
            (log_cnt, wav_cnt, other_cnt, others, log_list) = list_permanent_files()
            response = f'{log_cnt} log files\n{wav_cnt} .wav files\n{other_cnt} Other files:\n{others}\nlogs: {str(log_list)}'
            return [past, response, None, gptModel, uploaded_image_file, plot]
        if prompt.startswith('stock'):
            args = prompt.split(' ')
            num = len(args)
            if num == 1:
                response = stock_list()
                return [past, md(response), None, gptModel, uploaded_image_file, plot]
            elif num == 2:
                response = get_stock_report()
                if args[1] == 'value':
                    return [past, md(response), None, gptModel, uploaded_image_file, plot]
                elif args[1] == 'history':
                    (plot_df, ymax) = stock_history_df(12)
                    # ymax = float(ymax)
                    return [past, md(response), None, gptModel, uploaded_image_file,
                           gr.LinePlot(plot_df, x="date", y="value", visible=True,
                                      y_lim=[500000, 700000], label="Portfolio Value History")]
            elif num >= 3:
                if args[1] == 'news':
                    symbol = ' '.join(args[2:])
                    response = get_stock_news(symbol)
                    return [past, md(response), None, gptModel, uploaded_image_file, plot]
                # elif arg[1] == 'history':
                #     symbol = arg[2]
                #     response = 'ok' # get_


        # if prompt.startswith('stock values'):
        #     response = get_stock_report()
        #     if 'history' in prompt:
        #         (plot_df, ymax) = stock_history_df(12)
        #         ymax = float(ymax)
        #         return [past, response, None, gptModel, uploaded_image_file,
        #                gr.LinePlot(plot_df, x="date", y="value", visible=True,
        #                           y_lim=[500000, 700000], label="Portfolio Value History")]
        #     else:
        #         return [past, response, None, gptModel, uploaded_image_file, plot]
        # if prompt.startswith('stock news'):
        #         symbol = prompt[11:]
        #         response = get_stock_news(symbol)
        #         return [past, response, None, gptModel, uploaded_image_file, plot]
        if prompt.startswith('stockload'):
            create_stock_data_file(prompt[9:].lstrip())
            return [past, 'Stock data file created', None, gptModel, uploaded_image_file, plot]
    if user_window in unames and pwd_window == pwdList[unames.index(user_window)]:
        chatType = 'normal'
        prompt = prompt.strip()
        if prompt.lower().startswith('solve'):
            prompt = 'How do I solve ' + prompt[5:] + ' Do not use Latex for math expressions.'
            chatType = 'math'
        elif prompt.lower().startswith('puzzle'):
            chatType = 'logic'
            prompt = prompt[6:]
        past.append({"role":"user", "content":prompt})
        gen_image = (uploaded_image_file != '')
        if chatType in special_chat_types:
           (reply, tokens_in, tokens_out, tokens) = solve(prompt, chatType)
           reporting_model = image_gen_model
        elif not gen_image:
            completion = Client().chat.completions.create(model=gptModel,
                                            messages=past)
            reporting_model = gptModel
        else:
            (completion, msg) = analyze_image(user_window, image_gen_model, prompt)
            uploaded_image_file= ''
            reporting_model = image_gen_model
            if not msg == 'ok':
                return [past, msg, None, gptModel, uploaded_image_file, plot]
        if not chatType in special_chat_types:
            reply = completion.choices[0].message.content
            tokens_in = completion.usage.prompt_tokens
            tokens_out = completion.usage.completion_tokens
            tokens = completion.usage.total_tokens
        response += md("\n\nYOU: " + prompt + "\nGPT: " + reply)
        if isBoss:
            response += md(f"\n{reporting_model}: tokens in/out = {tokens_in}/{tokens_out}")
        if tokens > 40000:
            response += "\n\nTHIS DIALOG IS GETTING TOO LONG. PLEASE RESTART CONVERSATION SOON."
        past.append({"role":"assistant", "content": reply})
        accessOk = False
        for i in range(3):
            try:
                dataFile = new_func(user_window)
                with open(dataFile, 'a') as f:
                    m = '4o'
                    if 'mini' in reporting_model:
                        m = '4omini'
                    f.write(f'{user_window}:{tokens_in}/{tokens_out}-{m}\n')
                accessOk = True
                break
            except Exception as e:
                sleep(3)
        if not accessOk:
            response += f"\nDATA LOG FAILED, path = {dataFile}"
        return [past, response , None, gptModel, uploaded_image_file, plot]
    else:
        return [[], "User name and/or password are incorrect", prompt, gptModel, uploaded_image_file, plot]

def new_func(user):
    dataFile = dataDir + user + '_log.txt'
    return dataFile

def image_count_path(user):
    fpath = dataDir + user + '_image_count.txt'
    return fpath

def transcribe(user, pwd, fpath):
    user = user.lower().strip()
    pwd = pwd.lower().strip()
    if not (user in unames and pwd in pwdList):
        return 'Bad credentials'
    with audioread.audio_open(fpath) as audio:
        duration = int(audio.duration)
        if duration > 0:
            with open(dataDir + user + '_audio.txt','a') as f:
                f.write(f'audio:{str(duration)}\n')
    with open(fpath,'rb') as audio_file:
        transcript = Client().audio.transcriptions.create(
            model='whisper-1', file = audio_file ,response_format = 'text' )
    reply = transcript
    return str(reply)

def pause_message():
    return "Audio input is paused.  Resume or Stop as desired"

# def gen_output_audio(txt):
#     if len(txt) < 10:
#         txt = "This dialog is too short to mess with!"
#     response = Client().audio.speech.create(model="tts-1", voice="fable", input=txt)
#     with open(speak_file, 'wb') as fp:
#         fp.write(response.content)
#     return speak_file


# def set_speak_button(txt):
#     vis = False
#     if txt and len(txt) > 2:
#         vis = True
#     return gr.Button(visible=vis)

def update_user(user_win):
    user_win = user_win.lower().strip()
    user = 'unknown'
    for s in unames:
        if user_win == s:
            user = s
            break
    return [user, user]

def speech_worker(chunks=[],q=[]):
    for chunk in chunks:
        fpath = q.pop(0)
        response = Client().audio.speech.create(model="tts-1", voice="fable", input=chunk, speed=0.85, response_format='wav')
        with open(fpath, 'wb') as fp:
            fp.write(response.content)

def gen_speech_file_names(user, cnt):
    rv = []
    for i in range(0, cnt):
        rv.append(dataDir + f'{user}_speech{i}.wav')
    return rv

def final_clean_up(user, do_b64 = False):
    user = user.strip().lower()
    if user == 'kill':
        flist = glob(dataDir + '*')
    elif user == 'all':
        flist = glob(dataDir + '*_speech*.wav')
        if do_b64:
            flist.extend(glob(dataDir + '*.b64'))
    else:
        flist = glob(dataDir + f'{user}_speech*.wav')
        if do_b64:
            flist.append(dataDir + user + '_image.b64')
    for fpath in flist:
        try:
            os.remove(fpath)
        except:
            continue

def delete_image(user):
    fpath = dataDir + user + '.png'
    if os.path.exists(fpath):
        os.remove(fpath)

def list_permanent_files():
    flist = os.listdir(dataDir)
    others = []
    log_cnt = 0
    wav_cnt = 0
    other_cnt = 0
    list_logs = []
    for fpath in flist:
        if fpath.endswith('.txt'):
            log_cnt += 1
            list_logs.append(fpath)
        elif fpath.endswith('.wav'):
            wav_cnt += 1
        else:
            others.append(fpath)
    other_cnt = len(others)
    if log_cnt > 5:
        list_logs = []
    return (str(log_cnt), str(wav_cnt), str(other_cnt), str(others), list_logs)

def make_image(prompt, user, pwd):
    user = user.lower().strip()
    msg = 'Error: unable to create image.'
    fpath = None
    model = 'dall-e-2'
    size = '512x512'
    quality = 'standard'
    if user in unames and pwd == pwdList[unames.index(user)]:
        if len(prompt.strip()) == 0:
            return [gr.Image(value=None, visible=False), 'You must provide a prompt describing image you desire']
        if prompt.startswith('hd '):
            prompt = prompt[3:]
            model = 'dall-e-3'
            size = '1024x1024'
            quality = 'hd'
        try:
            response = Client().images.generate(model=model, prompt=prompt,size=size,
               quality=quality, response_format='b64_json')
        except Exception as ex:
            msg = ex.message
            return [gr.Image(visible=False, value=None), msg]
        if len(response.data) == 0:
            msg = "OpenAI returned no image data"
            return [gr.Image(visible=False, value=None), msg]
        try:
            image_data = response.data[0].b64_json 
            with Image.open(BytesIO(base64.b64decode(image_data))) as image:
                fpath = dataDir + user + '.png'
                image.save(fpath)
            with open(image_count_path(user), 'at') as fp:
                if quality == 'hd':
                    fp.write('hd\n')
                else:
                    fp.write('1\n')
            msg = 'Image created!'
        except:
            return [gr.Image(visible=False, value=None), msg]
    else:
        msg = 'Incorrect user name or password'
        return [gr.Image(visible=False, value=None), msg]
    return [gr.Image(visible=True, value=fpath), msg]

def show_help():
    txt = '''
    1.  Gemeral:
        1.1 Login with user name and password (not case-sensitive)
        1.2 Type prompts (questions, instructions) into "Prompt or Question" window (OR) you can speak prompts by
           tapping the audio "Record" button, saying your prompt, then tapping the "Stop" button.
           Your prompt will appear in the Prompt window, and you can edit it there if needed.
        1.3 Text in the "Dialog" window can be spoken by tapping the "Speak Dialog" button.
    2.  Chat:
        2.1 Enter prompt and tap the "Submit Prompt/Question" button.  The responses appear in the Dialog window.
        2.2 Enter follow-up questions in the Prompt window either by typing or speaking. Tap the voice
              entry "Reset Voice Entry" button to enable additional voice entry. Then tap "Submit Prompt/Question".
        2.3 If topic changes or when done chatting, tap the "Restart Conversation" button.
    3.  Solve math equations or logic problems providing step-by-step analysis:
        3.1 Math:  Make "solve" the first word in your prompt, followed by the equation, e.g., x^2 - x + 1 = 0
        3.2 Logic: Make "puzzle" the first word in your prompt, followed by a detailed description of a logic
           problem with the answer(s) you desire.
    4.  Make Image:
          4.1 Enter description of desired image in prompt window via either typing or voice entry
          4.2 Tap the "Make Image" button.  This can take a few seconds.
          4.3 There is a download button on the image display if your system supports file downloads.
          4.4 When done viewing image, tap the "Restart Conversation" button
    5.  Analyze an Image you provide:
          5.1 Enter what you want to know about the image in the prompt window. You can include instructions
               to write a poem about something in the image, for example.  Or just say "what's in this image?"
          5.2 Tap the "Upload Image to Analyze" button.
          5.3 An empty image box will appear lower left. Drag or upload image into it. It offers web cam or camera
               input also.
          5.4 The image should appear. This can take some time with a slow internet connection and large image.
          5.5 Tap the "Submit Prompt/Question" button to start the analysis.  This initiates a chat dialog and
               you can ask follow-up questions. However, the image is not re-analyzed for follow-up dialog.
    Hints:
        1. Better chat and image results are obtained by including detailed descriptions and instructions
            in the prompt.
        2. Always tap "Restart Conversation" before requesting an image or changing chat topics.
        3. Audio input and output functions depend on the hardware capability of your device.
        4. "Speak Dialog" will voice whatever is currently in the Dialog window.  You can repeat it and you
             can edit what's to be spoken.  Except:  In a chat conversation, spoken dialog will only include
             the latest prompt/response ("YOU:/GPT:") sequence.'''
    return md(txt)

def upload_image(prompt, user, password):
    if not (user in unames and password == pwdList[unames.index(user)]):
        return [gr.Image(visible=False, interactive=True), "Incorrect user name and/or password"]
    if len(prompt) < 3:
        return [gr.Image(visible=False, interactive=True), "You must provide prompt/instructions (what to do with the image)"]
    return [gr.Image(visible=True, interactive=True), '']

def load_image(image, user):
    status = 'OK, image is ready! Tap "Submit Prompt/Question" to start analyzing'
    try:
        with open(image, 'rb') as image_file:
            base64_image = base64.b64encode(image_file.read()).decode('utf-8')
        fpath = dataDir + user + '_image.b64'
        with open(fpath, 'wt') as fp:
            fp.write(base64_image)
    except:
        status = 'Unable to upload image'
    return [fpath, status]

def analyze_image(user, model, prompt):
    status = 'ok'
    try:
        with open(dataDir + user + '_image.b64', 'rt') as fp:
            base64_image = fp.read()
    except:
        status = "base64 image file not found"
        return [None, status]

    completion = Client().chat.completions.create(
        model=model,
        messages=[
            { "role": "user",
               "content": [
                   {
                       "type": "text",
                       "text": prompt
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": f"data:image/jpeg;base64,{base64_image}",
                            "detail": "high"
                            }
                    }
                   ]
               }
            ],
        max_tokens= 500
    )
    # response = completion.choices[0].message.content
    return [completion, status]


with gr.Blocks(theme=gr.themes.Soft()) as demo:
    history = gr.State([])
    password = gr.State("")
    user = gr.State("unknown")
    model = gr.State("gpt-4o-mini")
    q = gr.State([])
    qsave = gr.State([])
    uploaded_image_file = gr.State('')

    def clean_up(user):
        flist = glob(dataDir + f'{user}_speech*.wav')
        for fpath in flist:
            try:
                os.remove(fpath)
            except:
                continue

    def initial_audio_output(txt, user):
        global digits
        global abbrevs
        if not user in unames:
            return [gr.Audio(sources=None), []]
        clean_up(user)
        q = []
        if len(txt.strip()) < 5:
            return ['None', q]
        try:
            loc = txt.rindex('YOU:')
            txt = txt[loc:]
        except:
            pass
        for s,x in abbrevs.items():
            txt = txt.replace(s, x)
        words_in = txt.replace('**', '').replace('&nbsp;','').split('<br>')
        words_out = []
        for s in words_in:
            s = s.lstrip('- *@#$%^&_=+-')
            if len(s) > 0:
                loc = s.find(' ')
                if loc > 1:
                    val = s[0:loc]
                    isnum = val.replace('.','0').isdecimal()
                    if isnum:
                        if val.endswith('.'):
                            val = val[:-1].replace('.',' point ') + '., '
                        else:
                            val = val.replace('.', ' point ') + ', '
                        s = 'num'+ val + s[loc:]
                words_out.append(s)
        chunklist = []
        for chunk in words_out:
            if chunk.strip() == '':
                continue
            isnumbered = chunk.startswith('num')
            number = ''
            loc = 0
            if isnumbered:
                chunk = chunk[3:]
                loc = chunk.index(',')
                number = chunk[0:loc]
                chunk = chunk[loc:]
            locs = []
            for i in range(1,len(chunk)-1):
                (a, b, c) = chunk[i-1:i+2]
                if a.isdecimal() and b == '.' and c.isdecimal():
                    locs.append(i)
            for i in locs:
                chunk = chunk[:i] + ' point ' + chunk[i+1:]
            if len(chunk) > 50:
                finechunks = chunk.split('.')
                for fchunk in finechunks:
                    if isnumbered:
                        fchunk = number + fchunk
                        isnumbered = False
                    if len(fchunk) > 0:
                        if fchunk != '"':
                            chunklist.append(fchunk)
            else:
                line = number + chunk
                if line != '"':
                    chunklist.append(line)
        total_speech = 0
        for chunk in chunklist:
            total_speech += len(chunk)
        with open(dataDir + user + '_speech.txt','a') as f:
            f.write(f'speech:{str(total_speech)}\n')
        chunk = chunklist[0]
        if chunk.strip() == '':
            return gr.Audio(sources=None)
        fname_list = gen_speech_file_names(user, len(chunklist))
        q = fname_list.copy()
        qsave = fname_list.copy()
        fname = q.pop(0)
        if len(chunklist) > 0:
            threading.Thread(target=speech_worker, daemon=True, args=(chunklist[1:],fname_list[1:])).start()
        response = Client().audio.speech.create(model="tts-1", voice="fable", input=chunk, speed=0.85, response_format='wav')
        with open(fname, 'wb') as fp:
            fp.write(response.content)
        return [fname, q]

    def gen_output_audio(q, user):
        try:
            fname = q.pop(0)
        except:
            final_clean_up(user)
            return [None, gr.Audio(sources=None)]
        if not os.path.exists(fname):
            sleep(3)
            if not os.path.exists(fname):
                response = Client().audio.speech.create(model="tts-1", voice="fable",
                    input='Sorry, text-to-speech is responding too slow right now', speed=0.85, response_format='wav')
                with open(fname, 'wb') as fp:
                    fp.write(response.content)
                q = []
        return [fname, q]


    gr.Markdown('# GPT Chat')
    gr.Markdown('Enter user name & password.  Tap "Help & Hints" button for more instructions.')
    with gr.Row():
        user_window = gr.Textbox(label = "User Name")
        user_window.blur(fn=update_user, inputs=user_window, outputs=[user, user_window])
        pwd_window = gr.Textbox(label = "Password")
        pwd_window.blur(updatePassword, inputs = pwd_window, outputs = [password, pwd_window])
        help_button = gr.Button(value='Help & Hints')
    with gr.Row():
        audio_widget = gr.Audio(type='filepath', format='wav',waveform_options=gr.WaveformOptions(
           show_recording_waveform=True), sources=['microphone'], scale = 3, label="Prompt/Question Voice Entry", max_length=120)
        reset_button = gr.ClearButton(value="Reset Voice Entry", scale=1) #new_func1()
    with gr.Row():
        clear_button = gr.Button(value="Restart Conversation")
        # gpt_chooser=gr.Radio(choices=[("GPT-3.5","gpt-3.5-turbo"),("GPT-4o","gpt-4o-mini")],
        #                      value="gpt-3.5-turbo", label="GPT Model", interactive=True)
        button_do_image = gr.Button(value='Make Image')
        button_get_image = gr.Button(value='Upload Image to Analyze')
        submit_button = gr.Button(value="Submit Prompt/Question")
        speak_output = gr.Button(value="Speak Dialog", visible=True)
    prompt_window = gr.Textbox(label = "Prompt or Question")
    gr.Markdown('### **Dialog:**')
    output_window = gr.Markdown(container=True)
    with gr.Row():
        with gr.Column():
            image_window2 = gr.Image(visible=False, interactive=True, label='Image to Analyze', type='filepath')
        with gr.Column():
            image_window = gr.Image(visible=False, label='Generated Image')
    with gr.Row():
        plot = gr.LinePlot(test_plot_df(), x="month", y="value", visible=False, label="Portfolio Value History")
    submit_button.click(chat,
             inputs=[prompt_window, user_window, password, history, output_window, model, uploaded_image_file],
             outputs=[history, output_window, prompt_window, model, uploaded_image_file, plot])
    clear_button.click(fn=new_conversation, inputs=user_window,
                      outputs=[prompt_window, history, output_window, image_window, image_window2, uploaded_image_file, plot])
    audio_widget.stop_recording(fn=transcribe, inputs=[user_window, password, audio_widget],
                                outputs=[prompt_window])
    audio_widget.pause_recording(fn=pause_message, outputs=[prompt_window])
    reset_button.add(audio_widget)
    audio_out = gr.Audio(autoplay=True, visible=False)
    audio_out.stop(fn=gen_output_audio, inputs=[q, user_window], outputs = [audio_out, q])
    speak_output.click(fn=initial_audio_output, inputs=[output_window, user_window], outputs=[audio_out, q])
    # output_window.change(fn=set_speak_button, inputs=output_window,outputs=speak_output)
    button_do_image.click(fn=make_image, inputs=[prompt_window,user_window, password],outputs=[image_window, output_window])
    image_window.change(fn=delete_image, inputs=[user])
    help_button.click(fn=show_help, outputs=output_window)
    button_get_image.click(fn=upload_image,inputs = [prompt_window, user, password], outputs = [image_window2, output_window])
    image_window2.upload(fn=load_image, inputs=[image_window2, user], outputs=[uploaded_image_file, output_window])
    # demo.unload(final_clean_up(user))
demo.launch(share=True, allowed_paths=[dataDir], ssr_mode=False)