File size: 173,876 Bytes
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9690769
b12c766
 
 
721265b
81500c0
 
 
b634bd1
cc9a4f7
 
 
 
 
 
b634bd1
 
cc9a4f7
b634bd1
5b60200
7ea3b2a
 
 
 
 
 
 
 
81500c0
cc9a4f7
 
81500c0
 
20df050
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4511910
81500c0
 
 
 
 
 
 
 
 
 
9dc194f
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0e8082
f227dbb
 
81500c0
 
 
 
 
4a66e5d
81500c0
4a66e5d
a806daf
a535805
a14f6ba
8689d68
f4f695c
 
 
a14f6ba
4a66e5d
 
 
521402f
81500c0
5645667
 
 
 
 
 
81500c0
4a66e5d
6d397aa
 
a535805
81500c0
 
 
 
 
 
 
f227dbb
 
81500c0
 
 
 
 
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
 
 
 
 
 
 
 
4a66e5d
81500c0
 
 
4a66e5d
 
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a66e5d
e5b6d94
be9d1db
e5b6d94
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4891822
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0df727b
81500c0
 
 
 
f5e6675
81500c0
84278b3
81500c0
 
3759f18
f5e6675
 
81500c0
 
 
 
 
 
e98a517
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459c70c
 
 
 
 
 
13b9a6c
1da716d
 
9c29d50
 
 
 
 
 
 
 
 
13b9a6c
 
 
f6f1b64
13b9a6c
 
 
 
f6f1b64
13b9a6c
fb88948
6346157
 
 
 
 
 
21440a4
c92a929
9bfaf60
f5e6675
13b9a6c
9c31005
13b9a6c
9bfaf60
 
943189e
a9e0cce
 
e0830e7
 
 
d4e2298
f227dbb
 
d4e2298
8cb714b
f227dbb
e9e92d8
d939e54
fb88948
9bfaf60
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
 
 
 
 
 
 
 
 
 
 
4a66e5d
81500c0
 
 
 
 
4a66e5d
81500c0
 
 
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
 
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
 
 
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
 
 
4a66e5d
81500c0
 
 
 
 
 
 
 
 
 
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
 
 
 
 
 
4a66e5d
9f7f049
81500c0
 
b1e4a4a
5aae156
81500c0
 
6f4cb86
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f4cb86
81500c0
 
 
 
 
 
 
 
 
 
 
 
e25a75d
81500c0
 
6f4cb86
81500c0
 
31f0b37
 
 
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f4cb86
81500c0
 
 
4a66e5d
81500c0
 
 
 
 
4a66e5d
81500c0
 
 
 
 
 
 
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
 
 
 
 
 
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a66e5d
81500c0
 
 
ba5ddeb
aa4fdbc
385273f
98c11f5
4a3de3c
385273f
 
 
 
 
 
96d9d04
385273f
eb84b83
385273f
4a3de3c
385273f
63f52ab
385273f
4a3de3c
385273f
 
 
 
 
4360fc1
385273f
cd7320d
 
ba5ddeb
 
 
385273f
 
 
 
 
 
aa4fdbc
 
 
 
 
 
 
 
 
 
 
 
 
 
385273f
81500c0
4a66e5d
0458836
 
81500c0
 
 
 
 
4a66e5d
81500c0
385273f
fb88948
 
 
 
 
 
 
a183ace
fb88948
 
 
 
 
8f3ab62
 
fb88948
 
 
 
8f3ab62
fb88948
893ec97
8f3ab62
fb88948
 
 
 
8f3ab62
fb88948
 
8f3ab62
 
 
a183ace
fb88948
 
385273f
81500c0
 
 
 
 
 
 
4c1ba8e
81500c0
c093ea3
81500c0
 
 
4a66e5d
 
81500c0
 
 
 
 
4a66e5d
81500c0
 
 
 
 
 
d2b76a8
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ada07f
a183ace
 
 
 
 
 
 
 
478a83b
a183ace
 
 
 
 
 
 
 
 
 
 
 
 
d96cc88
a183ace
 
7af53c5
a183ace
 
 
 
 
 
 
 
 
478a83b
a183ace
 
 
 
 
9ada07f
a183ace
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
 
 
 
 
 
4a66e5d
 
81500c0
 
 
4a66e5d
81500c0
 
 
 
 
 
4a66e5d
 
81500c0
 
 
 
 
 
ecb6875
 
81500c0
 
 
 
ecb6875
 
 
 
81500c0
4a66e5d
81500c0
3d40b74
81500c0
 
 
 
 
b8403f8
ac3bdb1
81500c0
ac3bdb1
4a66e5d
81500c0
 
 
 
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a66e5d
81500c0
 
 
 
 
 
 
 
4a66e5d
81500c0
 
aa4fdbc
81500c0
4c87f07
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c87f07
 
 
 
 
 
 
 
 
 
 
 
 
 
81500c0
 
 
 
 
4c87f07
81500c0
 
 
 
 
 
 
 
 
 
 
4c87f07
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
 
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
 
61b253a
81500c0
 
4a66e5d
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a66e5d
81500c0
 
 
 
 
 
 
 
 
 
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
 
 
 
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
 
4c87f07
d0e8082
4c87f07
d0e8082
3f5b676
d0e8082
 
 
 
 
 
 
9c29d50
d0e8082
2280f6d
4891822
 
554ed08
a92854f
04afa23
2272e2f
81500c0
 
19c01ed
81500c0
 
2280f6d
81500c0
 
 
 
 
2280f6d
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2280f6d
81500c0
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0e8082
81500c0
b50db34
81500c0
 
 
e7ee863
81500c0
 
 
e7ee863
81500c0
 
b50db34
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
b50db34
 
81500c0
 
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
 
 
4a66e5d
 
81500c0
 
 
 
 
 
 
4a66e5d
 
81500c0
 
 
 
 
 
 
 
4a66e5d
 
81500c0
 
 
 
 
 
 
 
 
 
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
4a66e5d
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a66e5d
81500c0
ba5ddeb
3872797
 
ba5ddeb
d4e2298
4f5ccf6
d94e6ef
fd419e9
ba5ddeb
4f5ccf6
b50db34
b32c4c2
 
 
 
 
ba5ddeb
5f3380a
b32c4c2
045bfb6
b32c4c2
 
 
2222840
4f5ccf6
b32c4c2
81500c0
 
7757e4a
416e6db
5ad4810
 
 
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ad4810
5b60200
81500c0
 
 
c1355df
81500c0
 
 
 
6eed671
5ad4810
 
6eed671
 
81500c0
5645667
357bdbe
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7369958
81500c0
 
 
 
 
 
 
 
 
 
fe6d263
81500c0
 
 
 
 
 
 
 
 
 
 
7369958
81500c0
75c29e5
98c11f5
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ad4810
7757e4a
81500c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01f0147
1de1ffe
81500c0
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
import gradio as gr
import json
import time
import numpy as np
import random
import os
import asyncio
import aiohttp
import requests
from PIL import Image
import io
#from textgen import getTextGen,multiprocessPrompts    

def getTextGen(prompt, model=''):
    from huggingface_hub import InferenceClient
    client = InferenceClient(token=os.getenv('inference'))
    import time
    good = False
    response = ''
    tries = 0
    model = model if model else "mistralai/Mixtral-8x7B-Instruct-v0.1"
    while not good and tries<=3:
        try:
            print('getTextGen -- trying prompt: ', model, prompt[:50])
            response = client.text_generation(prompt, model=model, max_new_tokens=2500, temperature=.7)
            print('getTextGen -- generated: ', response[:50], '\n\n')
            good = True
        except:
            time.sleep(.7)
            model = ["mistralai/Mistral-7B-Instruct-v0.2", "microsoft/Phi-3-mini-4k-instruct", "google/gemma-7b"][tries]
            tries += 1
            print('getTextGen -- retrying prompt: ', model, prompt[:50])
            
    return response


def multiprocessPrompts(prompts):
    from multiprocessing import Pool
    import time
    start = time.time()
    with Pool(5) as p:
        responses = p.map(getTextGen, prompts)
    print(time.time()-start)
    return responses



js_func = """
function newScroll() {
    var gallerys = document.getElementsByClassName("scroll");
    for (var i = 0; i < box.length; i++) {
        gallerys[i].style.overflow = "scroll";
    }
}
"""

js_func = """
function refresh() {
    const url = new URL(window.location);
    
    if (url.searchParams.get('__theme') !== 'dark') {
        url.searchParams.set('__theme', 'dark');
        window.location.href = url.href;
    }
}

"""

css = """
    .scroll[style] {
        overflow: scroll !important;
    }

"""





bed_layout_new = ['Artwork', 'Curtains', 'Palette', 'Bedroom Rug', 'Mirrors', 'Bedroom Chair', 'Ottoman', 'Bedroom', 'Bedroom Set', 'Bedding']

living_layout_new = ['Artwork', 'Curtains', 'Palette', 'Rug', 'Armchairs', 'End Tables',  'Love Seats', 'Living Room', 'Sofas', 'End Tables', 'Plant Pots', 'Indoor Plants', 'Coffee tables', 'TV stands', 'Artwork']


img_url = 'https://dreamdemo.pythonanywhere.com/image/'

bedrooms = {'bedroom 1': img_url+'master bedroom.jpg', 'bedroom 2': img_url+'guest bedroom 2 beds.jpg', "bedroom 3": img_url+'boy bedroom 1 bed (n).jpg', "bedroom 4": img_url+'kids bedroom with bunkbeds a.jpg', 'living room': img_url+'living room.jpg'}

room_item_placeholder_images_dict = {'BEDROOM FURNITURE':{'Bedroom': img_url + 'gray bedroom.png', 'Bedroom Set':img_url + 'gray bedroom set.jpg', 'Beds':img_url + 'gray bed.jpg', 'Mattresses':img_url + 'gray matresses.jpg', 'Dressers': img_url + 'gray dresser.jpg', 'Nightstands': img_url + 'gray nightstand.jpg', 'Armoires':img_url + 'gray armoires.jpg', 'Chests of drawers': img_url + 'gray chest of drawers.jpg', 'Mirrors':img_url + 'gray bedroom mirror.jpg', 'Bedroom Chair':img_url + 'gray bedroom chair.jpg', 'Rug':img_url + 'gray bedroom rug.jpg', 'Bedding':img_url + 'gray bedding.jpg', 'paint':img_url + 'gray can of paint.jpg', 'Curtains':img_url + 'gray bedroom curtains.jpg', 'Artwork':img_url + 'gray bedroom art.jpg', 'Plant Pots':img_url + 'gray plant pots.jpg', 'Indoor Plants':img_url + 'gray plants.png'}, 'LIVING ROOM FURNITURE':{'Living Room': img_url + 'gray living room.png', 'Love Seats': img_url + 'gray love seat.jpg', 'Sofas': img_url + 'gray sofa.jpg', 'Armchairs':img_url + 'gray armchair.jpg', 'Coffee tables': img_url + 'gray coffee table.jpg', 'End Tables': img_url + 'gray end table.jpg', 'TV stands': img_url + 'gray tv stand.jpg', 'Bookshelves': img_url + 'gray bookshelf.jpg', 'Media consoles':img_url + 'gray media console.jpg', 'Sectionals':img_url + 'gray sectional.jpg', 'Recliners':img_url + 'gray recliner.jpg', 'Rug':img_url + 'gray living room rug.jpg', 'paint':img_url + 'gray can of paint.jpg', 'Curtains':img_url + 'gray living room curtains.jpg', 'Artwork':img_url + 'gray living room art.jpg', 'Plant Pots':img_url + 'gray plant pots.jpg', 'Indoor Plants':img_url + 'gray plants.png'}}


async def get(url, session):
    try:
        async with session.get(url=url, timeout=1.5) as response:
            resp = await response.read()
            print("Successfully got url {} with resp of length {}.".format(url, len(resp)))
            return resp
    except Exception as e:
        print("Unable to get url {} due to {}.".format(url, e.__class__))
        return None


async def main(urls):
    async with aiohttp.ClientSession() as session:
        ret = await asyncio.gather(*(get(url, session) for url in urls))
    print("Finalized all. Return is a list of len {} outputs.".format(len(ret)))
    return ret



async def post(url, session, json_data, headers, timeout=120):
    try:
        print('main_post: ', type(url), len(url), type(headers), len(headers), type(json_data), len(json_data))
        async with session.request(method='post', url=url, timeout=timeout, headers=headers, json=json_data) as response:
            resp = await response.read()
            print("Successfully got url {} with resp of length {}.".format(url, len(resp)))
            return resp
    except Exception as e:
        print("Unable to get url {} due to {}.".format(url, e.__class__))
        return None


async def main_post(urls, headers, json_data, timeout=120):
    
    async with aiohttp.ClientSession() as session:
        ret = await asyncio.gather(*(post(url, session, json_data[i], headers[i], timeout=timeout) for i,url in enumerate(urls)))
    print("Finalized all. Return is a list of len {} outputs.".format(len(ret)))
    return ret

    

def getVizText(html):
    from bs4 import BeautifulSoup, NavigableString, Tag
    soup = BeautifulSoup(str(html), 'html.parser')
    viz_text = [tag.text for tag in soup.find_all() if tag.text and len(tag.find_all())==0 and tag.name not in ['style', 'script', 'head', 'title', 'meta', '[document]'] and not isinstance(tag, NavigableString)]
    viz_text_str = '...'.join(viz_text).replace('\\n', '').replace('\\t', '').replace('\n', '').replace('\t', '')
    return viz_text_str

def findShoppingRelevantTerms(html):
    viz_text_str = getVizText(str(html.decode("utf-8")))
    search_terms = [' off ', ' availability ', ' available ', ' delivery ', ' deliver ', ' ship ', ' shipping ', ' return ', ' returns ', ' exchange ', ' exchanges ', ' material ', ' materials ']
    found_terms = {t:(lambda text, term_loc: text[term_loc-300:term_loc+300])(viz_text_str, viz_text_str.lower().find(t.lower())) for t in search_terms if (t != ' off ' and t in viz_text_str) or (t == ' off ' and t in viz_text_str and ('%' in viz_text_str or '$' in viz_text_str))}
    return found_terms



int_des_styles_keys = ['Mid-Century Modern', 'Coastal', 'Industrial', 'Scandinavian', 'Bohemian', 'Farmhouse', 'Contemporary', 'Transitional', 'Maximalist', 'Southwestern', 'Rustic', 'Mexican', 'Traditional', 'Art Deco', 'Shabby Chic']


styles_images = {style: {'bedroom': img_url + style + ' bedroom.jpg', 'living room': img_url + style + ' living room.jpg'} for style in int_des_styles_keys}

design_images = [(v['bedroom'], k) for k,v in styles_images.items()]

def writeForStoreProcessing(store, zipcode):
    with open('C:\\Users\\Wayne\\Documents\\store_processors\\'+store+zipcode+'.json', 'w') as file:
        json.dump({'store': store, 'zipcode': zipcode}, file)


alarm1 = ['If the matter of..', 'Should the issue of..', 'In the event that..', 'If..', 'Provided..', 'Given that..', 'Supposing..', 'Assuming..', 'On the condition that..', 'In the case that..', 'Provided that..', 'Given the scenario where..', 'Supposing the situation where..', 'Assuming the circumstance in which..', 'On the off-chance that..', 'In the event..', 'If the prospect of..', 'Provided the idea of..', 'Given the notion of..', 'Supposing the thought of..', 'Assuming the consideration of..', 'On the chance that..', 'In the instance..', 'If the possibility of..', 'Provided the eventuality of..', 'Given the contingency of..', 'Supposing the scenario of..', 'Assuming the situation of..', 'On the occasion that..', 'In the likelihood that..', 'If the prospect of..', 'Provided the idea of..', 'Given the notion of..', 'Supposing the thought of..', 'Assuming the consideration of..', 'On the chance that..', 'In the instance..', 'If the possibility of..', 'Provided the eventuality of..', 'Given the contingency of..', 'Supposing the scenario of..', 'Assuming the situation of..', 'On the occasion that..', 'In the likelihood that..', 'If the aspect of..', 'Provided the feature of..', 'Given the element of..', 'Supposing the component of..', 'Assuming the detail of..', 'On the chance that..', 'In the instance..', 'If the detail of..', 'Provided the facet of..', 'Given the dimension of..', 'Supposing the aspect of..', 'Assuming the attribute of..', 'On the occasion that..', 'In the likelihood that..', 'If the factor of..', 'Provided the variable of..', 'Given the element of..', 'Supposing the component of..', 'Assuming the detail of..', 'On the chance that..', 'In the instance..', 'If the particulars of..', 'Provided the specifics of..', 'Given the intricacies of..', 'Supposing the nuances of..', 'Assuming the subtleties of..', 'On the occasion that..', 'In the likelihood that..', 'If the matter of..', 'Provided the issue of..', 'Given the concern over..']

alarm2 = ['be a source of worry', 'is a cause for concern', 'is a source of unease', 'is a cause for apprehension', 'is a point of uneasiness', 'is a source of discomfort', 'is a cause for distress', 'is a cause for alarm', 'is a point of concern', 'troubles you', 'unsettles you', 'worries you', 'unnerves you', 'disturbs you', 'vexes you', 'distresses you', 'bothers you', 'unsettles you', 'worries you', 'unnerves you', 'disturbs you', 'vexes you', 'distresses you', 'is a source of unease for you', 'is a cause for apprehension', 'is a point of uneasiness', 'is a source of discomfort', 'is a cause for distress', 'is a point of concern', 'is a cause for alarm', 'is a point of concern', 'is a source of unease for you', 'is a cause for apprehension', 'is a point of uneasiness', 'is a source of discomfort', 'is a cause for distress', 'is a point of concern', 'is a cause for alarm', 'is a point of concern', 'is a source of unease for you', 'is a cause for apprehension', 'is a point of uneasiness', 'is a source of discomfort', 'is a cause for distress', 'is a point of concern', 'is a cause for alarm', 'is a point of concern', 'is a source of unease for you']

alarm3 = ['this might be worrying', 'this could be worrying to you', 'you might be worried', 'you may be worried', 'you may be concerned', 'you might be concerned', 'you might be uneasy', 'you may be uneasy', 'this may cause some apprehension', 'this could make you apprehensive', 'you may be apprehensive', 'you might be apprehensive', 'you may have some uneasiness', 'you might have some uneasiness', 'this might cause some uneasiness', 'it might make you uneasy', 'maybe you have some uneasiness', 'you may have some discomfort', 'you might have some discomfort', 'you could have some discomfort', 'maybe you have some discomfort', 'you may have some distress', 'this may cause some distress', 'it might give you some distress', 'you might have some distress', 'you could have some distress', 'maybe you have some distress', 'you might be alarmed', 'you may be alarmed', 'you could be alarmed', 'this might be alarming', 'you may find this alarming', 'maybe you are alarmed', 'you might find it concerning', 'you may find it concerning', 'you could find it concerning', 'maybe you find it concerning', 'this could be concerning', 'this may be concerning to you', 'you might be troubled', 'you may be troubled', 'you could be troubled', 'maybe you are troubled', 'you may be unsettled by this', 'you might be unsettled by this', 'you could be unsettled by this', 'maybe you are unsettled by this', 'you may find this unsettling', 'you might find it unsettling', 'you may find it worrying', 'you might find it worrying', 'you could find it worrying', 'maybe you find it worrying', 'you may find it unnerving', 'you might find it unnerving', 'you could find it unnerving', 'maybe you find it unnerving', 'maybe you are disturbed', 'maybe you find it disturbing', 'you may be disturbed', 'you might disturbed', 'this might disturb you', 'this may be disturbing to you', 'you could be disturbed this', 'you might be vexed', 'you may be vexed', 'you might find this vexing', 'maybe this is vexing', 'this maybe distresses you', 'this might distress you', 'this could distress you', 'you may be distressed', 'this might bother you', 'this could bother you', 'this maybe bothers you', 'you might be bothered', 'you may be bothered by this', 'this might be unsettling', 'this may be unsettling to you']

class Session():
    def __init__(self):
        self.match_counties = []
        self.county = ""
        self.prompts = {}
        self.listing_details = {}
        self.img_data = {}
        self.bound_box_ij = (0,0)
        self.stride_tm1 = 1
        self.nudge = 1
        self.impresh_image_rewrite = {}
        self.Palettes = {}
        self.activated_items = {}
        self.filtered_files = {}
        self.filtered_files_room = {}
        self.filtered_files_style = {}
        self.filtered_items_room = {}
        self.filtered_items_style = {}
        self.filtered_items_colors = {}
        self.items = bed_layout_new 
        self.price = 'Affordable'.lower().split()[0]
        self.bedsize = 'Queen'.lower().split()[0]
        self.room_style = 'Mid-Century Modern'.lower().split()[0]
        self.room_type = 'bedroom'
        self.item_data = {}
        self.item_data_ = {}
        self.item_data_keys = {}
        self.Palette_img = np.zeros((200,200,3)).astype(np.uint8)
        self.Palette_img[:] = 128
        self.default_img = np.zeros((200,200,3)).astype(np.uint8)
        self.default_img[:] = 64
        self.display_items = {}
        self.Paletteid = None
        self.clicked_displayed_product = ''
        self.current_img_signature = self.img_id = None
        self.updated_display = [((self.Palette_img if item == 'Palette' else self.default_img) if item in ['Palette', 'Living Room', 'Bedroom'] else room_item_placeholder_images_dict['LIVING ROOM FURNITURE'][item], item) for item in living_layout_new]
        self.summary = {}
        self.summary_closed = True
        self.summary_radio = 'Complete'
        self.product_means = {}
        self.Palette_imgs = {}
        self.Palette_ids = {}
        self.Palettes_displayed = {}
        self.items_layouts = {}
        self.zipcode = '30054'
        self.state = 'GA'
        self.seshid = str(time.time())
        self.time = ''
        self.reset = False
        self.locator_genid = {}
        self.frmt_idxs_maps = {}
        self.frmt_id_maps = {}
        
class AllSessions():
    def __init__(self):
        self.sessions = {}

all_sesh = AllSessions()

def getSesh(seshid):
    print('getSesh: ', seshid, all_sesh.sessions.keys())
    if seshid and seshid not in all_sesh.sessions:
        all_sesh.sessions[seshid] = Session()
        all_sesh.sessions[seshid].seshid = seshid
        print('getSesh--instantiated sesh: ', seshid, all_sesh.sessions[seshid].seshid, all_sesh.sessions[seshid].Palettes.keys())
    else:
        print('getSesh--sesh in all_sesh: ', seshid, all_sesh.sessions[seshid].Palettes.keys())
    sesh = all_sesh.sessions[seshid]
    return sesh

def setSesh(seshid, sesh):
    all_sesh.sessions[seshid] = sesh

default_img = np.zeros((200,200,3)).astype(np.uint8)
default_img[:] = 64

Palette_img = np.zeros((200,200,3)).astype(np.uint8)
Palette_img[:] = 128

def submitPhoto(img, rooms, seshid):
    sesh = getSesh(seshid)
    if sesh.seshid != seshid:
        sesh.seshid = seshid
    print('submitPhoto reset rooms: ', rooms, seshid, sesh.seshid)
    sesh.current_img_signature = str(img.sum())
    sesh.img_data[sesh.current_img_signature] = img
    sesh.Palettes[sesh.current_img_signature] = {}
    sesh.activated_items[sesh.current_img_signature] = {}
    sesh.filtered_files[sesh.current_img_signature] = {} 
    sesh.filtered_files_room[sesh.current_img_signature] = {} 
    sesh.filtered_files_style[sesh.current_img_signature] = {}  
    sesh.frmt_idxs_maps[sesh.current_img_signature] = {}
    sesh.frmt_id_maps[sesh.current_img_signature] = {}
    sesh.Palette_img = np.zeros((200,200,3)).astype(np.uint8)
    sesh.Palette_img[:] = 128
    sesh.items_layouts[sesh.current_img_signature] = bed_layout_new 
    rooms = rooms if rooms else []
    rooms.append((img, sesh.current_img_signature))
    print('submitPhoto reset: ', sesh.reset)
    #return [(v,str(k)) for k,v in sesh.img_data.items()], gr.Image(label='Upload Room Photo
    setSesh(seshid, sesh)
    return rooms, gr.Image(label='Upload Room Photo'), seshid

def summarisePerStore(seshid):
    sesh = getSesh(seshid)
    sesh.summary_joined = {}
    for imgid,product_dicts in sesh.summary.items():
        for item_pd in product_dicts: 
            if not item_pd:
                continue
            item, pd = item_pd[0], item_pd[1]
            store = pd['store'].split(' -')[0]
            if store and store not in sesh.summary_joined:
                sesh.summary_joined[store] = {'total': 0, 'num_items':0, 'descriptions':[], 'prices':[], 'sources':[]}
            sesh.summary_joined[store]['total'] += float(pd['price'].replace('$', '').replace(',', '')) if pd['price'] and '$' in pd['price'] else 0
            sesh.summary_joined[store]['prices'].append(pd['price'] if pd['price'] and '$' in pd['price'] else None)
            sesh.summary_joined[store]['descriptions'].append(pd['description'])
            sesh.summary_joined[store]['sources'].append(pd['href'])
            sesh.summary_joined[store]['num_items'] += 1
    setSesh(seshid, sesh)


def summarisePerStore(seshid):
    sesh = getSesh(seshid)
    sesh.summary_joined = {}
    for imgid,product_dicts in sesh.summary.items():
        for item_pd in product_dicts: 
            if not item_pd:
                continue
            item, pd = item_pd[0], item_pd[1]
            store = pd['store'].split(' -')[0]
            if store and store not in sesh.summary_joined:
                sesh.summary_joined[store] = {}

            sesh.summary_joined[store][item] = {'product_dict': pd, 'count':1}
    setSesh(seshid, sesh)


def updateItemDisplay(seshid, budget=False):
    sesh = getSesh(seshid)
    
    if True:
        keys = ['filtered_items_room', 'current_img_signature', 'items', 'filtered_items_style', 'room_style', 'room_type', 'bedsize', 'price', 'filtered_items_colors', 'Palette_ids', 'item_data', 'item_data_', 'display_items', 'item_data_keys', 'Palettes_displayed', 'room_img_loaded', 'Paletteid', 'img_id', 'seshid']
        url = 'https://dreamdemo.pythonanywhere.com/sesh'
        data = sesh.__dict__
        valid_data = {k:v for k,v in data.items() if k in keys} 
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}

    if True: #try:

        import json
        r = requests.post(url, data=json.dumps(valid_data), headers=headers)
        print('json return status code: ', r.status_code)
        data_dict = json.loads(r.content)
        for k in data_dict:
            print('setting attr: ', k)
            setattr(sesh, k, data_dict[k])

        if True:

            #sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]] = {item:[d for d in products if ((not budget or not hasattr(sesh,'item_budgets') or sesh.current_img_signature not in sesh.item_budgets) or float(d['price'].replace('$', '').replace(',', ''))<sesh.item_budgets[sesh.current_img_signature][item])] for item,products in sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items()}

            sesh.product_means[sesh.current_img_signature] = {item:sum([float(pd['price'].replace('$', '').replace(',', '')) for pd in products])/len(products) if products else 0 for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items() if item not in ['Palette', 'Living Room', 'Bedroom']}

            if hasattr(sesh, 'budget_number') and sesh.budget_number:
                print('updateItemDisplay -- sesh.budget_number: ', sesh.budget_number)
                #product_lens = {item:len(products) for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items() if item not in ['Palette', 'Living Room', 'Bedroom']}
                #print('updateItemDisplay -- product_lens: ', product_lens)

                sesh.product_means_total = sum([v for img in sesh.product_means for k,v in sesh.product_means[img].items()])
                sesh.product_means_weights = {img:{item:avg/sesh.product_means_total for item,avg in sesh.product_means[img].items()} for img in sesh.product_means}
                print('updateItemDisplay -- sesh.product_means, sesh.product_means_total, sesh.product_means_weights, budget: ', sesh.product_means, sesh.product_means_total, sesh.product_means_weights, budget)

                sesh.item_budgets = {img: {item: int(weight*sesh.budget_number) for item,weight in weights.items()} for img,weights in sesh.product_means_weights.items()}
                #sesh.item_data_keys[sesh.current_img_signature] = {'room_type': sesh.room_type, 'room_style':sesh.room_style, 'price': sesh.price, 'Paletteid': sesh.Palette_ids[sesh.current_img_signature], 'inbudget':{item:[didx for didx,d in enumerate(products) if ((not budget or not hasattr(sesh,'item_budgets') or sesh.current_img_signature not in sesh.item_budgets) or float(d['price'].replace('$', '').replace(',', ''))<sesh.item_budgets[sesh.current_img_signature][item])] for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items()}}

                sesh.inbudget = {img:{item:[didx for didx,d in enumerate(products) if float(d['price'].replace('$', '').replace(',', ''))<sesh.item_budgets[img][item]] for item,products in sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']].items()} for img in sesh.item_data_keys}

                sesh.display_items_ = {img:[(-1 if item in ['Palette', 'Living Room', 'Bedroom'] or not sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item] else (sesh.display_items_[img][itemi][0] if sesh.display_items_[img][itemi][0] in sesh.inbudget[img][item] else (-1 if not sesh.inbudget[img][item] else np.random.choice(sesh.inbudget[img][item]))), item) for itemi,item in enumerate(sesh.items_layouts[img])] for img in sesh.item_data_keys}

            else:
                #sesh.item_data_keys[sesh.current_img_signature] = {'room_type': sesh.room_type, 'room_style':sesh.room_style, 'price': sesh.price, 'Paletteid': sesh.Palette_ids[sesh.current_img_signature], 'inbudget':{item:[didx for didx,d in enumerate(products)] for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items()}}

                sesh.inbudget = {img:{item:[didx for didx,d in enumerate(products)] for item,products in sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']].items()} for img in sesh.item_data_keys}

                #print('room type: ', [(sesh.item_data_keys[img]['room_type'], None if not hasattr(sesh, 'display_items_') else [data[0] for itemis,data in sesh.display_items_[img].items()],) for img in sesh.item_data_keys])
                print('room type: ', [sesh.item_data_keys[img]['room_type'] for img in sesh.item_data_keys])
                #sesh.display_items_ = {img:[(-1 if item in ['Palette', 'Living Room', 'Bedroom'] or not sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item] else (sesh.display_items_[img][itemi][0] if hasattr(sesh, 'display_items_') and img in sesh.display_items_ and itemi in sesh.display_items_[img] and sesh.display_items_[img][itemi] and sesh.display_items_[img][itemi][0] in sesh.inbudget[img][item] else random.sample(list(range(len(sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item]))), 1)[0]), item) for itemi,item in enumerate(sesh.items_layouts[img])] for img in sesh.item_data_keys}
                sesh.display_items_ = {img:[(-1 if item in ['Palette', 'Living Room', 'Bedroom'] or not sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item] else (random.sample(list(range(len(sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item]))), 1)[0]), item) for itemi,item in enumerate(sesh.items_layouts[img])] for img in sesh.item_data_keys}


            if hasattr(sesh, 'budget_number') and sesh.budget_number:
                print('updateDisplay -- sesh.item_budgets: ', sesh.item_budgets, sum([v for img in sesh.item_budgets for k,v in sesh.item_budgets[img].items()]))


            sesh.summary = {img: [() if itemidx_item[1] in ['Palette', 'Living Room', 'Bedroom'] or itemidx_item[0] < 0 else (itemidx_item[1], sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][itemidx_item[1]][itemidx_item[0]]) for itemidx_item in sesh.display_items_[img]] for img in sesh.display_items_}


        realised_display = [((sesh.Palette_imgs[sesh.current_img_signature] if item_dataidx[1] == 'Palette' else sesh.img_data[sesh.img_id]) if item_dataidx[1] in ['Palette', 'Living Room', 'Bedroom'] else (sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][item_dataidx[1]][item_dataidx[0]]['img'] if item_dataidx[0] >= 0 else sesh.default_img), item_dataidx[1]) for item_dataidx in sesh.display_items_[sesh.current_img_signature]]

        #print('writing For Store Processing')
        for item_dataidx in sesh.display_items_[sesh.current_img_signature]:
            if item_dataidx[0] >= 0:
                store = sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][item_dataidx[1]][item_dataidx[0]]['store']
                writeForStoreProcessing(store, sesh.zipcode)
                #print('wrote For Store Processing: ', store)
        #print('completed writing For Store Processing')


        sesh.updated_display = realised_display 
        summarisePerStore(seshid)

        setSesh(seshid, sesh)

        return gr.Gallery(realised_display, label='Room Items', columns=5) 
    else: #except:
        setSesh(seshid, sesh)
        return sesh.updated_display 

def getMostUsedColorsRGB(img_bytes):
    if True:
        img = np.array(Image.open(io.BytesIO(img_bytes)))
    else:
        return []
    imgq = img // 48 * 48
    clr_counts = {}
    for i in range(0, imgq.shape[0], 7):
        for j in range(0, imgq.shape[1], 7):
            clr = tuple(imgq[i,j])
            if clr not in clr_counts:
                clr_counts[clr] = 0
            clr_counts[clr] += 1
    clr_counts_ = {v:k for k,v in clr_counts.items()}
    counts_srtd = sorted(clr_counts_)[::-1]
    counts_srtd_rgb = [[int(val) for val in clr_counts_[i]] for i in counts_srtd[:7]]
    return counts_srtd_rgb

def bytesToSerializableImageVals(img_bytes):
    if True:
        img = np.array(Image.open(io.BytesIO(img_bytes)).resize((35,35)))
        #data = [tuple([int(val) for val in rgb]) for row in img for rgb in row]
        data = [int(val) for row in img for rgb in row for val in rgb]
        print('bytesToSerializableImageVals len+: ', len(data))
        return data
    else:
        return []

    
def isJSONSerialiazable(obj):
    try:
        json.dumps(obj)
        return True
    except:
        return False

def updateItemDisplay(seshid, budget=False, pallete_change=False):
    sesh = getSesh(seshid)
    print('updateItemDisplay seshid: ', seshid, sesh.seshid) 
    print('updateItemDisplay sesh.Palettes.keys: ', sesh.Palettes.keys())
    print('updateItemDisplay all_sesh.sessions: ', all_sesh.sessions.keys()) 
    if True:
        keys = ['filtered_items_room', 'current_img_signature', 'items', 'filtered_items_style', 'room_style', 'room_type', 'bedsize', 'price', 'filtered_items_colors', 'Palette_ids', 'item_data', 'item_data_', 'display_items', 'item_data_keys', 'Palettes_displayed', 'room_img_loaded', 'Paletteid', 'img_id', 'seshid']
        url = 'https://dreamdemo.pythonanywhere.com/sesh'
        data = sesh.__dict__
        valid_data = {k:v for k,v in data.items() if k in keys and isJSONSerialiazable(v)} 
        print('updateItemDisplay sesh keys: ', valid_data.keys())
        valid_data['seshid'] = seshid
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}

    if True: #try:

        print('new and improved updateDisplay -- Palette_ids, Paletteid: ', sesh.Palette_ids, sesh.Paletteid)

        import json
        r = requests.post(url, data=json.dumps(valid_data), headers=headers)
        print('json return status code: ', r.status_code)
        data_dict = json.loads(r.content)
        #print('json return item_data_: ', data_dict['item_data_'])
        for k in data_dict:
            if k == 'seshid': continue
            print('setting attr: ', k)
            setattr(sesh, k, data_dict[k])

        if True:

            #sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]] = {item:[d for d in products if ((not budget or not hasattr(sesh,'item_budgets') or sesh.current_img_signature not in sesh.item_budgets) or float(d['price'].replace('$', '').replace(',', ''))<sesh.item_budgets[sesh.current_img_signature][item])] for item,products in sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items()}

            sesh.product_means[sesh.current_img_signature] = {item:sum([float(pd['price'].replace('$', '').replace(',', '')) for pd in products])/len(products) if products else 0 for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items() if item not in ['Palette', 'Living Room', 'Bedroom']}

            if hasattr(sesh, 'budget_number') and sesh.budget_number and not pallete_change:
                print('updateItemDisplay -- sesh.budget_number: ', sesh.budget_number)
                #product_lens = {item:len(products) for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items() if item not in ['Palette', 'Living Room', 'Bedroom']}
                #print('updateItemDisplay -- product_lens: ', product_lens)

                sesh.product_means_total = sum([v for img in sesh.product_means for k,v in sesh.product_means[img].items()])
                sesh.product_means_weights = {img:{item:avg/sesh.product_means_total for item,avg in sesh.product_means[img].items()} for img in sesh.product_means}
                print('updateItemDisplay -- sesh.product_means, sesh.product_means_total, sesh.product_means_weights, budget: ', sesh.product_means, sesh.product_means_total, sesh.product_means_weights, budget)

                sesh.item_budgets = {img: {item: int(weight*sesh.budget_number) for item,weight in weights.items()} for img,weights in sesh.product_means_weights.items()}
                #sesh.item_data_keys[sesh.current_img_signature] = {'room_type': sesh.room_type, 'room_style':sesh.room_style, 'price': sesh.price, 'Paletteid': sesh.Palette_ids[sesh.current_img_signature], 'inbudget':{item:[didx for didx,d in enumerate(products) if ((not budget or not hasattr(sesh,'item_budgets') or sesh.current_img_signature not in sesh.item_budgets) or float(d['price'].replace('$', '').replace(',', ''))<sesh.item_budgets[sesh.current_img_signature][item])] for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items()}}

                sesh.inbudget = {img:{item:[didx for didx,d in enumerate(products) if float(d['price'].replace('$', '').replace(',', ''))<sesh.item_budgets[img][item]] for item,products in sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']].items()} for img in sesh.item_data_keys}

                sesh.display_items_ = {img:[(-1 if item in ['Palette', 'Living Room', 'Bedroom'] or not sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item] else (sesh.display_items_[img][itemi][0] if sesh.display_items_[img][itemi][0] in sesh.inbudget[img][item] else (-1 if not sesh.inbudget[img][item] else np.random.choice(sesh.inbudget[img][item]))), item) for itemi,item in enumerate(sesh.items_layouts[img])] for img in sesh.item_data_keys}

            else:
                #sesh.item_data_keys[sesh.current_img_signature] = {'room_type': sesh.room_type, 'room_style':sesh.room_style, 'price': sesh.price, 'Paletteid': sesh.Palette_ids[sesh.current_img_signature], 'inbudget':{item:[didx for didx,d in enumerate(products)] for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items()}}

                sesh.inbudget = {img:{item:[didx for didx,d in enumerate(products)] for item,products in sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']].items()} for img in sesh.item_data_keys}

                #print('room type: ', [(sesh.item_data_keys[img]['room_type'], None if not hasattr(sesh, 'display_items_') else [data[0] for itemis,data in sesh.display_items_[img].items()],) for img in sesh.item_data_keys])
                print('room type: ', [sesh.item_data_keys[img]['room_type'] for img in sesh.item_data_keys])
                #sesh.display_items_ = {img:[(-1 if item in ['Palette', 'Living Room', 'Bedroom'] or not sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item] else (sesh.display_items_[img][itemi][0] if hasattr(sesh, 'display_items_') and img in sesh.display_items_ and itemi in sesh.display_items_[img] and sesh.display_items_[img][itemi] and sesh.display_items_[img][itemi][0] in sesh.inbudget[img][item] else random.sample(list(range(len(sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item]))), 1)[0]), item) for itemi,item in enumerate(sesh.items_layouts[img])] for img in sesh.item_data_keys}
                item_lens = [(item, len(sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][item])) for itemi,item in enumerate(sesh.items_layouts[sesh.current_img_signature])]
                getSampleIndexes = lambda lngth: sorted(set([int(i) for j in [2,3,4] for i in [np.clip(0,lngth-1,lngth//j), np.clip(0,lngth-1,lngth-(lngth//j))]] + [0,(lngth-1 if lngth > 0 else 0)]))
                item_idxs = [(pair[0], [] if pair[1] <= 0 else getSampleIndexes(pair[1])) for pair in item_lens]
                item_lens_ln = [len(pair[1]) for pair in item_idxs]
                urls = [sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][pair[0]][idx]['img'] for i,pair in enumerate(item_idxs) if pair[1] for idx in pair[1]]
                start = time.time()
                responses = asyncio.run(main(urls))
                #rgbs = [getMostUsedColorsRGB(r) for r in responses]
                print('number of images retrieved: ', len(responses), item_lens)
                
                pallete_rgb = list(set([tuple([int(val) for val in rgb]) for row in sesh.Palette_img for rgb in row]))

                """url = 'https://dreamdemo.pythonanywhere.com/rgb'
                valid_data = {'rgbs':rgbs, 'pallete_rgb':pallete_rgb} 
                headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
                r = requests.post(url, data=json.dumps(valid_data), headers=headers)
                jsondata = json.loads(r.content)
                scores = jsondata['data']"""

                start = time.time()

                urls = ['https://dreamdemo.pythonanywhere.com/overlap' for i,_ in enumerate(responses)]
                headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
                #json_data = [json.dumps({'pallete_rgb': pallete_rgb, 'item_rgb':bytesToSerializableImageVals(r)}) for i,r in enumerate(responses)]
                end = time.time()
                print('bytesToSerializableImageVals: ', end-start)
                
                start = time.time()
                """try:
                    responses = asyncio.run(main_post(urls[:3], headers[:3], json_data[:3], timeout=.5))
                    responses = asyncio.run(main_post(urls, headers, json_data, timeout=5))
                    scores_ = [json.loads(r)['data'] for r in responses]
                    #print('overlap scores: ', scores[:20])
                except:
                    scores_ = [0 for i,_ in enumerate(urls)]"""
                scores_ = [0 for i,_ in enumerate(urls)]
                end = time.time()
                scores = scores_ #[scores_[i%7] if i%7==0 else 0 for i,_ in enumerate(item_lens_ln)]
                print('bytesToSerializableImageVals overlap: ', end-start, scores[:10])
                
                section_scores = [scores[sum(item_lens_ln[:i]):sum(item_lens_ln[:i])+ln] for i,ln in enumerate(item_lens_ln)]
                section_scores_amax = [np.argmax(s) if s else -1 for s in section_scores]
                #section_scores_amax = [np.argsort(s)[::-1][np.random.randint(0,max(3, len(s)-1))] if len(s) < 2 else -1 for s in section_scores]
                best_idxs = {item_idxs[i][0]: item_idxs[i][1][idx] if idx > -1 else -1 for i,idx in enumerate(section_scores_amax)}
                end = time.time()
                
                print('updateDisplay -- item images downloaded: ', str(end-start), best_idxs)
                #sesh.display_items_ = {img:[(-1 if item in ['Palette', 'Living Room', 'Bedroom'] or not sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item] else (random.sample(list(range(len(sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item]))), 1)[0]), item) for itemi,item in enumerate(sesh.items_layouts[img])] for img in sesh.item_data_keys}
                sesh.display_items_ = {img:[(-1 if item in ['Palette', 'Living Room', 'Bedroom'] or not sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item] else (random.sample(list(range(len(sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item]))), 1)[0] if img != sesh.current_img_signature else best_idxs[item]), item) for itemi,item in enumerate(sesh.items_layouts[img])] for img in sesh.item_data_keys}


            

            if hasattr(sesh, 'budget_number') and sesh.budget_number:
                print('updateDisplay -- sesh.item_budgets: ', sesh.item_budgets, sum([v for img in sesh.item_budgets for k,v in sesh.item_budgets[img].items()]))





            sesh.summary = {img: [() if itemidx_item[1] in ['Palette', 'Living Room', 'Bedroom'] or itemidx_item[0] < 0 else (itemidx_item[1], sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][itemidx_item[1]][itemidx_item[0]]) for itemidx_item in sesh.display_items_[img]] for img in sesh.display_items_}


        realised_display = [((sesh.Palette_imgs[sesh.current_img_signature] if item_dataidx[1] == 'Palette' else sesh.img_data[sesh.img_id]) if item_dataidx[1] in ['Palette', 'Living Room', 'Bedroom'] else (sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][item_dataidx[1]][item_dataidx[0]]['img'] if item_dataidx[0] >= 0 else sesh.default_img), item_dataidx[1]) for item_dataidx in sesh.display_items_[sesh.current_img_signature]]

        #print('writing For Store Processing')
        for item_dataidx in sesh.display_items_[sesh.current_img_signature]:
            if item_dataidx[0] >= 0:
                store = sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][item_dataidx[1]][item_dataidx[0]]['store']
                writeForStoreProcessing(store, sesh.zipcode)
                #print('wrote For Store Processing: ', store)
        #print('completed writing For Store Processing')

        


        sesh.updated_display = realised_display 
        summarisePerStore(seshid)

        """sesh.product_pd_counts = [(product,pd_count) for store in sesh.summary_joined for product,pd_count in sesh.summary_joined[store].items()]
        urls = [product_pd_count[1]['product_dict']['href'] for product_pd_count in sesh.product_pd_counts]
        sesh.responses = asyncio.run(main(urls))
        item_locator_data = {data[1]: sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']}
        print('item_locator_data: ', item_locator_data, '\n/*/*', [item_locator_data[product_pd_count[0]] for i,product_pd_count in enumerate(sesh.product_pd_counts)])
        responses = [r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]
        urls = ['https://dreamdemo.pythonanywhere.com/dump_text_gen' for _ in range(len(sesh.product_pd_counts))]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        for item,idxs in item_locator_data.items():
            if tuple(idxs) not in sesh.locator_genid: sesh.locator_genid[tuple(idxs)] = gen_uid = str(time.time())
        json_data = [json.dumps({'room_type': sesh.room_type, 'item_locator_data': item_locator_data[product_pd_count[0]], 'gen_uid': sesh.locator_genid[tuple(item_locator_data[product_pd_count[0]])], 'response':responses[i], 'item': product_pd_count[0]}) for i,product_pd_count in enumerate(sesh.product_pd_counts) if product_pd_count[0] not in ['Palette', 'Living Room', 'Bedroom']]
        responses = asyncio.run(main_post(urls, headers, json_data, timeout=.1))
        print('dump_text_gen: ', responses)"""

        
        """item_locator_data = content['item_locator_data']
        responses = content['responses']
        items = content['items']
        number_of_items = min(max(content['number_of_items'], 3), 7)
        room_type = content['room_type']
        video_format = content['video_format']"""

        """urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature]  if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
        sesh.responses = asyncio.run(main(urls))
        urls = ['https://dreamdemo.pythonanywhere.com/store_shop' for _ in range(len(urls))]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        responses = [r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]
        item_locator_data = [sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']]
        json_data = [json.dumps({'response': responses[i], 'item_locator_data': item_locator_data[i]}) for i,url in enumerate(urls)]
        responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
        print('*-/*/-*-updateDisplay: dumped store_shop: ', item_locator_data)
        
        formats = ['Youtube Long-Form', 'Youtube Short-Form', 'Facebook Long-Form', 'Instagram Reel', 'Tiktok', 'LinkedIn']
        number_of_items = [7, 3, 7, 3, 3, 7]
        urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature]  if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
        sesh.responses = asyncio.run(main(urls))
        urls = ['https://dreamdemo.pythonanywhere.com/scriptgen_promise' for _ in range(len(formats))]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        responses = [[r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses] for _ in range(len(formats))]
        item_locator_data = [[sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
        items = [[data[1] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
        idxs = [list(range(len(items))) for i,_ in enumerate(formats)]
        for i,_ in enumerate(formats):
            np.random.shuffle(idxs[i])
            idxs[i] = idxs[i][:number_of_items[i]]
            sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]] = [item_locator_data[i][idx] for idx in idxs[i]]
            sesh.frmt_id_maps[sesh.current_img_signature][formats[i]] = str(time.time())
            time.sleep(.001)
        #json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data, 'gen_uid': i, 'responses':responses, 'items': items}) for i,fmt in enumerate(formats)]
        json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'idxs':idxs[i][:number_of_items[i]], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data[i], 'gen_uid': sesh.frmt_id_maps[sesh.current_img_signature][formats[i]], 'seshid':seshid, 'items': items[i]}) for i,fmt in enumerate(formats)]
        responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
        #responses = asyncio.run(main_post(urls, headers, json_data, timeout=3))
        print('*-/*/-*-updateDisplay: dumped scriptgen_promise: ', responses)"""
        
        setSesh(seshid, sesh)
        return gr.Gallery(realised_display, label='Room Items', columns=5) 
    else: #except:
        setSesh(seshid, sesh)
        return sesh.updated_display 


def updateRoomType(evt: gr.SelectData, seshid):
    sesh = getSesh(seshid)
    label = evt.value['caption'].lower().split()[0] if evt.value['caption'] else sesh.room_type 
    sesh.room_type = label
    images = [(v['bedroom'] if sesh.room_type == 'bedroom' else v['living room'], k) for k,v in styles_images.items()]
    sesh.items = items = bed_layout_new if sesh.room_type == 'bedroom' else living_layout_new 
    sesh.items_layouts[sesh.current_img_signature] = items = bed_layout_new if sesh.room_type == 'bedroom' else living_layout_new 

    #display = updateItemDisplay()

    if hasattr(sesh, 'room_img_loaded') and sesh.room_img_loaded:
        display = updateItemDisplay(seshid)
    else:
        display = sesh.updated_display
    setSesh(seshid, sesh)

    return images, gr.Radio(['Full', 'Queen', 'King'], value='Full', label='Bed Size', interactive=True, visible=True) if label == 'bedroom' else gr.Radio(visible=False), gr.Gallery(sesh.updated_display, label='Room Items', columns=5), display


def updateStyle(evt: gr.SelectData, seshid):
    sesh = getSesh(seshid)
    style = evt.value['caption'].lower().split()[0] if evt.value['caption'] else sesh.room_style
    sesh.room_style = style

    if hasattr(sesh, 'room_img_loaded') and sesh.room_img_loaded:
        display = updateItemDisplay(seshid)
        setSesh(seshid, sesh)
        return display
    else:
        setSesh(seshid, sesh)
        return sesh.updated_display

def updatePrice(evt: gr.SelectData, seshid):
    sesh = getSesh(seshid)
    print('updatePrice: ', type(evt.value), evt.value)
    price = evt.value if evt.value else sesh.price
    sesh.price = price


    if hasattr(sesh, 'room_img_loaded') and sesh.room_img_loaded:
        display = updateItemDisplay(seshid)
        setSesh(seshid, sesh)
        return display
    else:
        setSesh(seshid, sesh)
        return sesh.updated_display


def updateBedsize(evt: gr.SelectData, seshid):
    sesh = getSesh(seshid)
    bedsize = evt.value if evt.value else sesh.bedsize 
    sesh.bedsize = bedsize 


    if hasattr(sesh, 'room_img_loaded') and sesh.room_img_loaded:
        display = updateItemDisplay(seshid)
        setSesh(seshid, sesh)
        return display
    else:
        setSesh(seshid, sesh)
        return sesh.updated_display


#sesh.palettes_data
def updateColors(evt: gr.SelectData, seshid):
    sesh = getSesh(seshid)
    Paletteid = evt.value['caption'] if evt.value['caption'] else '0'
    sesh.Paletteid = evt.value['caption']
    sesh.Palette_ids[sesh.current_img_signature] = Paletteid 
    sesh.Palette_img = np.zeros((200,200,3)).astype(np.uint8)
    sesh.Palette_img[:50,:] = sesh.palettes_data[sesh.Paletteid][0]
    sesh.Palette_img[50:100,:] = sesh.palettes_data[sesh.Paletteid][1]
    sesh.Palette_img[100:150,:] = sesh.palettes_data[sesh.Paletteid][2]
    sesh.Palette_img[150:,:] = sesh.palettes_data[sesh.Paletteid][3]
    sesh.Palette_imgs[sesh.img_id] = sesh.Palette_img

    if hasattr(sesh, 'room_img_loaded') and sesh.room_img_loaded:
        display = updateItemDisplay(seshid, pallete_change=True)
        setSesh(seshid, sesh)
        return display
    else:
        setSesh(seshid, sesh)
        return sesh.updated_display



 
#Palettes_displayed, Palettes

def makePalettes(evt: gr.SelectData, seshid):
    sesh = getSesh(seshid)
    print('makePalettes called: ', seshid, sesh.seshid, sesh.Palettes_displayed.keys())
    sesh.img_id = sesh.current_img_signature = evt.value['caption'] if evt.value['caption'] else sesh.current_img_signature
    if sesh.current_img_signature in sesh.Palettes_displayed:
        print('makePalettes img found: ', seshid, sesh.seshid)
        print('makePalettes img sig in sesh.Palettes_displayed--updating and returning: ', evt.value['caption'], sesh.current_img_signature, sesh.img_id, sesh.Palettes_displayed.keys())
        display = updateItemDisplay(seshid)
        return sesh.Palettes_displayed[sesh.current_img_signature], sesh.img_data[sesh.current_img_signature], display
    print('makePalettes check1: ')
    img = sesh.img_data[sesh.img_id]
    imgq = img // 48 * 48
    Palette_out = []
    Palette_accounting = []
    clr_counts = {}
    for i in range(imgq.shape[0]):
        for j in range(imgq.shape[1]):
            clr = tuple(imgq[i,j])
            if clr not in clr_counts:
                clr_counts[clr] = 0
            clr_counts[clr] += 1
    clr_counts_ = {v:k for k,v in clr_counts.items()}
    counts_srtd = sorted(clr_counts_)[::-1]
    #counts_srtd_rgb = [clr_counts_[i] for i in counts_srtd[:4]]
    counts_srtd_rgb = [[int(val) for val in clr_counts_[i]] for i in counts_srtd[:4]]
    #bestclr_keys = [color_maps[color_maps_keys[getBestMatch(color_maps_keys, rgb)]] for rgb in counts_srtd_rgb]
    dark_light_bool = int(np.sum(counts_srtd_rgb)//12//128)
    Palettes = {}
    i = 0
    print('makePalettes check2: ')
    #print('bestclr_keys: ', bestclr_keys)
    url = 'https://dreamdemo.pythonanywhere.com/palletes'
    #valid_data = {'seshid': str(sesh.seshid), 'img_id':str(sesh.img_id), 'dark_light_bool':str(dark_light_bool), 'bestclr_keys':bestclr_keys} 
    #valid_data = {'seshid': str(sesh.seshid), 'img_id':str(sesh.img_id), 'dark_light_bool':str(dark_light_bool), 'counts_srtd_rgb':counts_srtd_rgb} 
    valid_data = {'seshid': str(seshid), 'img_id':str(sesh.img_id), 'dark_light_bool':str(dark_light_bool), 'counts_srtd_rgb':counts_srtd_rgb} 
    #print('MAKE PALLETE SESHID: ', seshid, sesh.seshid)
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    #print('json requests response: ', str({k:(type(v), None if type(v) != type(dict({})) or not v else (type(list(v.items())[0][0]), type(list(v.items())[0][1]))) for k,v in valid_data.items()}))
    #print('json requests response: ', str({k:(type(v), None if type(v) != type(dict({})) or not v else (type(list(v.items())[0][0]), type(list(v.items())[0][1]))) for k,v in data.items()}))
    r = requests.post(url, data=json.dumps(valid_data), headers=headers)
    #jsondata = r.json()
    jsondata = json.loads(r.content)
    print('makePalettes img sig was not in sesh.Palettes_displayed: ', sesh.Palettes_displayed.keys())
    #print('\npalette json requests response: ', str(r.content), '\njson data: ', jsondata )

    print('makePalettes check3: ')
    Palette_out = []
    palettes_data = [cdata[0] for cdata in jsondata['got']]
    gcounts = [sum([c[1] for c in cdata]) for cdata in palettes_data]
    gsrt = np.argsort(gcounts)[::-1]
    palettes_data = [palettes_data[i] for i in gsrt]
    sesh.palettes_data = {str(idx+1):cdata for idx,cdata in enumerate(palettes_data)}
    #print('palettes_data: ', type(palettes_data), palettes_data)
    for idx,cdata in enumerate(palettes_data):                
        newimg = np.zeros((200,200,3))
        newimg[:50,:] = cdata[0]
        newimg[50:100,:] = cdata[1]
        newimg[100:150,:] = cdata[2]
        newimg[150:,:] = cdata[3]
        Palette_out.append((newimg.astype(np.uint8), str(idx+1)))


    sesh.Paletteid = '1' #str(len(palettes_data)-1)
    sesh.Palette_ids[sesh.current_img_signature] = sesh.Paletteid 
    sesh.Palette_img = np.zeros((200,200,3)).astype(np.uint8)
    sesh.Palette_img[:50,:] = palettes_data[0][0]
    sesh.Palette_img[50:100,:] = palettes_data[0][1]
    sesh.Palette_img[100:150,:] = palettes_data[0][2]
    sesh.Palette_img[150:,:] = palettes_data[0][3]

    sesh.Palette_imgs[sesh.img_id] = sesh.Palette_img
    display = updateItemDisplay(seshid)
    print('makePalettes check4: ')
    sesh.Palettes_displayed[sesh.current_img_signature] = Palette_out

    sesh.room_img_loaded = True
    setSesh(seshid, sesh)

    return Palette_out, sesh.img_data[sesh.img_id], display

#directory 
def set_Palette(evt: gr.SelectData, seshid):
    sesh = getSesh(seshid)
    sesh.Paletteid = evt.value['caption']
    sesh.Palette_img = np.zeros((200,200,3)).astype(np.uint8)
    sesh.Palette_img[:50,:] = sesh.Palettes[sesh.img_id][sesh.Paletteid][0][0]
    sesh.Palette_img[50:100,:] = sesh.Palettes[sesh.img_id][sesh.Paletteid][0][1]
    sesh.Palette_img[100:150,:] = sesh.Palettes[sesh.img_id][sesh.Paletteid][0][2]
    sesh.Palette_img[150:,:] = sesh.Palettes[sesh.img_id][sesh.Paletteid][0][3]

    sesh.Palette_imgs[sesh.img_id] = sesh.Palette_img
    sesh.Palette_ids[sesh.img_id] = sesh.Paletteid
    setSesh(seshid, sesh)


def set_style(evt: gr.SelectData, seshid):
    sesh = getSesh(seshid)
    label = evt.value['caption'].lower().split()[0]
    sesh.room_type = label
    images = [(v['bedroom'] if label == 'bedroom' else v['living room'], k) for k,v in styles_images.items()]
    sesh.items = items = bed_layout_new if label == 'bedroom' else living_layout_new 
    print('set_style: ', items)

    sesh.filtered_files_room[sesh.img_id] = {color: [f for f in cfiles if any([(lambda substrs, f: substrs and substrs[0].lower() in f.lower() and (len(substrs)==1 or substrs[1] in f.lower()))(item.replace('-', ' ').split(), f) for item in items])] for color,cfiles in sesh.filtered_files[sesh.img_id].items()}

    room_items_imgs_tuples = [((sesh.Palette_img if item == 'Palette' else sesh.img_data[sesh.img_id]) if item in ['Palette', 'Living Room', 'Bedroom'] else room_item_placeholder_images_dict['BEDROOM FURNITURE' if label == 'bedroom' else 'LIVING ROOM FURNITURE'][item], item) for item in items]

    setSesh(seshid, sesh)
    return images, gr.Radio(['Full', 'Queen', 'King'], value='Full', label='Bed Size', interactive=True, visible=True) if label == 'bedroom' else gr.Radio(visible=False), gr.Gallery(room_items_imgs_tuples, label='Room Items', columns=5) 


def applyStyle(evt: gr.SelectData, seshid):
    sesh = getSesh(seshid)
    design_style = evt.value['caption'].lower().split()[0]

    sesh.filtered_files_style[sesh.img_id] = {color: [f for f in cfiles if any([(lambda substrs, f: substrs and substrs[0].lower() in f.lower() and (len(substrs)==1 or substrs[1] in f.lower()))(substr.replace('-', ' ').split(), f) for substr in design_style.split()])] for color,cfiles in sesh.filtered_files_room[sesh.img_id].items()}

    
    room_items_imgs_tuples = []
    for item in sesh.items:
        for color,cfiles in sesh.filtered_files_style[sesh.img_id].items():
            for f in cfiles:
                if item.split()[-1].lower() in f:
                    if item not in sesh.activated_items[str(img.sum())]:
                        sesh.activated_items[sesh.img_id][item] = []
                    with open(directory+f, 'r') as openfile:
                        data = json.load(openfile)
                    sesh.activated_items[sesh.img_id][item] += data

    room_items_imgs_tuples = [((sesh.Palette_img if item == 'Palette' else sesh.img_data[sesh.img_id]) if item in ['Palette', 'Living Room', 'Bedroom'] else room_item_placeholder_images_dict['BEDROOM FURNITURE' if sesh.room_type == 'bedroom' else 'LIVING ROOM FURNITURE'][item], item) for item in sesh.items]

    setSesh(seshid, sesh)
    return gr.Gallery(room_items_imgs_tuples, label='Room Items', columns=5) 


def uploadToScriptGenPromise(frmt, seshid):
    sesh = getSesh(seshid)
    if True:
        formats = ['Youtube Long-Form', 'Youtube Short-Form', 'Facebook Long-Form', 'Instagram Reel', 'Tik Tok', 'LinkedIn']
        #formats = [frmt]
        number_of_items = [7, 3, 7, 3, 3, 7]
        urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature]  if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
        #urls = ['https://dreamdemo.pythonanywhere.com/scriptgen_promise' for _ in range(len(formats))]
        #headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        item_locator_data = [[sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
        items = [[data[1] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
        idxs = [list(range(len(items[0]))) for i,_ in enumerate(formats)]
        process = {}
        print('*-/*/-*-DDSDSDSSD roomItemClick:  scriptgen_promise items : ', items[0], idxs[0])
        for i,_ in enumerate(formats):
            if formats[i] != frmt or (formats[i] in sesh.frmt_idxs_maps[sesh.current_img_signature] and all([tupe in item_locator_data[0] for tupe in sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]]])):
                process[i] = False
                continue
            np.random.shuffle(idxs[i])
            print('*-/*/-*-DDSDSDSSD roomItemClick:  scriptgen_promise number_of_items 1: ', formats[i], frmt, number_of_items[i], idxs[i])
            idxs[i] = idxs[i][:number_of_items[i]]
            sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]] = [item_locator_data[i][idx] for idx in idxs[i]]
            sesh.frmt_id_maps[sesh.current_img_signature][formats[i]] = str(time.time())
            process[i] = True
            time.sleep(.001)
            print('*-/*/-*-DDSDSDSSD roomItemClick:  scriptgen_promise number_of_items 2: ', number_of_items[i], idxs[i])
        #json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data, 'gen_uid': i, 'responses':responses, 'items': items}) for i,fmt in enumerate(formats)]
        #json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'idxs':idxs[i][:number_of_items[i]], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data[i], 'gen_uid': sesh.frmt_id_maps[sesh.current_img_signature][formats[i]], 'seshid':seshid, 'items': items[i]}) for i,fmt in enumerate(formats) if process[i]]
        json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'idxs':idxs[i], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data[i], 'gen_uid': sesh.frmt_id_maps[sesh.current_img_signature][formats[i]], 'seshid':seshid, 'items': items[i]}) for i,fmt in enumerate(formats) if process[i]]
        if not json_data:
            setSesh(seshid, sesh)
            return 
        urls = ['https://dreamdemo.pythonanywhere.com/scriptgen_promise' for i in range(len(formats)) if process[i]]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(formats) if process[i]]
        print('*-/*/-*-roomItemClick -- processed: ', len(json_data), [(f,process[i], idxs[i]) for i,f in enumerate(formats)])
        responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
        #responses = asyncio.run(main_post(urls, headers, json_data, timeout=3))
        print('*-/*/-*-roomItemClick: dumped scriptgen_promise: ', responses)
    setSesh(seshid, sesh)

def uploadStoreShop(seshid):
    sesh = getSesh(seshid)
    if True:
        urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature]  if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
        sesh.responses = asyncio.run(main(urls))
        urls = ['https://dreamdemo.pythonanywhere.com/store_shop' for _ in range(len(urls))]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        responses = [r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]
        item_locator_data = [sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']]
        json_data = [json.dumps({'response': responses[i], 'item_locator_data': item_locator_data[i]}) for i,url in enumerate(urls)]
        responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
    setSesh(seshid, sesh)

def roomItemClick(evt: gr.SelectData, seshid):
    sesh = getSesh(seshid)
    if 'SESHID' in all_sesh.sessions:
        del all_sesh.sessions['SESHID']
    selection = evt.value['caption'].lower()
    seshidtype = '...'+str(type(seshid))+ '...'
    seshid_ = '...'+str(seshid)+ '...'
    seshid = str(time.time()) if not seshid or seshid == 'SESHID' else seshid
    sesh.clicked_displayed_product = evt.value['caption']
    setSesh(seshid, sesh)
    if selection == 'palette':
        """urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature]  if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
        sesh.responses = asyncio.run(main(urls))
        urls = ['https://dreamdemo.pythonanywhere.com/store_shop' for _ in range(len(urls))]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        responses = [r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]
        item_locator_data = [sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']]
        json_data = [json.dumps({'response': responses[i], 'item_locator_data': item_locator_data[i]}) for i,url in enumerate(urls)]
        responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
        print('*-/*/-*-roomItemClick: dumped store_shop: ', item_locator_data)
        
        formats = ['Youtube Long-Form', 'Youtube Short-Form', 'Facebook Long-Form', 'Instagram Reel', 'Tiktok', 'LinkedIn']
        number_of_items = [7, 3, 7, 3, 3, 7]
        urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature]  if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
        sesh.responses = asyncio.run(main(urls))
        #urls = ['https://dreamdemo.pythonanywhere.com/scriptgen_promise' for _ in range(len(formats))]
        #headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        responses = [[r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses] for _ in range(len(formats))]
        item_locator_data = [[sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
        items = [[data[1] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
        idxs = [list(range(len(items))) for i,_ in enumerate(formats)]
        process = {}
        for i,_ in enumerate(formats):
            if formats[i] in sesh.frmt_idxs_maps[sesh.current_img_signature] and all([tupe in item_locator_data[0] for tupe in sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]]]):
                process[i] = False
            np.random.shuffle(idxs[i])
            idxs[i] = idxs[i][:number_of_items[i]]
            sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]] = [item_locator_data[i][idx] for idx in idxs[i]]
            sesh.frmt_id_maps[sesh.current_img_signature][formats[i]] = str(time.time())
            process[i] = True
            time.sleep(.001)
        #json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data, 'gen_uid': i, 'responses':responses, 'items': items}) for i,fmt in enumerate(formats)]
        json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'idxs':idxs[i][:number_of_items[i]], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data[i], 'gen_uid': sesh.frmt_id_maps[sesh.current_img_signature][formats[i]], 'seshid':seshid, 'items': items[i]}) for i,fmt in enumerate(formats) if process[i]]
        urls = ['https://dreamdemo.pythonanywhere.com/scriptgen_promise' for i in range(len(formats)) if process[i]]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(formats) if process[i]]
        print('*-/*/-*-roomItemClick -- processed: ', len(json_data), [(f,process[i], idxs[i]) for i,f in enumerate(formats)])
        responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
        #responses = asyncio.run(main_post(urls, headers, json_data, timeout=3))
        print('*-/*/-*-roomItemClick: dumped scriptgen_promise: ', responses)"""
        return gr.Column(scale=4), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.Gallery(visible=False), gr.Label('Dream Home: As Quick As A Click. As Simple As Shopping.', label='Sponsors'), gr.update(visible=bool(0)), seshid
    elif selection in ['living room', 'bedroom']:
        return gr.Column(scale=4), gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.update(visible=bool(0)), gr.Gallery(visible=False), gr.Label('Dream Home: As Quick As A Click. As Simple As Shopping.', label='Sponsors', visible=True) if sesh.summary_closed else gr.Label('Dream Home: As Quick As A Click. As Simple As Shopping.', label='Sponsors', visible=False), gr.update(visible=bool(0)) if sesh.summary_closed else gr.update(visible=bool(1)), seshid
    else:
        try:
            item = evt.value['caption']
            replacements = [(product['img'] if itemi in sesh.inbudget[sesh.current_img_signature][item] else sesh.default_img, product['price']) for itemi,product in enumerate(sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid][item])]
            return gr.Column(scale=4), gr.update(visible=bool(1)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.Gallery(replacements, 'Item Replacements', height=150, rows=1, columns=7, visible=True, interactive=True), gr.Label(visible=False), gr.update(visible=bool(0)), seshid
        except:
            return gr.Column(scale=5), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.Gallery([], 'Item Replacements', rows=1, columns=7, visible=False, interactive=True), gr.Label(visible=True), gr.update(visible=bool(0)), seshid


def closeSidePanel(seshid):
    sesh = getSesh(seshid)
    setSesh(seshid, sesh)
    return gr.Column(scale=5), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.Label('No Item Selected', label='Merchant'), gr.Gallery(visible=False), gr.Label('Dream Home: As Quick As A Click. As Simple As Shopping.', label='Sponsors', visible=True), gr.update(visible=bool(0))



def productClick(evt: gr.SelectData, seshid):
    sesh = getSesh(seshid)
    if not sesh.clicked_displayed_product:
        return gr.Label('No Item Selected', label='Merchant')
    product_idx = evt.index
    sesh.product_idx = evt.index
    product = sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid][sesh.clicked_displayed_product][product_idx]
    sesh.product = product 
    lookup_idxs = sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid][sesh.clicked_displayed_product][product_idx]
    sesh.clicked_product_data = {'item': sesh.clicked_displayed_product, 'lookup_idxs': lookup_idxs}
    setSesh(seshid, sesh)
    return gr.Label(product['store'].split('-')[0], label='Merchant')

def replaceProduct(seshid):
    sesh = getSesh(seshid)
    item_idx = sesh.items.index(sesh.clicked_displayed_product)
    sesh.updated_display[item_idx] = (sesh.product['img'], sesh.clicked_displayed_product)
    #sesh.display_items[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid][item_idx] = (sesh.product_idx, sesh.clicked_displayed_product) if sesh.product_idx in sesh.inbudget[sesh.current_img_signature][sesh.clicked_displayed_product] else sesh.display_items[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid][item_idx]
    sesh.display_items_[sesh.current_img_signature][item_idx] = (sesh.product_idx, sesh.clicked_displayed_product) if sesh.product_idx in sesh.inbudget[sesh.current_img_signature][sesh.clicked_displayed_product] else sesh.display_items_[sesh.current_img_signature][item_idx]

    for item_dataidx in sesh.display_items_[sesh.current_img_signature]:
        if item_dataidx[0] != -1:
            store = sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][item_dataidx[1]][item_dataidx[0]]['store']
            writeForStoreProcessing(store, sesh.zipcode)

    #sesh.summary[sesh.current_img_signature] = [() if itemidx_item[1] in ['Palette', 'Living Room', 'Bedroom'] else (itemidx_item[1], sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid][itemidx_item[1]][itemidx_item[0]]) for itemidx_item in sesh.display_items[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid]]
    sesh.summary[sesh.current_img_signature] = [() if itemidx_item[1] in ['Palette', 'Living Room', 'Bedroom'] else (itemidx_item[1], sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid][itemidx_item[1]][itemidx_item[0]]) for itemidx_item in sesh.display_items_[sesh.current_img_signature]]
    summarisePerStore(seshid)

    #print('replaceProduct: ', sesh.product_idx, sesh.clicked_displayed_product, sesh.product_idx in sesh.inbudget[sesh.current_img_signature][sesh.clicked_displayed_product], sesh.display_items_, sum([float(item_product[1]['price'].replace('$', '').replace(',', '')) for img in sesh.summary for item_product in sesh.summary[img] if item_product]))

    """if True:
        urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature]  if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
        sesh.responses = asyncio.run(main(urls))
        urls = ['https://dreamdemo.pythonanywhere.com/store_shop' for _ in range(len(urls))]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        responses = [r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]
        item_locator_data = [sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']]
        json_data = [json.dumps({'response': responses[i], 'item_locator_data': item_locator_data[i]}) for i,url in enumerate(urls)]
        responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
        print('*-/*/-*-replaceProduct: dumped store_shop: ', item_locator_data)
        
        formats = ['Youtube Long-Form', 'Youtube Short-Form', 'Facebook Long-Form', 'Instagram Reel', 'Tiktok', 'LinkedIn']
        number_of_items = [7, 3, 7, 3, 3, 7]
        urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature]  if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
        sesh.responses = asyncio.run(main(urls))
        #urls = ['https://dreamdemo.pythonanywhere.com/scriptgen_promise' for _ in range(len(formats))]
        #headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        responses = [[r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses] for _ in range(len(formats))]
        item_locator_data = [[sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
        items = [[data[1] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
        idxs = [list(range(len(items))) for i,_ in enumerate(formats)]
        process = {}
        for i,_ in enumerate(formats):
            print('*-/*/-*-replaceProduct -- prep: ', formats[i], formats[i] in sesh.frmt_idxs_maps[sesh.current_img_signature], all([tupe in item_locator_data[0] for tupe in sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]]]), sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]] if formats[i] in sesh.frmt_idxs_maps[sesh.current_img_signature] else None, '*****', item_locator_data[0])
            if formats[i] in sesh.frmt_idxs_maps[sesh.current_img_signature] and all([tupe in item_locator_data[0] for tupe in sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]]]):
                process[i] = False
                continue
            np.random.shuffle(idxs[i])
            idxs[i] = idxs[i][:number_of_items[i]]
            sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]] = [item_locator_data[i][idx] for idx in idxs[i]]
            sesh.frmt_id_maps[sesh.current_img_signature][formats[i]] = str(time.time())
            process[i] = True
            time.sleep(.001)
        json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'idxs':idxs[i][:number_of_items[i]], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data[i], 'gen_uid': sesh.frmt_id_maps[sesh.current_img_signature][formats[i]], 'seshid':seshid, 'items': items[i]}) for i,fmt in enumerate(formats) if process[i]]
        urls = ['https://dreamdemo.pythonanywhere.com/scriptgen_promise' for i in range(len(formats)) if process[i]]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(formats) if process[i]]
        print('*-/*/-*-replaceProduct -- processed: ', len(json_data), [(f,process[i], idxs[i]) for i,f in enumerate(formats)])
        if json_data: 
            responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
            #responses = asyncio.run(main_post(urls, headers, json_data, timeout=3))
        else:
            responses = []
        print('*-/*/-*-replaceProduct: dumped scriptgen_promise: ', responses)"""
    
    setSesh(seshid, sesh)
    return gr.Column(scale=5), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.Label('No Item Selected', label='Merchant'), gr.Gallery(visible=False), gr.Label('Dream Home: As Quick As A Click. As Simple As Shopping.', label='Sponsors', visible=True), gr.Gallery(sesh.updated_display, label='Room Items', columns=5)


def selectMerchantItemCountAndTotal(store, seshid):
    sesh = getSesh(seshid)
    num_items = 0
    total = 0
    for item in sesh.summary_joined[store]:
        for description in sesh.summary_joined[store][item]:
            price = sesh.summary_joined[store][item][description]['product_dict']['price']
            count = sesh.summary_joined[store][item][description]['count']
            total += float(price.replace('$', '').replace(',', '')) * count
            num_items += count 
    setSesh(seshid, sesh)
    return num_items, total

def selectMerchantItemCountAndTotal(store, seshid):
    sesh = getSesh(seshid)
    num_items = 0
    total = 0
    for item in sesh.summary_joined[store]:
        price = sesh.summary_joined[store][item]['product_dict']['price']
        count = sesh.summary_joined[store][item]['count']
        total += float(price.replace('$', '').replace(',', '')) * count
        num_items += count 
    setSesh(seshid, sesh)
    return num_items, total

from huggingface_hub import InferenceClient


def retrieveProcessedStoreData(store, seshid):
    sesh = getSesh(seshid)
    """if os.path.isfile(f'C:\\Users\\Wayne\\Documents\\store_processors\\completed_{store+sesh.zipcode}.json'):
        with open(f'C:\\Users\\Wayne\\Documents\\store_processors\\completed_{store+sesh.zipcode}.json', 'r') as file:
            data = json.load(file)
        return data['store_data']
    else:
        return []"""
    return []
    setSesh(seshid, sesh)
        
def summaryClick(seshid):
    sesh = getSesh(seshid)
    #from pathlib import Path
    sesh.counts_totals = {store:selectMerchantItemCountAndTotal(store, seshid) for store in sesh.summary_joined}
    all_counts = str(sum([ct[0] for store,ct in sesh.counts_totals.items()]))
    all_totals = sum([ct[1] for store,ct in sesh.counts_totals.items()])
    print('summaryClick -- counts_totals: ', all_counts, all_totals, sesh.counts_totals) 
    if sesh.summary_closed:
        sesh.summary_closed = False
        store_data = {store: (lambda data: '' if not data or store.split()[0].lower() not in data[0]['STORE'].lower() or 'ZIPCODE' not in data[0] or 'PHONE' not in data[0] or 'STATE' not in data[0] or data[0]['STATE'] != sesh.state or len(data[0]['STATE']) != 2 or len(data[0]['PHONE']) != 12 else '\n'.join(['\n'.join([('\t\t\t'+key if key.lower() != 'store' else '\t\tNAME')+': '+value for key,value in d.items()]) for d in data]))(retrieveProcessedStoreData(store, seshid)) for store in sesh.summary_joined}
        #store_data = {store: (lambda data: '' if not data or 'zipcode' not in data[0] else '\n'.join([str(d) for d in data]))(retrieveProcessedStoreData(store, seshid)) for store in sesh.summary_joined}
        item_summary_data = '\n\n'.join(['STORE: '+store+'\n'+('\tLOCATIONS: N/A' if not store_data[store] else '\tLOCATIONS: \n'+store_data[store])+''.join(['\n\tPRODUCT: '+ product +'\n\tPRICE: '+pd_count['product_dict']['price']+'\n\tSOURCE: '+pd_count['product_dict']['href'] for product,pd_count in sesh.summary_joined[store].items()]) for store in sesh.summary_joined]) 
        print('store summary: ', {store: retrieveProcessedStoreData(store, seshid) for store in sesh.summary_joined})
        setSesh(seshid, sesh)
        return gr.Button('Suppress Summary'), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.Dropdown(list(sesh.summary_joined), label='Merchants', interactive=True), gr.Label('All', label='Merchant'), gr.Label(all_counts, label='Number of Items'), gr.Label('$'+str(np.round(all_totals, 2)), label='Total'), item_summary_data 

#'\n\n'.join(['Store: '+store+'\n\n'+'\n\n'.join(['\n\tProduct: '+ product +'\n\tPrice: '+pd_count['product_dict']['price']+'\n\tSource: '+pd_count['product_dict']['href'] for product,pd_count in sesh.summary_joined[store].items()]) for store in sesh.summary_joined]) 
    else:
        sesh.summary_closed = True
        setSesh(seshid, sesh)
        return gr.Button('Summarise'), gr.update(visible=bool(1)), gr.update(visible=bool(1)), gr.update(visible=bool(1)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.update(visible=bool(0)), gr.Dropdown(), gr.Label(), gr.Label(), gr.Label(), ''


def selectMerchantProduct(evt: gr.SelectData, seshid):
    sesh = getSesh(seshid)
    store = evt.value
    sesh.summary_store = store

    #print('selectMerchantProduct -- counts_totals: ', counts_totals) 
    setSesh(seshid, sesh)
    return gr.Dropdown(list(sesh.summary_joined[store]), label='Items', interactive=True), gr.Label(sesh.summary_store if sesh.summary_store else 'All', label='Merchant'), gr.Label(str(sesh.counts_totals[store][0]), label='Number of Items'), gr.Label('$'+str(np.round(sesh.counts_totals[store][1], 2)), label='Total')


def getVizText(html):
    from bs4 import BeautifulSoup, NavigableString, Tag
    soup = BeautifulSoup(str(html), 'html.parser')
    viz_text = [tag.text for tag in soup.find_all() if tag.text and len(tag.find_all())==0 and tag.name not in ['style', 'script', 'head', 'title', 'meta', '[document]'] and not isinstance(tag, NavigableString)]
    viz_text_str = '...'.join(viz_text).replace('\\n', '').replace('\\t', '').replace('\n', '').replace('\t', '')
    return viz_text_str

def findShoppingRelevantTerms(html):
    if not html:
        return {}
    if True: #try:
        start = time.time()
        print('findShoppingRelevantTerms: getting viztext')
        viz_text_str = getVizText(str(html.decode("utf-8")))
        print('findShoppingRelevantTerms -- got viztext: ', time.time()-start)
        search_terms = [' off ', ' availability ', ' available ', ' delivery ', ' deliver ', ' ship ', ' shipping ', ' return ', ' returns ', ' exchange ', ' exchanges ', ' material ', ' materials ']
        print('findShoppingRelevantTerms: getting found_terms')
        start = time.time()
        #found_terms = {t:(lambda text, term_loc: text[term_loc-200:term_loc+300])(viz_text_str, viz_text_str.lower().find(t.lower())) for t in search_terms if t in viz_text_str}
        found_terms = {t:(lambda text, term_loc: text[term_loc-500:term_loc+500])(viz_text_str, viz_text_str.lower().find(t.lower())) for t in search_terms if (lambda text, term_loc: (t != ' off ' and t in text[term_loc-500:term_loc+500]) or (t == ' off ' and (t in text[term_loc-500:term_loc+500] or ' off...' in text[term_loc-500:term_loc+500]) and ('%' in text[term_loc-500:term_loc+500] or '$' in text[term_loc-500:term_loc+500])))(viz_text_str, viz_text_str.lower().find(t.lower()))}
        print('findShoppingRelevantTerms -- got found_terms: ', time.time()-start)
        return found_terms
    else: #except:
        return {}

def changeSummaryFilter(evt: gr.SelectData, seshid):
    sesh = getSesh(seshid)
    summary_radio = evt.value
    print('changeSummaryFilter: ', summary_radio)
    sesh.summary_radio = summary_radio 
    all_counts = str(sum([ct[0] for store,ct in sesh.counts_totals.items()]))
    all_totals = sum([ct[1] for store,ct in sesh.counts_totals.items()])
    #if summary_radio == 'Complete' or not hasattr(sesh, 'summary_store'):
    if summary_radio == 'Complete':
        print('changeSummaryFilter: in Complete')
        setSesh(seshid, sesh)
        return gr.Label('All', label='Merchant'), gr.Label(all_counts, label='Number of Items'), gr.Label('$'+str(np.round(all_totals, 2)), label='Total'), gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.update(visible=bool(1)), gr.update(visible=bool(0))
    elif summary_radio == 'Script':
        uploadStoreShop(seshid)
        #textgen for general audience, things to look out for or be aware of
        """product_pd_counts = [(product,pd_count) for store in sesh.summary_joined for product,pd_count in sesh.summary_joined[store].items()]
        urls = [product_pd_count[1]['product_dict']['href'] for product_pd_count in product_pd_counts]
        start = time.time()
        responses = asyncio.run(main(urls))
        end = time.time()
        lapse = end-start
        #fdsdweesdd = findShoppingRelevantTerms(responses[0])
        #print('changeSummaryFilter -- in Script: ', lapse, fdsdweesdd)
        start = time.time()
        found_terms_4_room_items = [(product_pd_counts[ir][0], findShoppingRelevantTerms(r)) for ir,r in enumerate(responses)]

        url = 'https://dreamdemo.pythonanywhere.com/shopping'
        valid_data = {'product_pd_counts': product_pd_counts, 'responses':responses} 
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        r = requests.post(url, data=json.dumps(valid_data), headers=headers)
        jsondata = json.loads(r.content)
        print('changeSummaryFilter: ', jsondata)
        
        del responses
        #dsdsd = 'ITEM TOPICS: \n\n'+'\n\n'.join(['ITEM : '+data[0].upper() + f'\n\n{data[0].upper()} TOPICS: \n'+'\n\n'.join(['Topic: '+term[1:-1].upper()+'\n...'+text for term,text in data[1].items()]) for idx,data in enumerate(found_terms_4_room_items ) if data[1]])
        start = time.time()
        topics = 'ITEM TOPICS: \n\n'+'\n\n'.join(['\n\n'.join([f'{data[0].upper()} TOPIC: '+term[1:-1].upper()+'\n...'+text for term,text in data[1].items()]) for idx,data in enumerate(found_terms_4_room_items ) if data[1]])
        descriptions = '\n\n'+'\n\n'.join(['Store: '+store+'\n\n'.join(['\n\tProduct: '+ product.upper() +'\n\tDescription: '+pd_count['product_dict']['description']+'\n\tPrice: '+pd_count['product_dict']['price'] for product,pd_count in sesh.summary_joined[store].items()]) for store in sesh.summary_joined]) 
        prompt = topics + "\n\nITEMS: \n\n"+descriptions+"\n\nTask: Referencing the ITEMS provided, create an audio script about shopping to decorate a room, writing to prompt the listener for their feedback as to whether the items chosen are choices they might have made; where applicable, incorporate the corresponding ITEM TOPICS to the ITEM being written about, and do so in a way that is informing the listener of what they might expect during the ordering process -- reference the ITEM TOPICS in a fun way as if you are engaging in small talk, making remarks to the respective ITEM TOPICS in a 'just a heads up' tangent and then getting back on script. Write in the past tense, like we have already decorated and are now reviewing the items chosen to outfit the room, speculating as to the listener's stance on the items chosen, whether they would like the ITEM being spoken about and why (be creative, thinking of random reasons the listener would or would not like the ITEM chosen). Write in an informal style. Keep in mind, the items have NOT been ordered and shipped yet." 

        items_prepped = ['\n\n'.join([f'ITEM: {data[0].upper()}\n\n'+f'{data[0].upper()} STORE: '+product_pd_counts[idx][1]['product_dict']['store']+'\n\n'+f'{data[0].upper()} DESCRIPTION: '+product_pd_counts[idx][1]['product_dict']['description']+'\n\n'+'\n\n'.join([f'{data[0].upper()} TOPIC: '+(term[1:-1].upper() if term[1:-1] != 'ship' else 'SHIPPING')+'\n...'+text for term,text in data[1].items()])]) for idx,data in enumerate(found_terms_4_room_items)]

        #print('indivij prep: ', items_prepped , len(items_prepped))
        templates = {0:['For ITEM, we went with the ITEM DESCRIPTION. SPECULATED RESPONSE.', 'SPECULATED RESPONSE, so for ITEM we went with the ITEM DESCRIPTION.'], 1:['For ITEM, we went with the ITEM DESCRIPTION. ITEM TOPIC. SPECULATED RESPONSE.', 'SPECULATED RESPONSE, so for ITEM we went with the ITEM DESCRIPTION. ITEM TOPIC.'], 2:['For ITEM, we went with the ITEM DESCRIPTION. ITEM TOPICS. SPECULATED RESPONSE.', 'SPECULATED RESPONSE, so for ITEM we went with the ITEM DESCRIPTION. ITEM TOPICS.']}
        responses = []"""
        #for idx,data in enumerate(found_terms_4_room_items): 
            #template = templates[len(data[1]) if len(data[1])<2 else 2][np.random.choice([0,1])] 
            #prompt = items_prepped[idx]+'\n\nTEMPLATE: '+template+"\n\nTASK: adapt TEMPLATE using the ITEM/DESCRIPTION/STORE info provided, where SPECULATED RESPONSE is your creative guess as to the reader's stance on the items chosen, whether they would like the ITEM being written about and why (be creative, thinking of random reasons the reader would or would not like the ITEM chosen). Write from the perspective of reporting to someone who is considering purchasing a home and you are presenting different decorative options that might persuade them to buy the home; so, make sure your wording reflects this -- 'if you go with...', 'now keep in mind...', 'were you to purchase this home...' and the like are examples of how you might word things. You don't have to use these examples exactly, just word things similarly. Be creative."
            #if data[1]:
                #prompt += " Incorporate each ITEM TOPIC in a way that is a heads up for the reader to inform them of the purchase process and what they can expect. Reference the each ITEM TOPIC in a fun way as if you are engaging in small talk, making remarks to the respective ITEM TOPIC info in a 'just a heads up' tangent and then getting back on script."
            #prompt += f" This should read as a review of an item chosen for a room being furnished, but the item has NOT been purchased or shipped yet. Write in an informal style. And to clarify, you are writing AS a reviewer, FOR a prospective home buyer, ABOUT an item FROM a store, and the likely buying experience with them (the store); you are writing about decorating a {sesh.room_type}. "

            #if idx==0:
                #prompt += "Keep in mind this is the first of many items we are reviewing, so ensure your writing reflects the fact that this is just the first item being reported on."
            #elif idx==len(found_terms_4_room_items)-1:
                #prompt += "Keep in mind this is the last of many items we are reviewing, so ensure your writing reflects the fact that this is the final item being reported on and do a review wrap-up/send off for this particular room's decor review. Maybe begin by writing something along the lines of 'Okay lastly we have the...' or 'Well, our final item is...' or what have you jare examples of how you might word things. You don't have to use these examples exactly, just word things similarly. Be creative.."
            #else:
                #prompt += "Keep in mind this is one of many items we have already reviewed and one of other yet to be reviewed, so ensure your writing reflects the fact that this is just the next item being reported on. Maybe begin by writing something along the lines of 'Okay now we have...' or 'So next up is...' or what have you are examples of how you might word things. You don't have to use these examples exactly, just word things similarly. Be creative."

            #response = client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
            #response = response.replace("I know what you're thinking", np.random.choice(alarm3)).replace("I know what you are thinking", np.random.choice(alarm3))
            #print('script response: ', response)
            #responses.append(response)
            #time.sleep(.7)

        #response = client.text_generation('\n\n'.join(responses)+"\n\nTASK: summarize this script for a tiktok video about a prospective homebuyer decorating this {sesh.room_type} should they purchase the home. The review should cover the following topics: { ', '.join([data[0] for idx,data in enumerate(found_terms_4_room_items)])}", model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
        #print('\n\ntiktok response: ', response)
        #response = client.text_generation('\n\n'.join(responses)+"\n\nTASK: summarize this script for a youtube short about a prospective homebuyer decorating this {sesh.room_type} should they purchase the home. The review should cover the following topics: {', '.join([data[0] for idx,data in enumerate(found_terms_4_room_items)])}", model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
        #print('\n\nyoutube short response: ', response) #script response:

        #preprompt = 'ITEMS: \n\n'+'\n\n'.join(['\n\n'.join([f'ITEM: {data[0].upper()}\n\n'+f'{data[0].upper()} STORE: '+product_pd_counts[idx][1]['product_dict']['store']+'\n\n'+f'{data[0].upper()} DESCRIPTION: '+product_pd_counts[idx][1]['product_dict']['description']+'\n\n'+'\n\n'.join([f'{data[0].upper()} TOPIC: '+term[1:-1].upper()+'\n...'+text for term,text in data[1].items()])]) for idx,data in enumerate(found_terms_4_room_items)])

   
        #prompt = preprompt+"\n\nTask: Referencing the ITEMS provided -- each item DESCRIPTION, in particular -- create an audio script about shopping to decorate a room, writing to prompt the listener for their feedback as to whether the items chosen are choices they might have made; where applicable, incorporate the corresponding ITEM TOPICS to the item DESCRIPTION being written about, and do so in a way that is informing the listener of what they might expect during the ordering process. Reference the ITEM TOPICS in a fun way as if you are engaging in small talk, making remarks to the respective ITEM TOPIC in a 'just a heads up' tangent and then getting back on script. Write in the past tense, like we have already decorated and are now reviewing the items chosen to outfit the room, speculating as to the listener's stance on the items chosen, whether they would like the ITEM being spoken about and why (be creative, thinking of random reasons the listener would or would not like the ITEM chosen). Write in an informal style." 

        #end = time.time()
        setSesh(seshid, sesh)
        return gr.Label('All', label='Merchant'), gr.Label(all_counts, label='Number of Items'), gr.Label('$'+str(np.round(all_totals, 2)), label='Total'), gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.update(visible=bool(1)), gr.update(visible=bool(0))
    else: 
        setSesh(seshid, sesh)
        return gr.Label(sesh.summary_store if hasattr(sesh, 'summary_store') and sesh.summary_store else 'All', label='Merchant'), gr.Label(str(sesh.counts_totals[sesh.summary_store][0]) if hasattr(sesh, 'summary_store') and sesh.summary_store else '--', label='Number of Items'), gr.Label('$'+str(np.round(sesh.counts_totals[sesh.summary_store][1], 2)) if hasattr(sesh, 'summary_store') and sesh.summary_store else '--', label='Total'), gr.update(visible=bool(1)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(1))
 


def displaySource(evt: gr.SelectData, seshid):
    sesh = getSesh(seshid)
    product = evt.value
    sesh.summary_product = product 
    #sources = '\n\n'.join(['Price: '+pd_count['product_dict']['price']+'\n\nSource: '+pd_count['product_dict']['href'] for description_key,pd_count in sesh.summary_joined[sesh.summary_store][product].items()]) 
    sources = 'Price: '+sesh.summary_joined[sesh.summary_store][product]['product_dict']['price']+'\n\nSource: '+sesh.summary_joined[sesh.summary_store][product]['product_dict']['href']
    setSesh(seshid, sesh)
    return gr.Markdown(sources), gr.Number(value=sesh.summary_joined[sesh.summary_store][product]['count'], label='Item Count', minimum=0) 

def updateProductCount(count, seshid):
    sesh = getSesh(seshid)
    sesh.summary_joined[sesh.summary_store][sesh.summary_product]['count'] = count
    sesh.counts_totals = {store:selectMerchantItemCountAndTotal(store) for store in sesh.summary_joined}
    all_counts = str(sum([ct[0] for store,ct in sesh.counts_totals.items()]))
    all_totals = sum([ct[1] for store,ct in sesh.counts_totals.items()])

    setSesh(seshid, sesh)
    return gr.Label(str(sesh.counts_totals[sesh.summary_store][0]) if sesh.summary_store and sesh.summary_radio != 'Complete' else all_counts, label='Number of Items'), gr.Label('$'+str(np.round(sesh.counts_totals[sesh.summary_store][1], 2)) if sesh.summary_store and sesh.summary_radio != 'Complete' else '$'+str(np.round(all_totals, 2)), label='Total')

def updateBudget(budget_number, seshid):
    sesh = getSesh(seshid)
    sesh.budget_number = float(budget_number)
    #sesh.item_budgets = {img: {item: int(weight*sesh.budget_number) for item,weight in weights.items()} for img,weights in sesh.product_means_weights.items()}
    #print('updateBudget: ', sesh.budget_number, sesh.item_budgets)

    display = updateItemDisplay(seshid, budget=True)
    sesh.counts_totals = {store:selectMerchantItemCountAndTotal(store, seshid) for store in sesh.summary_joined}
    all_counts = str(sum([ct[0] for store,ct in sesh.counts_totals.items()]))
    all_totals = sum([ct[1] for store,ct in sesh.counts_totals.items()])
    setSesh(seshid, sesh)
    return display, gr.Label(all_counts, label='Number of Items'), gr.Label('$'+str(np.round(all_totals, 2)), label='Total')


def showPalettes(seshid):
    return gr.update(visible=bool(1)), gr.update(visible=bool(0)), gr.update(visible=bool(0))

def showScripts(seshid):
    return gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.update(visible=bool(0)), 'load'

def showJourneys(seshid):
    return gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(1))


templates = {0:['For ITEM, we went with the ITEM DESCRIPTION. SPECULATED RESPONSE.', 'SPECULATED RESPONSE, so for ITEM we went with the ITEM DESCRIPTION.'], 1:['For ITEM, we went with the ITEM DESCRIPTION. ITEM TOPIC. SPECULATED RESPONSE.', 'SPECULATED RESPONSE, so for ITEM we went with the ITEM DESCRIPTION. ITEM TOPIC.'], 2:['For ITEM, we went with the ITEM DESCRIPTION. ITEM TOPICS. SPECULATED RESPONSE.', 'SPECULATED RESPONSE, so for ITEM we went with the ITEM DESCRIPTION. ITEM TOPICS.']}

def makeItemPrompt(idx,data, seshid):
    sesh = getSesh(seshid)
    template = templates[len(data[1]) if len(data[1])<2 else 2][np.random.choice([0,1])] 
    prompt = sesh.items_prepped[idx]+'\n\nTEMPLATE: '+template+"\n\nTASK: adapt TEMPLATE using the ITEM/DESCRIPTION/STORE info provided, where SPECULATED RESPONSE is your creative guess as to the reader's stance on the items chosen, whether they would like the ITEM being written about and why (be creative, thinking of random reasons the reader would or would not like the ITEM chosen). Write from the perspective of reporting to someone who is considering purchasing a home and you are presenting different decorative options that might persuade them to buy the home; so, make sure your wording reflects this -- 'if you go with...', 'now keep in mind...', 'were you to purchase this home...' and the like are examples of how you might word things. You don't have to use these examples exactly, just word things similarly. Be creative."
    if data[1]:
        prompt += " Incorporate each ITEM TOPIC in a way that is a heads up for the reader to inform them of the purchase process and what they can expect. Reference the each ITEM TOPIC in a fun way as if you are engaging in small talk, making remarks to the respective ITEM TOPIC info in a 'just a heads up' tangent and then getting back on script."
        prompt += f" This should read as a review of an item chosen for a room being furnished, but the item has NOT been purchased or shipped yet. Write in an informal style. And to clarify, you are writing AS a reviewer, FOR a prospective home buyer, ABOUT an item FROM a store, and the likely buying experience with them (the store); you are writing about decorating a {sesh.room_type}. "

    if idx==0:
        prompt += "Keep in mind this is the first of many items we are reviewing, so ensure your writing reflects the fact that this is just the first item being reported on, including a proper intro to get started."
    elif idx==len(sesh.found_terms_4_room_items)-1:
        prompt += "Keep in mind this is the last of many items we are reviewing, so ensure your writing reflects the fact that this is the final item being reported on and do a review wrap-up/send off for this particular room's decor review. Maybe begin by writing something along the lines of 'Okay lastly we have the...' or 'Well, our final item is...' or what have you are examples of how you might word things. You don't have to use these examples exactly, just word things similarly. Be creative."
    else:
        prompt += "Keep in mind this is the one of many items we have already reviewed and one of other yet to be reviewed, so ensure your writing reflects the fact that this is just the next item being reported on. Maybe begin by writing something along the lines of 'Okay now we have...' or 'So next up is...' or what have you are examples of how you might word things. You don't have to use these examples exactly, just word things similarly. Be creative."
    setSesh(seshid, sesh)
    return prompt

def generateScriptForItem(idx,data, seshid):
    sesh = getSesh(seshid)
    prompt = makeItemPrompt(idx,data)
    #tg_response = client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
    tg_response = getTextGen(prompt)
    tg_response = tg_response.replace("I know what you're thinking", np.random.choice(alarm3)).replace("I know what you're thinking", np.random.choice(alarm3))
    sesh.tg_responses.append(tg_response)
    setSesh(seshid, sesh)

def generateScriptForItem(seshid):
    sesh = getSesh(seshid)
    url = 'https://dreamdemo.pythonanywhere.com/script_gen'
    valid_data = {'room_type': sesh.room_type, 'idx': sesh.found_terms_4_room_items_idx, 'gen_uid': sesh.gen_uid} 
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    r = requests.post(url, data=json.dumps(valid_data), headers=headers)
    jsondata = json.loads(r.content)
    tg_response = jsondata['response']
    print('generateScriptForItem from endpoint: ', tg_response)
    sesh.tg_responses.append(tg_response)
    setSesh(seshid, sesh)
    
def loadColorAndCharacter(text, seshid):
    sesh = getSesh(seshid)
    if text == 'load':
        sesh.product_pd_counts = [(product,pd_count) for store in sesh.summary_joined for product,pd_count in sesh.summary_joined[store].items()]
        sesh.tg_responses = []
        urls = [product_pd_count[1]['product_dict']['href'] for product_pd_count in sesh.product_pd_counts]
        """sesh.responses = asyncio.run(main(urls))

        #gen_uid = str(time.time())
        item_locator_data = {data[1]: sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']}
        print('item_locator_data: ', item_locator_data, '\n/*/*', [item_locator_data[product_pd_count[0]] for i,product_pd_count in enumerate(sesh.product_pd_counts)])
        responses = [r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]
        urls = ['https://dreamdemo.pythonanywhere.com/dump_text_gen' for _ in range(len(sesh.product_pd_counts))]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        for item,idxs in item_locator_data.items():
            if tuple(idxs) not in sesh.locator_genid: sesh.locator_genid[tuple(idxs)] = gen_uid = str(time.time())
        json_data = [json.dumps({'room_type': sesh.room_type, 'item_locator_data': item_locator_data[product_pd_count[0]], 'gen_uid': sesh.locator_genid[tuple(item_locator_data[product_pd_count[0]])], 'response':responses[i], 'item': product_pd_count[0]}) for i,product_pd_count in enumerate(sesh.product_pd_counts) if product_pd_count[0] not in ['Palette', 'Living Room', 'Bedroom']]
        responses = asyncio.run(main_post(urls, headers, json_data, timeout=3))
        print('dump_text_gen: ', responses)"""

        """dummy = dummy_
        
        print('sesh.display_items_[sesh.current_img_signature]: ', sesh.display_items_[sesh.current_img_signature])
        print('item_data_: ', [(k,len(v)) for k,v in sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items() if k not in ['Palette', 'Living Room', 'Bedroom']])
        item_locator_data = {data[1]: sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']}
        print('item_locator_data: ', item_locator_data)
        
        url = 'https://dreamdemo.pythonanywhere.com/shopping'
        sesh.gen_uid = str(time.time())
        valid_data = {'gen_uid': sesh.gen_uid, 'item_locator_data': item_locator_data, 'product_pd_counts': sesh.product_pd_counts, 'responses':[r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]} 
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        r = requests.post(url, data=json.dumps(valid_data), headers=headers)
        jsondata = json.loads(r.content)"""
        """urls = ['https://dreamdemo.pythonanywhere.com/script_gen' for _ in range(len(sesh.product_pd_counts))]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        json_data = [json.dumps({'room_type': sesh.room_type, 'idx': i, 'gen_uid': sesh.gen_uid}) for i in range(len(sesh.product_pd_counts))]
        responses = asyncio.run(main_post(urls, headers, json_data))"""
        #sesh.found_terms_4_room_items = jsondata['response']
        """print('loadColorAndCharacter: ', jsondata['response'])


        urls = ['https://dreamdemo.pythonanywhere.com/script_gen' for _ in range(1)]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        json_data = [json.dumps({'room_type': sesh.room_type, 'idx': i, 'gen_uid': sesh.gen_uid, 'model': i}) for i in range(1)]
        try:
            responses = asyncio.run(main_post(urls, headers, json_data, timeout=7))
        except:
            pass
            

        urls = ['https://dreamdemo.pythonanywhere.com/script_gen' for _ in range(4)]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        json_data = [json.dumps({'room_type': sesh.room_type, 'idx': i, 'gen_uid': sesh.gen_uid, 'model': i}) for i in range(4)]
        try:
            responses = asyncio.run(main_post(urls, headers, json_data, timeout=1))
        except:
            pass
        setSesh(seshid, sesh)"""
        return 'loaded'
    else:
        setSesh(seshid, sesh)
        return 'not loaded'


def searchColorAndCharacter(text, seshid):
    sesh = getSesh(seshid)
    if text == 'search':
        """url = 'https://dreamdemo.pythonanywhere.com/shopping'
        sesh.gen_uid = str(time.time())
        valid_data = {'gen_uid': sesh.gen_uid, 'product_pd_counts': sesh.product_pd_counts, 'responses':[r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]} 
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        r = requests.post(url, data=json.dumps(valid_data), headers=headers)
        jsondata = json.loads(r.content)
     
        #sesh.found_terms_4_room_items = jsondata['response']
        print('searchColorAndCharacter: ', jsondata['response'])
        urls = ['https://dreamdemo.pythonanywhere.com/script_gen' for _ in range(1)]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        json_data = [json.dumps({'room_type': sesh.room_type, 'idx': i, 'gen_uid': sesh.gen_uid, 'model': i}) for i in range(1)]
        try:
            responses = asyncio.run(main_post(urls, headers, json_data, timeout=7))
        except:
            pass
            
        urls = ['https://dreamdemo.pythonanywhere.com/script_gen' for _ in range(4)]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        json_data = [json.dumps({'room_type': sesh.room_type, 'idx': i, 'gen_uid': sesh.gen_uid, 'model': i}) for i in range(4)]
        try:
            responses = asyncio.run(main_post(urls, headers, json_data, timeout=1))
        except:
            pass"""

        
        """start = time.time()
        urls = ['https://dreamdemo.pythonanywhere.com/script_gen' for _ in range(len(sesh.product_pd_counts))]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        json_data = [json.dumps({'room_type': sesh.room_type, 'idx': i, 'gen_uid': sesh.gen_uid}) for i in range(len(sesh.product_pd_counts))]
        #responses = asyncio.run(main_post(urls, headers, json_data, timeout=180))
        end = time.time()
        r_ = [r[:250] if r else str(i)+'--N/A' for i,r in enumerate(responses)]

        #sesh.tg_responses = [json.loads(r)['response'] if type(r) == type(b'') else '********' for r in responses]
        #sesh.tg_responses.append(tg_response)
        print('searchColorAndCharacter script_gen: ', (end-start)/60, [(r[:250], sesh.product_pd_counts[i][0]) for i,r in enumerate(sesh.tg_responses)])
        """
        """script_prompts = {'Youtube Long-Form': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a long-form Youtube video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Youtube Short-Form': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a Youtube Short. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Facebook Long-Form': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a long-form Facebook video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Instagram Reel': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for an Instagram Reel video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Tiktok': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a Tiktok video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'LinkedIn': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a LinkedIn long-form video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'}
        start = time.time()
        script_types = [s for s in script_prompts]
        urls = ['https://dreamdemo.pythonanywhere.com/textgen' for _ in range(len(script_types))]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        json_data = [json.dumps({'prompts': script_prompts[k]}) for k in script_types]
        responses = asyncio.run(main_post(urls, headers, json_data, timeout=180))
        end = time.time()
        
        print('searchColorAndCharacter script types: ', end-start, [(r[:250], script_types[i]) for i,r in enumerate(responses)])
        """
        
        #sesh.found_terms_4_room_items = [(sesh.product_pd_counts[ir][0], findShoppingRelevantTerms(r)) for ir,r in enumerate(sesh.responses)]
        #print('searchColorAndCharacter 2: ', sesh.found_terms_4_room_items)
        #sesh.found_terms_4_room_items_idx = 0
        #sesh.scripts = {}
        #sesh.items_prepped = ['\n\n'.join([f'ITEM: {data[0].upper()}\n\n'+f'{data[0].upper()} STORE: '+sesh.product_pd_counts[idx][1]['product_dict']['store']+'\n\n'+f'{data[0].upper()} DESCRIPTION: '+sesh.product_pd_counts[idx][1]['product_dict']['description']+'\n\n'+'\n\n'.join([f'{data[0].upper()} TOPIC: '+(term[1:-1].upper() if term[1:-1] != 'ship' else 'SHIPPING')+'\n...'+text for term,text in data[1].items()])]) for idx,data in enumerate(sesh.found_terms_4_room_items)]
        #item_prompts = [makeItemPrompt(idx,idata) for idx,idata in enumerate(sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])]
        #item_scripts = multiprocessPrompts(item_prompts)
        #print('searchColorAndCharacter: ', item_scripts)
        setSesh(seshid, sesh)
        return 'searched'
    else:
        setSesh(seshid, sesh)
        return 'not searched'



def updateLinksLoadStatus(text, seshid):
    sesh = getSesh(seshid)
    setSesh(seshid, sesh)
    if text == 'loaded':
        print('LOADED color and character for script\nadding color and character to script\nstandby...')
        return 'LOADED color and character\nadding color and character to scripts\nstandby...', 'search'
    else:
        return 'searched color and character for script\npreparing script for item1\nstandby...update this', ''

def updateLinksSearchStatus(text, seshid):
    sesh = getSesh(seshid)
    setSesh(seshid, sesh)
    if text == 'searched':
        print('ADDED color and character for script\npreparing script for item1\nstandby...')
        #return f'ADDED color and character for script\npreparing script for {sesh.product_pd_counts[0][0]}\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby......', 'prep1'
        return f'ADDED color and character for script\npreparing all scripts, standby......', 'prep1'
    else:
        return 'searched color and character for script\npreparing script for item1\nstandby...update this', ''

def prepAllScripts(text, seshid):
    sesh = getSesh(seshid)
    
    if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
        script_prompts = {'Youtube Long-Form': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a long-form Youtube video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Youtube Short-Form': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a Youtube Short. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Facebook Long-Form': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a long-form Facebook video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Instagram Reel': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for an Instagram Reel video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Tiktok': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a Tiktok video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'LinkedIn': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a LinkedIn long-form video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'}
        start = time.time()
        script_types = [s for s in script_prompts]
        urls = ['https://dreamdemo.pythonanywhere.com/textgen' for _ in range(len(script_types))]
        headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
        json_data = [json.dumps({'prompts': script_prompts[k]}) for k in script_types]
        responses = asyncio.run(main_post(urls, headers, json_data, timeout=210))
        end = time.time()
        sesh.scripts = {k:json.loads(responses[i])['response'] if type(responses[i]) == type(b'') else 'Unable to complete this script.' for i,k in enumerate(script_types)}
        
        #print('prepItem1ForScript script types: ', (end-start)/60, [(r[:250], script_types[i]) for i,r in enumerate(responses)])
        setSesh(seshid, sesh)
        return 'good'
        
    else:
        setSesh(seshid, sesh)
        return 'bad'

def updateAllItemsStatus(text, seshid):
    sesh = getSesh(seshid)
    completed = len([s for s in sesh.scripts if s != 'Unable to complete this script.'])
    if text == 'good' and completed > 0:
        setSesh(seshid, sesh)
        return f"Color and character updated, {completed} {'scripts' if completed != 1 else 'script'} completed. ", gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
        
    else:
        setSesh(seshid, sesh)
        return f'Something went wrong, failed to complete scripts.', gr.Dropdown([], label='Scripts', interactive=True)

def prepItem1ForScript(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
        #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
        generateScriptForItem()
        sesh.found_terms_4_room_items_idx += 1
        setSesh(seshid, sesh)
        return f'prepped{sesh.found_terms_4_room_items_idx}'+'-changed for testing'
  
    else:
        setSesh(seshid, sesh)
        return f'prep{sesh.found_terms_4_room_items_idx} failed'

def updateItem1Status(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prepped{sesh.found_terms_4_room_items_idx}':
        #print('prepItem1forScript: ', sesh.tg_responses[0])
        setSesh(seshid, sesh)
        return 'Color and character updated, scripts complete.', f'prep{sesh.found_terms_4_room_items_idx+1}'
        #return f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...', f'prep{sesh.found_terms_4_room_items_idx+1}'
    else:
        setSesh(seshid, sesh)
        print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
        return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''


def prepItem2ForScript(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
        #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
        generateScriptForItem()
        sesh.found_terms_4_room_items_idx += 1
        setSesh(seshid, sesh)
        return f'prepped{sesh.found_terms_4_room_items_idx}'
    else:
        setSesh(seshid, sesh)
        return f'prep{sesh.found_terms_4_room_items_idx} failed'

def updateItem2Status(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prepped{sesh.found_terms_4_room_items_idx}':
        #print('prepItem1forScript: ', sesh.tg_responses[0])
        setSesh(seshid, sesh)
        return f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...', f'prep{sesh.found_terms_4_room_items_idx+1}'
    else:
        print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
        setSesh(seshid, sesh)
        return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''


def prepItem3ForScript(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
        #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
        generateScriptForItem()
        sesh.found_terms_4_room_items_idx += 1
        setSesh(seshid, sesh)
        return f'prepped{sesh.found_terms_4_room_items_idx}'
    else:
        setSesh(seshid, sesh)
        return f'prep{sesh.found_terms_4_room_items_idx} failed'

def updateItem3Status(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prepped{sesh.found_terms_4_room_items_idx}':
        #print('prepItem1forScript: ', sesh.tg_responses[0])
        setSesh(seshid, sesh)
        return f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...', f'prep{sesh.found_terms_4_room_items_idx+1}'
    else:
        print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
        setSesh(seshid, sesh)
        return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''

def prepItem4ForScript(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
        #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
        generateScriptForItem()
        sesh.found_terms_4_room_items_idx += 1
        setSesh(seshid, sesh)
        return f'prepped{sesh.found_terms_4_room_items_idx}'
    else:
        setSesh(seshid, sesh)
        return f'prep{sesh.found_terms_4_room_items_idx} failed'

def updateItem4Status(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prepped{sesh.found_terms_4_room_items_idx}':
        #print('prepItem1forScript: ', sesh.tg_responses[0])
        setSesh(seshid, sesh)
        return f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...', f'prep{sesh.found_terms_4_room_items_idx+1}'
    else:
        print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
        setSesh(seshid, sesh)
        return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''

def prepItem5ForScript(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
        #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
        generateScriptForItem()
        sesh.found_terms_4_room_items_idx += 1
        setSesh(seshid, sesh)
        return f'prepped{sesh.found_terms_4_room_items_idx}'
    else:
        setSesh(seshid, sesh)
        return f'prep{sesh.found_terms_4_room_items_idx} failed'

def updateItem5Status(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prepped{sesh.found_terms_4_room_items_idx}':
        #print('prepItem1forScript: ', sesh.tg_responses[0])
        setSesh(seshid, sesh)
        return f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...', f'prep{sesh.found_terms_4_room_items_idx+1}'
    else:
        print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
        setSesh(seshid, sesh)
        return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''

def prepItem6ForScript(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
        #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
        generateScriptForItem()
        sesh.found_terms_4_room_items_idx += 1
        setSesh(seshid, sesh)
        return f'prepped{sesh.found_terms_4_room_items_idx}'
    else:
        setSesh(seshid, sesh)
        return f'prep{sesh.found_terms_4_room_items_idx} failed'

def updateItem6Status(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prepped{sesh.found_terms_4_room_items_idx}':
        #print('prepItem1forScript: ', sesh.tg_responses[0])
        setSesh(seshid, sesh)
        return f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx} of {len(sesh.product_pd_counts)+6}, standby...', f'prep{sesh.found_terms_4_room_items_idx+1}'
    else:
        print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
        setSesh(seshid, sesh)
        return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''

def prepItem7ForScript(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
        #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
        generateScriptForItem()
        sesh.found_terms_4_room_items_idx += 1
        setSesh(seshid, sesh)
        return f'prepped{sesh.found_terms_4_room_items_idx}'
    else:
        setSesh(seshid, sesh)
        return f'prep{sesh.found_terms_4_room_items_idx} failed'

def updateItem7Status(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prepped{sesh.found_terms_4_room_items_idx}':
        #print('prepItem1forScript: ', sesh.tg_responses[0])
        setSesh(seshid, sesh)
        return f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...', f'prep{sesh.found_terms_4_room_items_idx+1}'
    else:
   
        print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
        setSesh(seshid, sesh)
        return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''

def prepItem8ForScript(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
        #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
        generateScriptForItem()
        sesh.found_terms_4_room_items_idx += 1
        setSesh(seshid, sesh)
        return f'prepped{sesh.found_terms_4_room_items_idx}'
    else:
        setSesh(seshid, sesh)
        return f'prep{sesh.found_terms_4_room_items_idx} failed'

def updateItem8Status(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prepped{sesh.found_terms_4_room_items_idx}':
        #print('updateItem8Status: ', sesh.found_terms_4_room_items_idx, len(sesh.found_terms_4_room_items))
        sesh.script_status_text = f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...' if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts) else f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for Youtube long-form video.\nWorking on step {sesh.found_terms_4_room_items_idx} of {len(sesh.product_pd_counts)+6}, standby...'
        setSesh(seshid, sesh)
        return sesh.script_status_text, f'prep{sesh.found_terms_4_room_items_idx+1}'
    else:
        print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
        setSesh(seshid, sesh)
        return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''

def prepItem9ForScript(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
        if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): generateScriptForItem() #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
        if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): sesh.found_terms_4_room_items_idx += 1
        setSesh(seshid, sesh)
        return f'prepped{sesh.found_terms_4_room_items_idx}'
    else:
        setSesh(seshid, sesh)
        return f'prep{sesh.found_terms_4_room_items_idx} failed'

def updateItem9Status(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prepped{sesh.found_terms_4_room_items_idx}':
        #print('updateItem9Status: ', sesh.found_terms_4_room_items_idx, len(sesh.found_terms_4_room_items))
        sesh.script_status_text = f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...' if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts)-1 else sesh.script_status_text
        setSesh(seshid, sesh)
        return sesh.script_status_text, f'prep{sesh.found_terms_4_room_items_idx+1}'
    else:
        print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
        setSesh(seshid, sesh)
        return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''

def prepItem10ForScript(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
        if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): generateScriptForItem() #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
        if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): sesh.found_terms_4_room_items_idx += 1
        setSesh(seshid, sesh)
        return f'prepped{sesh.found_terms_4_room_items_idx}'
    else:
        setSesh(seshid, sesh)
        return f'prep{sesh.found_terms_4_room_items_idx} failed'

def updateItem10Status(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prepped{sesh.found_terms_4_room_items_idx}':
        #print('updateItem10Status: ', sesh.found_terms_4_room_items_idx, len(sesh.found_terms_4_room_items))
        sesh.script_status_text = f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...' if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts)-1 else sesh.script_status_text
        setSesh(seshid, sesh)
        return sesh.script_status_text, f'prep{sesh.found_terms_4_room_items_idx+1}'
    else:
        print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
        setSesh(seshid, sesh)
        return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''

def prepItem11ForScript(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
        if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): generateScriptForItem() #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
        if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): sesh.found_terms_4_room_items_idx += 1
        setSesh(seshid, sesh)
        return f'prepped{sesh.found_terms_4_room_items_idx}'
    else:
        setSesh(seshid, sesh)
        return f'prep{sesh.found_terms_4_room_items_idx} failed'

def updateItem11Status(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prepped{sesh.found_terms_4_room_items_idx}':
        #print('updateItem11Status: ', sesh.found_terms_4_room_items_idx, len(sesh.found_terms_4_room_items))
        sesh.script_status_text = f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...' if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts)-1 else sesh.script_status_text
        setSesh(seshid, sesh)
        return sesh.script_status_text, f'prep{sesh.found_terms_4_room_items_idx+1}'
    else:
        print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
        setSesh(seshid, sesh)
        return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''

def prepItem12ForScript(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
        if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): generateScriptForItem() #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
        if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): sesh.found_terms_4_room_items_idx += 1
        setSesh(seshid, sesh)
        return f'prepped{sesh.found_terms_4_room_items_idx}'
    else:
        setSesh(seshid, sesh)
        return f'prep{sesh.found_terms_4_room_items_idx} failed'

def updateItem12Status(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prepped{sesh.found_terms_4_room_items_idx}':
        #print('updateItem12Status: ', sesh.found_terms_4_room_items_idx, len(sesh.found_terms_4_room_items))
        sesh.script_status_text = f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...' if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts)-1 else sesh.script_status_text
        setSesh(seshid, sesh)
        return sesh.script_status_text, f'prep{sesh.found_terms_4_room_items_idx+1}'
    else:
        print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
        setSesh(seshid, sesh)
        return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''

def prepItem13ForScript(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
        if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): generateScriptForItem() #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
        if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): sesh.found_terms_4_room_items_idx += 1
        setSesh(seshid, sesh)
        return f'prepped{sesh.found_terms_4_room_items_idx}'
    else:
        setSesh(seshid, sesh)
        return f'prep{sesh.found_terms_4_room_items_idx} failed'

def updateItem13Status(text, seshid):
    sesh = getSesh(seshid)
    if text == f'prepped{sesh.found_terms_4_room_items_idx}':
        #print('updateItem13Status: ', sesh.found_terms_4_room_items_idx, len(sesh.found_terms_4_room_items))
        #print('prepItem13forScript: ', sesh.tg_responses)
        sesh.scripts['Base'] = '\n\n'.join(sesh.tg_responses)
        sesh.script_status_text = f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...' if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts)-1 else sesh.script_status_text
        setSesh(seshid, sesh)
        return sesh.script_status_text, 'prep_ytlong'
    else:
        print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
        setSesh(seshid, sesh)
        return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''


def prepYTLongFormScript(text, seshid):
    sesh = getSesh(seshid)
    if text == 'prep_ytlong':
        prompt = 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a long-form Youtube video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'
        sesh.scripts['Youtube Long-Form'] = getTextGen(prompt) #client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
        setSesh(seshid, sesh)
        return 'ytlong_prepped'
    else:
        setSesh(seshid, sesh)
        return 'prep_ytlong failed'

def updateYTLongFormStatus(text, seshid):
    sesh = getSesh(seshid)
    if text == 'ytlong_prepped':
        print('updateYTLongFormStatus: ', list(sesh.scripts))
        setSesh(seshid, sesh)
        return f'YOUTUBE LONG-FORM script complete.\nPreparing script for Youtube short-form.\nWorking on step {sesh.found_terms_4_room_items_idx+2} of {len(sesh.product_pd_counts)+6}, standby...', 'prep_ytshort', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
    else:
        setSesh(seshid, sesh)
        return 'YT long-form script failed', '', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)


def prepYTShortFormScript(text, seshid):
    sesh = getSesh(seshid)
    if text == 'prep_ytshort':
        prompt = 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a Youtube Short. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'
        sesh.scripts['Youtube Short-Form'] = getTextGen(prompt) #client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
        setSesh(seshid, sesh)
        return 'ytshort_prepped'
    else:
        setSesh(seshid, sesh)
        return 'prep_ytshort failed'

def updateYTShortFormStatus(text, seshid):
    sesh = getSesh(seshid)
    print('updateYTShortFormStatus: ', text, list(sesh.scripts))
    if text == 'ytshort_prepped':
        setSesh(seshid, sesh)
        return f'YOUTUBE SHORT script complete.\nPreparing script for Facebook.\nWorking on step {sesh.found_terms_4_room_items_idx+3} of {len(sesh.product_pd_counts)+6}, standby...', 'prepfb', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
    else:
        setSesh(seshid, sesh)
        return 'YT short-form script failed', '', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)


def prepFBScript(text,seshid):
    sesh = getSesh(seshid)
    if text == 'prepfb':
        prompt = 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a long-form Facebook video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'
        sesh.scripts['Facebook Long-Form'] = getTextGen(prompt) #client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
        setSesh(seshid, sesh)
        return 'fb_prepped'
    else:
        setSesh(seshid, sesh)
        return 'prepfb failed'

def updateFBStatus(text, seshid):
    sesh = getSesh(seshid)
    print('updateFBStatus: ', text, list(sesh.scripts))
    if text == 'fb_prepped':
        setSesh(seshid, sesh)
        return f'FACEBOOK script complete.\nPreparing script for Instagram Reel.\nWorking on step {sesh.found_terms_4_room_items_idx+4} of {len(sesh.product_pd_counts)+6}, standby...', 'prepig', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
    else:
        setSesh(seshid, sesh)
        return 'Facebook script failed', '', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)


def prepIGScript(text, seshid):
    if text == 'prepig':
        prompt = 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for an Instagram Reel video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'
        sesh.scripts['Instagram Reel'] = getTextGen(prompt) #client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
        return 'ig_prepped'
    else:
        return 'prepig failed'

def updateIGStatus(text, seshid):
    print('updateIGStatus: ', text, list(sesh.scripts))
    if text == 'ig_prepped':
        return f'INSTAGRAM REEL script complete.\nPreparing script for TikTok.\nWorking on step {sesh.found_terms_4_room_items_idx+5} of {len(sesh.product_pd_counts)+6}, standby...', 'prep_tiktok', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
    else:
        return 'IG script failed', '', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)


def prepTikTokScript(text, seshid):
    if text == 'prep_tiktok':
        prompt = 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a Tiktok video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'
        sesh.scripts['Tiktok'] = getTextGen(prompt) #client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
        return 'tiktok_prepped'
    else:
        return 'prep_tiktok failed'

def updateTikTokStatus(text, seshid):
    print('updateTikTokStatus: ', text, list(sesh.scripts))
    if text == 'tiktok_prepped':
        return f'TIKTOK script complete.\nPreparing script for LinkedIn.\nWorking on step {sesh.found_terms_4_room_items_idx+6} of {len(sesh.product_pd_counts)+6}, standby...', 'prep_linkedin', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
    else:
        return 'TikTok script failed', '', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)


def prepLinkedInScript(text, seshid):
    if text == 'prep_linkedin':
        prompt = 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a LinkedIn long-form video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'
        sesh.scripts['LinkedIn'] = getTextGen(prompt) #client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
        return 'linkedin_prepped'
    else:
        return 'prep_linkedin failed'

def updateLinkedInStatus(text, seshid):
    print('updateLinkedInStatus: ', text, list(sesh.scripts))
    if text == 'linkedin_prepped':
        return 'All scripts complete.', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
    else:
        return 'LinkedIn script failed', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)


def selectScript(evt: gr.SelectData, seshid):
    sesh = getSesh(seshid)
    script = evt.value
    frmt = evt.value
    if frmt == 'Status':
        return 'Select a video format to have a script prepared.'
    uploadToScriptGenPromise(frmt, seshid)
    #frmt_id_maps[formats[i]]
    url = 'https://dreamdemo.pythonanywhere.com/query_textgen'
    #item_locator_data = [tuple(sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]]) for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']]
    #valid_data = {'item_locator_data': item_locator_data} 
    valid_data = {'seshid':seshid, 'genuid': sesh.frmt_id_maps[sesh.current_img_signature][frmt]} 
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    start = time.time()
    #r = requests.post(url, data=json.dumps(valid_data), headers=headers)
    #jsondata = json.loads(r.content)

    urls = ['https://dreamdemo.pythonanywhere.com/query_textgen' for i in range(1)]
    headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i in range(1)]
    json_data = [json.dumps({'seshid':seshid, 'genuid': sesh.frmt_id_maps[sesh.current_img_signature][frmt]}) for i in range(1)]
    responses = asyncio.run(main_post(urls, headers, json_data, timeout=2))
    try:
        data_dict = json.loads(responses[0])
    except:
        data_dict = {}
    
    print('selectScript: ', frmt, sesh.frmt_id_maps[sesh.current_img_signature][frmt], time.time()-start, responses)
    #return sesh.scripts[script]
    return 'Script being generated. Try again in 30  seconds.' if not data_dict or 'text' not in data_dict else data_dict['text']


def showMainDisplay(home_address):
    print('showMainDisplay: ', home_address)
    return gr.update(visible=bool(0)), gr.update(visible=bool(1))



with gr.Blocks(theme=gr.themes.Monochrome(), js=js_func) as demo:
    ads = gr.Label('EndlessIdeas: Helping Your Ideas Find A Home', label='Sponsors')
    with gr.Tab('Update Property Data'):
        with gr.Row():
            with gr.Column():
                upload = gr.Image(label='Upload Room Photo')
                upload_photo = gr.Button('Submit Photo')
            with gr.Column():
                working_room = gr.Gallery(label='Select Working Room', height=350, interactive=True)
    with gr.Tab('Room Type'):
        with gr.Row():
            with gr.Column():
                working_room2 = gr.Image(label='Working Room')
            with gr.Column():
                rooms_gallery = gr.Gallery([(v,k) for k,v in bedrooms.items()], label="Room Type", height=350, interactive=True)
    with gr.Tab('Design Style'):
        with gr.Row():
            with gr.Column():
                working_room3 = gr.Image(label='Working Room')
            with gr.Column():
                design_gallery = gr.Gallery(label="Design Styles", preview=True, height=350, interactive=True)
                price_radio = gr.Radio(['Affordable', 'Upmarket'], label='Price Point', interactive=True, visible=True, value='Affordable')
                bedsize_radio = gr.Radio(['Full', 'Queen', 'King'], value='Queen', label='Bed Size', interactive=True, visible=False)
    with gr.Tab('Color Palette'):
        with gr.Row():
            with gr.Column():
                working_room1 = gr.Image(label='Working Room')
            with gr.Column():
                color_Palettes = gr.Gallery(label='Proposed Color Palettes', height=350, interactive=True)
    with gr.Tab('Room Items'):
        with gr.Row():
            room_items = gr.Gallery(label='Room Items', height=350, interactive=True)
    with gr.Tab('Item Replace'):
        with gr.Row():
            with gr.Column():
                working_Palette = gr.Image(label='Working Color Palette')
            with gr.Column():
                esdsd = gr.Gallery(label='Proposed Color Palettes', height=350, interactive=True)
    with gr.Tab('Shopping Cart'):
        pass


#home_address, address_enter, showMainDisplay
with gr.Blocks(theme=gr.themes.Monochrome(), js=js_func, css=css) as demo:
    #ads = gr.Image("C:\\Users\\Wayne\\Downloads\\Welcome Home.gif", show_label=False, scale=5, height=150, show_download_button=False)
    ads = gr.Label("Dream Home: As Quick As A Click. As Simple As Shopping. ", show_label=False)
    seshid = gr.Textbox('SESHID', visible=False)
    replace = gr.Gallery(label='Replacement Items', rows=2, columns=7, visible=False, interactive=True, elem_classes=['scroll'])
    with gr.Row(visible=False) as store_summary:
        merchant_top = gr.Label(label='Merchant')
        total = gr.Label(label='Number of Items')
        num_of_items = gr.Label(label='Total')
    with gr.Row() as landing_page:
        merchant_top = gr.Label(label="Let's Get Started")
        home_address = gr.Textbox()
        address_enter = gr.Button('Go')
    with gr.Row(visible=False) as main_display:
        with gr.Column(scale=5) as items_display:
            #room_items = gr.Gallery([((sesh.Palette_img if item == 'Palette' else sesh.default_img ) if item in ['Palette', 'Living Room', 'Bedroom'] else room_item_placeholder_images_dict['LIVING ROOM FURNITURE'][item], item) for item in living_layout_new], label='Room Items', columns=5, height=400, interactive=True)
            room_items = gr.Gallery([((Palette_img if item == 'Palette' else default_img ) if item in ['Palette', 'Living Room', 'Bedroom'] else room_item_placeholder_images_dict['LIVING ROOM FURNITURE'][item], item) for item in living_layout_new], label='Room Items', columns=5, height=400, elem_classes=['scroll'])
        with gr.Column(scale=1, visible=False) as style_side:
            #dsdf = gr.Image("C:\\Users\\Wayne\\Downloads\\agent-first.gif", show_label=False, show_download_button=False)
            close1 = gr.Button('Close')
        with gr.Column(scale=1, visible=False) as item_side:
            merchant = gr.Label('No Item Selected', label='Merchant')
            replace_item = gr.Button('Replace')
            #sdsd = gr.Image("C:\\Users\\Wayne\\Downloads\\agent-first.gif", show_label=False, show_download_button=False)
            close2 = gr.Button('Close')
            #with gr.Group():
                #with gr.Row():
                    #exclude = gr.Button('Exclude')
                    #include = gr.Button('Include')
            #Palette_ref = gr.Image(show_label=False)
            #replace = gr.Gallery(label='Replacement Items', columns=2)
        with gr.Column(scale=1, visible=False) as room_side:
            close3 = gr.Button('Close')
            summary_button = gr.Button('Summarise')
            with gr.Group(visible=False) as summary_group:
                with gr.Accordion(label='Merchant Summary') as merchant_summary:
                    complete_summary = gr.Radio(['Complete', 'Merchant', 'Script'], value='Complete', interactive=True, label='Inspection')
                    store_dropdown = gr.Dropdown(label='Merchants', visible=False)
                    with gr.Row(equal_height=True) as budget_row: 
                        budget = gr.Textbox(label='Budget', min_width=70)
                        #budget_button = gr.Button('Update', size='sm')
                    complete_source_breakdown = gr.Textbox(label='Item Breakdown', interactive=True)
                with gr.Accordion(label='Product Summary', open=False, visible=False) as product_summary:
                    product_dropdown = gr.Dropdown(label='Products')
                    count = gr.Number(label='Item Count', minimum=0)
                    source = gr.Markdown(label='Source')
            #room_ad = gr.Image("C:\\Users\\Wayne\\Downloads\\list with us.gif", show_label=False, show_download_button=False)
            room_ad = gr.Textbox(visible=False)
            with gr.Accordion(label='Select Design Style', open=False) as design_accordion:
                design_gallery = gr.Gallery(design_images, label="Design Styles", preview=True, interactive=True, height=200, elem_classes=['scroll'])
                price_radio = gr.Radio(['Affordable', 'Upmarket'], label='Price Point', interactive=True, visible=True, value='Affordable')
                bedsize_radio = gr.Radio(['Full', 'Queen', 'King'], value='Queen', label='Bed Size', interactive=True, visible=True)
            with gr.Accordion(label='Update Property Data', open=False) as update_accordion:
                with gr.Accordion(label='Upload Photo', open=False):
                    upload = gr.Image(label='Upload Room Photo', height=200)
                    upload_photo = gr.Button('Submit Photo')
                with gr.Accordion(label='Select Room', open=False):
                    choose_room = gr.Gallery(label="Room To Decorate", height=200, interactive=True)
                with gr.Accordion(label='Select Room Type', open=False):
                    room2decorate = gr.Image(label='Working Room', height=150)
                    rooms_gallery = gr.Gallery([(v,k) for k,v in bedrooms.items()], label="Room Type", interactive=True)

        with gr.Column(scale=1, visible=False) as colors_side:
            #close4 = gr.Button('Close')
            with gr.Row():
                close4 = gr.Button('Close', size='sm')
            with gr.Row():
                palettes = gr.Button('Palettes', size='sm', min_width=45)
                scripts = gr.Button('Scripts', size='sm', min_width=45)
                journeys = gr.Button('Journeys', size='sm', min_width=45)
            #dsdsd = gr.Image("C:\\Users\\Wayne\\Downloads\\local ad.gif", show_label=False, show_download_button=False)
            with gr.Group(visible=True) as palettes_div:
                color_Palettes = gr.Gallery(label='Proposed Color Palettes', columns=2, height=200, elem_classes=['scroll'])
            with gr.Group(visible=False) as script_div:
                status_text = gr.Textbox("loading info for color and character\nstand by...\n", show_label=True, interactive=False, lines=3, label='Status', visible=False)
                scripts_drop = gr.Dropdown(['Status', 'Youtube Long-Form', 'Youtube Short-Form', 'Facebook Long-Form', 'Instagram Reel', 'Tik Tok', 'LinkedIn'], label='Scripts', interactive=True)
                script_display = gr.Textbox(label='Script', max_lines=7)
                script_broker = gr.Textbox(visible=False)
                item_links_load = gr.Textbox(visible=False)
                item_links_search = gr.Textbox(visible=False)
                script_load1 = gr.Textbox(visible=False)
                script_load2 = gr.Textbox(visible=False)
                script_load3 = gr.Textbox(visible=False)
                script_load4 = gr.Textbox(visible=False)
                script_load5 = gr.Textbox(visible=False)
                script_load6 = gr.Textbox(visible=False)
                script_load7 = gr.Textbox(visible=False)
                script_load8 = gr.Textbox(visible=False)
                script_load9 = gr.Textbox(visible=False)
                script_load10 = gr.Textbox(visible=False)
                script_load11 = gr.Textbox(visible=False)
                script_load12 = gr.Textbox(visible=False)
                script_load13 = gr.Textbox(visible=False)
                yt_load = gr.Textbox(visible=False)
                linkedin_load = gr.Textbox(visible=False)
                facebook_load = gr.Textbox(visible=False)
                ytshorts_load = gr.Textbox(visible=False)
                reels_load = gr.Textbox(visible=False)
                tiktok_load = gr.Textbox(visible=False)

                item_links_load_update = gr.Textbox(visible=False)
                item_links_search_update = gr.Textbox(visible=False)
                all_items_update = gr.Textbox(visible=False)
                script_load1_update = gr.Textbox(visible=False)
                script_load2_update = gr.Textbox(visible=False)
                script_load3_update = gr.Textbox(visible=False)
                script_load4_update = gr.Textbox(visible=False)
                script_load5_update = gr.Textbox(visible=False)
                script_load6_update = gr.Textbox(visible=False)
                script_load7_update = gr.Textbox(visible=False)
                script_load8_update = gr.Textbox(visible=False)
                script_load9_update = gr.Textbox(visible=False)
                script_load10_update = gr.Textbox(visible=False)
                script_load11_update = gr.Textbox(visible=False)
                script_load12_update = gr.Textbox(visible=False)
                script_load13_update = gr.Textbox(visible=False)
                yt_update = gr.Textbox(visible=False)
                linkedin_update = gr.Textbox(visible=False)
                facebook_update = gr.Textbox(visible=False)
                ytshorts_update = gr.Textbox(visible=False)
                reels_update = gr.Textbox(visible=False)
                tiktok_update = gr.Textbox(visible=False)
                dummy = gr.Textbox(visible=False)
                
            with gr.Group(visible=False) as journeys_div:
                with gr.Accordion('Dream Job', open=False):
                    dream_job_title = gr.Textbox(label="Dream Job Title")
                    dream_job_company = gr.Textbox(label="Dream Job Company")
                    dream_job_salary = gr.Number(label="Dream Job Salary")
                    dream_job_skills = gr.Textbox(label="Dream Job Required Skills")
                    current_skills = gr.Textbox(label="Current Skills")
                with gr.Accordion('Dream Home', open=False):
                    dream_home_location = gr.Textbox(label="Dream Home Location")
                    dream_home_price = gr.Number(label="Dream Home Price")
                    dream_home_size = gr.Textbox(label="Dream Home Size")
                    dream_home_features = gr.Textbox(label="Dream Home Features")
                    current_savings = gr.Number(label="Current Savings")
                # Output components
                job_progress_textbox = gr.Textbox(label="Progress Towards Dream Job")
                home_progress_textbox = gr.Textbox(label="Progress Towards Dream Home")


    
    address_enter.click(showMainDisplay, [home_address], [landing_page, main_display])
    palettes.click(showPalettes, [seshid], [palettes_div, script_div, journeys_div])
    scripts.click(showScripts, [seshid], [palettes_div, script_div, journeys_div, item_links_load])
    journeys.click(showJourneys, [seshid], [palettes_div, script_div, journeys_div])

    item_links_load.change(loadColorAndCharacter, [item_links_load, seshid], [item_links_load_update])
    item_links_load_update.change(updateLinksLoadStatus, [item_links_load_update, seshid], [status_text, item_links_search])
    item_links_search.change(searchColorAndCharacter, [item_links_search, seshid], [item_links_search_update])
    item_links_search_update.change(updateLinksSearchStatus, [item_links_search_update, seshid], [status_text, script_load1])

    script_load1.change(prepAllScripts, [script_load1, seshid], [all_items_update])
    all_items_update.change(updateAllItemsStatus, [all_items_update, seshid], [status_text, scripts_drop])

    #script_load1.change(prepItem1ForScript, script_load1, [script_load1_update])
    script_load1_update.change(updateItem1Status, [script_load1_update, seshid], [status_text, script_load2])

    script_load2.change(prepItem2ForScript, [script_load2, seshid], [script_load2_update])
    script_load2_update.change(updateItem1Status, [script_load2_update, seshid], [status_text, script_load3])

    script_load3.change(prepItem3ForScript, [script_load3, seshid], [script_load3_update])
    script_load3_update.change(updateItem3Status, [script_load3_update, seshid], [status_text, script_load4])

    script_load4.change(prepItem4ForScript, [script_load4, seshid], [script_load4_update])
    script_load4_update.change(updateItem4Status, [script_load4_update, seshid], [status_text, script_load5])

    script_load5.change(prepItem5ForScript, [script_load5, seshid], [script_load5_update])
    script_load5_update.change(updateItem5Status, [script_load5_update, seshid], [status_text, script_load6])

    script_load6.change(prepItem6ForScript, [script_load6, seshid], [script_load6_update])
    script_load6_update.change(updateItem6Status, [script_load6_update, seshid], [status_text, script_load7])

    script_load7.change(prepItem7ForScript, [script_load7, seshid], [script_load7_update])
    script_load7_update.change(updateItem7Status, [script_load7_update, seshid], [status_text, script_load8])

    script_load8.change(prepItem8ForScript, [script_load8, seshid], [script_load8_update])
    script_load8_update.change(updateItem8Status, [script_load8_update, seshid], [status_text, script_load9])

    script_load9.change(prepItem9ForScript, [script_load9, seshid], [script_load9_update])
    script_load9_update.change(updateItem9Status, [script_load9_update, seshid], [status_text, script_load10])

    script_load10.change(prepItem10ForScript, [script_load10, seshid], [script_load10_update])
    script_load10_update.change(updateItem10Status, [script_load10_update, seshid], [status_text, script_load11])

    script_load11.change(prepItem11ForScript, [script_load11, seshid], [script_load11_update])
    script_load11_update.change(updateItem11Status, [script_load11_update, seshid], [status_text, script_load12])

    script_load12.change(prepItem12ForScript, [script_load12, seshid], [script_load12_update])
    script_load12_update.change(updateItem12Status, [script_load12_update, seshid], [status_text, script_load13])

    script_load13.change(prepItem13ForScript, [script_load13, seshid], [script_load13_update])
    script_load13_update.change(updateItem13Status, [script_load13_update, seshid], [status_text, yt_load])

    yt_load.change(prepYTLongFormScript, [yt_load, seshid], [yt_update])
    yt_update.change(updateYTLongFormStatus, [yt_update, seshid], [status_text, ytshorts_load, scripts_drop])

    ytshorts_load.change(prepYTShortFormScript, [ytshorts_load, seshid], [ytshorts_update])
    ytshorts_update.change(updateYTShortFormStatus, [ytshorts_update, seshid], [status_text, facebook_load, scripts_drop])

    facebook_load.change(prepFBScript, [facebook_load, seshid], [facebook_update])
    facebook_update.change(updateFBStatus, [facebook_update, seshid], [status_text, reels_load, scripts_drop])

    reels_load.change(prepIGScript, [reels_load, seshid], [reels_update])
    reels_update.change(updateIGStatus, [reels_update, seshid], [status_text, tiktok_load, scripts_drop])

    tiktok_load.change(prepTikTokScript, [tiktok_load, seshid], [tiktok_update])
    tiktok_update.change(updateTikTokStatus, [tiktok_update, seshid], [status_text, linkedin_load, scripts_drop])

    linkedin_load.change(prepLinkedInScript, [linkedin_load, seshid], [linkedin_update])
    linkedin_update.change(updateLinkedInStatus, [linkedin_update, seshid], [status_text, scripts_drop])

    scripts_drop.select(selectScript, [seshid], script_display)






    room_items.select(roomItemClick, seshid, [items_display, item_side, room_side, colors_side, replace, ads, store_summary, seshid])
    close1.click(closeSidePanel, [seshid], [items_display, item_side, room_side, colors_side, merchant, replace, ads, store_summary])
    close2.click(closeSidePanel, [seshid], [items_display, item_side, room_side, colors_side, merchant, replace, ads, store_summary])
    close3.click(closeSidePanel, [seshid], [items_display, item_side, room_side, colors_side, merchant, replace, ads, store_summary])
    close4.click(closeSidePanel, [seshid], [items_display, item_side, room_side, colors_side, merchant, replace, ads, store_summary])
 

    upload_photo.click(submitPhoto, [upload, choose_room, seshid], [choose_room, upload, seshid])
    #choose_room.select(makePalettes, None, [color_Palettes, room2decorate, room_items])
    choose_room.select(makePalettes, [seshid], [color_Palettes, room2decorate, room_items])

    #upload_photo.click(submitPhoto, upload, [working_room, upload])
    #working_room.select(makePalettes, None, [working_room1, color_Palettes])
    #working_room.select(makePalettes, None, [working_room1, working_room2, working_room3, color_Palettes, room_items])
    working_room.select(makePalettes, seshid, [working_room1, working_room2, working_room3, color_Palettes, room_items])
    #rooms_gallery.select(set_style, None, [design_gallery, bedsize_radio, room_items])
    rooms_gallery.select(updateRoomType, seshid, [design_gallery, bedsize_radio, room_items])

    #color_Palettes.select(set_Palette, None, None)
    color_Palettes.select(updateColors, seshid, [room_items])

    design_gallery.select(updateStyle, seshid, room_items)
    price_radio.select(updatePrice, seshid, room_items)
    bedsize_radio.select(updateBedsize, seshid, room_items)

    replace.select(productClick, [seshid], merchant)
    replace_item.click(replaceProduct, [seshid], [items_display, item_side, room_side, colors_side, merchant, replace, ads, room_items])

    #summary_button.click(summarisePerStore, None, None) 
    summary_button.click(summaryClick, [seshid], [summary_button, design_accordion, update_accordion, room_ad, summary_group, replace, ads, store_summary, store_dropdown, merchant_top, total, num_of_items, complete_source_breakdown]) 

    store_dropdown.select(selectMerchantProduct, [seshid], [product_dropdown, merchant_top, total, num_of_items])
    complete_summary.select(changeSummaryFilter, [seshid], [merchant_top, total, num_of_items, product_summary, complete_source_breakdown, budget_row, store_dropdown]) 

    product_dropdown.select(displaySource, [seshid], [source, count])
    count.change(updateProductCount, [count, seshid], [total, num_of_items])
    budget.submit(updateBudget, [budget, seshid], [room_items, total, num_of_items])




demo.launch()