File size: 43,741 Bytes
ff099b9
f24f171
 
5a6a643
6ecc602
5140a89
c907607
f24f171
 
4c33be9
f24f171
 
4c33be9
f24f171
 
5a6a643
 
f24f171
8f90878
f24f171
c00b679
 
 
e575ced
88e8aaa
 
1492cfb
dcf25eb
 
 
9eba640
1492cfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e946e53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1492cfb
e946e53
1492cfb
e946e53
 
 
 
 
 
 
 
 
 
 
 
1492cfb
 
 
e946e53
1492cfb
 
 
e946e53
 
 
1492cfb
 
 
 
 
 
 
 
 
 
e946e53
1492cfb
 
 
e946e53
1492cfb
 
 
9d57e80
cdabdd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dda1d8
9881db4
97b3f03
9881db4
 
 
 
 
6e703d5
97b3f03
9881db4
 
 
 
 
 
97b3f03
9881db4
 
 
 
 
 
 
 
 
 
97b3f03
5ed82ea
9881db4
5ed82ea
9881db4
 
 
97b3f03
9881db4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97b3f03
5ed82ea
97b3f03
5ed82ea
97b3f03
9881db4
 
 
 
 
 
97b3f03
9881db4
 
1492cfb
 
 
 
 
 
 
 
cdabdd7
 
 
 
 
 
 
 
 
9eba640
 
 
 
 
 
 
 
 
cdabdd7
9eba640
cdabdd7
c00b679
 
 
 
 
 
3538bec
 
 
 
c00b679
 
 
 
 
 
 
f24f171
c00b679
 
 
3538bec
 
 
 
 
 
c00b679
 
 
 
 
 
1a68cc7
 
 
 
 
 
 
 
f24f171
5a6a643
 
c907607
69162b3
 
 
c907607
f24f171
c907607
 
f24f171
 
 
 
 
c907607
 
 
f24f171
 
 
 
 
 
 
 
5a6c7a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f24f171
 
5a6c7a7
 
f24f171
c907607
f24f171
454b9fc
f24f171
 
c907607
4c33be9
f24f171
4c33be9
 
f24f171
 
 
4c33be9
 
f24f171
 
 
4c33be9
 
f24f171
 
 
e575ced
4c33be9
e575ced
f24f171
 
c907607
f24f171
 
 
 
 
 
 
 
 
 
 
 
 
 
4c33be9
 
c907607
f24f171
 
 
 
5a6a643
f24f171
5a6a643
 
f24f171
 
5a6a643
 
 
 
 
 
 
 
 
 
f24f171
 
 
 
 
 
 
c907607
 
 
 
 
f24f171
5a6a643
c907607
f24f171
c907607
 
f24f171
5a6a643
f24f171
 
 
 
 
 
c907607
f24f171
 
5a6a643
 
 
 
 
 
 
 
 
f24f171
 
c907607
f24f171
c907607
 
 
 
 
5a6a643
c907607
 
 
 
 
 
 
 
 
 
5a6a643
c907607
 
 
 
 
 
f24f171
c907607
 
 
5a6a643
f24f171
 
 
 
 
 
 
 
 
 
 
 
5a6a643
f24f171
 
 
 
 
 
 
 
 
 
5a6a643
f24f171
c907607
5a6a643
c907607
 
 
 
f24f171
c907607
 
f24f171
c907607
 
5a6a643
c907607
5a6a643
 
 
 
 
 
 
 
 
 
 
 
 
 
c907607
 
f24f171
c907607
f24f171
c907607
69162b3
f24f171
69162b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f24f171
69162b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f24f171
69162b3
c907607
69162b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c907607
d7b0d8c
 
 
 
 
 
d61861b
d7b0d8c
 
 
 
 
 
 
 
 
 
 
 
 
 
c00b679
d7b0d8c
 
 
 
c00b679
d7b0d8c
 
c00b679
d7b0d8c
 
 
d61861b
c00b679
d7b0d8c
 
 
 
 
 
c00b679
 
 
d7b0d8c
 
 
c00b679
d7b0d8c
c00b679
 
d7b0d8c
 
 
 
 
 
 
 
 
c00b679
d7b0d8c
 
c00b679
d7b0d8c
c00b679
d7b0d8c
 
 
d61861b
c00b679
d61861b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f24f171
 
 
 
 
 
 
5a6a643
f24f171
5a6a643
 
f24f171
 
5a6a643
f24f171
5a6a643
 
 
 
 
 
 
f24f171
 
 
 
5a6a643
f24f171
 
 
 
5a6a643
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c907607
f24f171
c907607
f24f171
 
 
 
 
 
 
 
 
 
 
 
c907607
 
 
f24f171
 
c907607
f24f171
 
c907607
5a6a643
f24f171
 
 
 
 
 
1ec0cbb
c00b679
1ec0cbb
 
 
 
 
 
 
1492cfb
 
 
 
 
1ec0cbb
1492cfb
 
 
 
1ec0cbb
 
 
 
 
 
c00b679
1ec0cbb
 
f24f171
1ec0cbb
1492cfb
cdabdd7
1492cfb
 
5412a1d
 
1492cfb
5412a1d
1492cfb
 
 
 
5412a1d
1492cfb
 
 
 
5412a1d
1492cfb
 
 
 
 
 
5412a1d
 
 
 
 
1492cfb
 
 
 
cdabdd7
1492cfb
 
cdabdd7
 
1492cfb
5412a1d
1492cfb
 
9881db4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1492cfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5140a89
 
f24f171
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
import streamlit as st
from pathlib import Path
import torch
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
from PIL import Image, ImageDraw, ImageFont
import tempfile
import os
from moviepy.editor import *
import numpy as np
from gtts import gTTS
import textwrap
from concurrent.futures import ThreadPoolExecutor
import io
import unicodedata
import re
import requests
import random
import logging
import time
from typing import Optional, List, Dict, Tuple
from bs4 import BeautifulSoup
import requests
from io import BytesIO

class ImageScraper:
    def __init__(self):
        self.PIXABAY_API_KEY = "48069976-37e20099248207cee12385560"
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        self.temp_dir = Path(tempfile.mkdtemp())
        
        # Initialize keyword extractor model
        try:
            self.keyword_model = pipeline(
                "text-classification",
                model="facebook/bart-large-mnli",
                device=0 if torch.cuda.is_available() else -1
            )
        except Exception as e:
            print(f"Failed to load keyword model: {e}")
            self.keyword_model = None

    def extract_keywords(self, text: str) -> List[Dict[str, str]]:
        """Extract relevant keywords and categories from text using AI"""
        keywords = []
        
        try:
            # Define candidate labels for classification
            candidate_labels = [
                "technology", "science", "education", "business",
                "health", "nature", "people", "urban", "abstract",
                "sports", "food", "travel", "architecture", "art",
                "music", "fashion", "medical", "industrial", "space",
                "environmental", "historical", "cultural", "professional"
            ]
            
            # Use model to classify text against each label
            if self.keyword_model:
                results = self.keyword_model(text, candidate_labels, multi_label=True)
                
                # Filter results with high confidence
                for score, label in zip(results['scores'], results['labels']):
                    if score > 0.3:  # Confidence threshold
                        keywords.append({
                            'keyword': label,
                            'confidence': score,
                            'category': self.categorize_keyword(label)
                        })
            
            # Extract additional keywords using NLP
            additional_keywords = self.extract_noun_phrases(text)
            for keyword in additional_keywords:
                keywords.append({
                    'keyword': keyword,
                    'confidence': 0.5,
                    'category': 'content_specific'
                })
            
            # Sort by confidence
            keywords = sorted(keywords, key=lambda x: x['confidence'], reverse=True)
            
            return keywords
            
        except Exception as e:
            print(f"Keyword extraction error: {e}")
            return self.get_fallback_keywords()

    def extract_noun_phrases(self, text: str) -> List[str]:
        """Extract important noun phrases from text"""
        words = text.lower().split()
        phrases = []
        
        # Common adjectives that might indicate important concepts
        adjectives = {'digital', 'smart', 'modern', 'advanced', 'innovative', 
                     'technical', 'professional', 'creative', 'strategic'}
                     
        for i in range(len(words)-1):
            if words[i] in adjectives:
                phrases.append(f"{words[i]} {words[i+1]}")
                
        return list(set(phrases))

    def categorize_keyword(self, keyword: str) -> str:
        """Categorize keyword into general themes"""
        categories = {
            'technical': {'technology', 'digital', 'software', 'computer', 'cyber'},
            'scientific': {'science', 'research', 'laboratory', 'experiment'},
            'business': {'business', 'professional', 'corporate', 'office'},
            'educational': {'education', 'learning', 'teaching', 'academic'},
            'creative': {'art', 'design', 'creative', 'innovation'},
        }
        
        for category, terms in categories.items():
            if any(term in keyword.lower() for term in terms):
                return category
        return 'general'


    def extract_key_topics(self, script: str) -> List[str]:
        """Extract key topics from a long text prompt with improved accuracy"""
        try:
            # Define relevant categories for VaultGenix
            categories = {
                'security': ['security', 'encryption', 'protection', 'privacy', 'safe', 'secure'],
                'digital': ['digital', 'online', 'virtual', 'cyber', 'electronic'],
                'legacy': ['legacy', 'inheritance', 'heir', 'posthumous', 'estate'],
                'management': ['management', 'planning', 'organization', 'control', 'administration'],
                'technology': ['AI', 'artificial intelligence', 'technology', 'platform', 'system'],
                'family': ['family', 'heir', 'custodian', 'relative', 'loved ones']
            }
            
            # Process text
            text = script.lower()
            found_topics = set()
            
            # Extract single-word matches
            words = text.split()
            for category, terms in categories.items():
                for term in terms:
                    if term in text:
                        found_topics.add(term)
                        found_topics.add(category)
            
            # Extract meaningful phrases
            important_phrases = [
                'digital legacy',
                'legacy management',
                'digital security',
                'data protection',
                'artificial intelligence',
                'digital estate',
                'digital identity',
                'secure platform',
                'family protection',
                'digital inheritance'
            ]
            
            for phrase in important_phrases:
                if phrase in text:
                    found_topics.add(phrase)
            
            # Combine related topics
            combined_topics = []
            for topic in found_topics:
                # Create meaningful combinations
                if topic in ['digital', 'secure', 'smart', 'AI']:
                    related = ['legacy', 'security', 'protection', 'management']
                    for rel in related:
                        if rel in found_topics:
                            combined_topics.append(f"{topic} {rel}")
            
            # Add combined topics to results
            found_topics.update(combined_topics)
            
            # Prioritize topics
            priority_topics = [
                topic for topic in found_topics 
                if any(key in topic for key in ['digital', 'security', 'legacy', 'AI'])
            ]
            
            # Ensure we have enough topics
            if len(priority_topics) < 3:
                priority_topics.extend(['digital security', 'legacy management', 'data protection'][:3 - len(priority_topics)])
            
            return list(set(priority_topics))[:5]  # Return top 5 unique topics
            
        except Exception as e:
            print(f"Topic extraction error: {e}")
            return ['digital security', 'legacy management', 'data protection']

    def get_images_for_keyword(self, keyword: str) -> List[Dict[str, str]]:
        """Get images for a specific keyword with improved relevance"""
        try:
            # Enhance keyword for better search results
            enhanced_keywords = {
                'digital': 'digital technology security',
                'security': 'cybersecurity protection',
                'legacy': 'digital legacy inheritance',
                'management': 'digital management system',
                'AI': 'artificial intelligence technology',
                'protection': 'data protection security'
            }
            
            search_term = enhanced_keywords.get(keyword, keyword)
            
            base_url = "https://pixabay.com/api/"
            params = {
                'key': self.PIXABAY_API_KEY,
                'q': search_term,
                'image_type': 'photo',
                'per_page': 5,
                'safesearch': True,
                'lang': 'en',
                'category': 'technology',  # Focus on technology category
                'orientation': 'horizontal'  # Better for video
            }
            
            response = requests.get(base_url, params=params, headers=self.headers)
            
            if response.status_code == 200:
                data = response.json()
                if 'hits' in data and data['hits']:
                    return [{
                        'url': img['largeImageURL'],
                        'keyword': keyword,
                        'relevance': 'Primary match' if keyword.lower() in img['tags'].lower() else 'Related',
                        'tags': img['tags']
                    } for img in data['hits']]
            return []
            
        except Exception as e:
            print(f"Error fetching images for keyword {keyword}: {e}")
            return []

    def get_pixabay_images(self, query: str) -> List[str]:
        """Get images from Pixabay API with enhanced error handling"""
        try:
            # Clean and encode the query
            clean_query = query.replace(' ', '+').strip()
            base_url = "https://pixabay.com/api/"
            
            params = {
                'key': self.PIXABAY_API_KEY,
                'q': clean_query,
                'image_type': 'photo',
                'per_page': 20,
                'safesearch': True,
                'lang': 'en'
            }
            
            response = requests.get(base_url, params=params, headers=self.headers)
            
            # Debug logging
            print(f"Pixabay API URL: {response.url}")
            print(f"Response status: {response.status_code}")
            
            if response.status_code == 200:
                data = response.json()
                print(f"Total hits: {data.get('totalHits', 0)}")
                if 'hits' in data and data['hits']:
                    image_urls = [img['largeImageURL'] for img in data['hits']]
                    print(f"Found {len(image_urls)} images")
                    return image_urls
                else:
                    print("No images found in response")
                    return self.get_stock_images()
            else:
                print(f"Pixabay API error: Status code {response.status_code}")
                return self.get_stock_images()
                
        except Exception as e:
            print(f"Exception in get_pixabay_images: {str(e)}")
            return self.get_stock_images()

    def get_stock_images(self) -> List[str]:
        """Return preset stock images as fallback"""
        return [
            "https://images.pexels.com/photos/60504/security-protection-anti-virus-software-60504.jpeg",
            "https://images.pexels.com/photos/5380642/pexels-photo-5380642.jpeg",
            "https://images.pexels.com/photos/2582937/pexels-photo-2582937.jpeg",
            "https://images.pexels.com/photos/7319074/pexels-photo-7319074.jpeg",
            "https://images.pexels.com/photos/4164418/pexels-photo-4164418.jpeg",
            "https://images.pexels.com/photos/3861969/pexels-photo-3861969.jpeg",
            "https://images.pexels.com/photos/5473298/pexels-photo-5473298.jpeg",
            "https://images.pexels.com/photos/4348401/pexels-photo-4348401.jpeg",
            "https://images.pexels.com/photos/8386440/pexels-photo-8386440.jpeg",
            "https://images.pexels.com/photos/5473950/pexels-photo-5473950.jpeg"
        ]

    def get_images(self, query: str, num_images: int = 15) -> Dict[str, List[Dict[str, str]]]:
        """Get images for either single word queries or extract keywords from long prompts"""
        try:
            # Initialize result structure
            result = {
                'primary': [],
                'secondary': [],
                'general': []
            }
            
            # Extract keywords if query is long
            if len(query.split()) > 3:
                keywords = self.extract_key_topics(query)
                print(f"Extracted keywords: {keywords}")  # Debug log
            else:
                keywords = [query]
            
            # Fetch images for each keyword
            for keyword in keywords:
                base_url = "https://pixabay.com/api/"
                params = {
                    'key': self.PIXABAY_API_KEY,
                    'q': keyword,
                    'image_type': 'photo',
                    'per_page': max(3, num_images // len(keywords)),  # Distribute images among keywords
                    'safesearch': True,
                    'lang': 'en'
                }
                
                response = requests.get(base_url, params=params, headers=self.headers)
                
                if response.status_code == 200:
                    data = response.json()
                    hits = data.get('hits', [])
                    
                    for hit in hits:
                        image_data = {
                            'url': hit['largeImageURL'],
                            'keyword': keyword,
                            'relevance': 'Primary match',
                            'tags': hit.get('tags', '')
                        }
                        
                        # Distribute images across categories
                        if len(result['primary']) < num_images // 3:
                            result['primary'].append(image_data)
                        elif len(result['secondary']) < num_images // 3:
                            result['secondary'].append(image_data)
                        else:
                            result['general'].append(image_data)
            
            # If no images found, use stock images
            if not any(result.values()):
                stock_images = self.get_stock_images()
                result['general'] = [{
                    'url': url,
                    'keyword': 'technology',
                    'relevance': 'Fallback',
                    'tags': 'technology'
                } for url in stock_images[:num_images]]
            
            return result
            
        except Exception as e:
            print(f"Error in get_images: {str(e)}")
            # Return stock images as fallback
            stock_images = self.get_stock_images()
            return {
                'general': [{
                    'url': url,
                    'keyword': 'technology',
                    'relevance': 'Fallback',
                    'tags': 'technology'
                } for url in stock_images[:num_images]]
            }
                
                
    def get_fallback_keywords(self) -> List[Dict[str, str]]:
        """Return fallback keywords if AI extraction fails"""
        return [
            {'keyword': 'technology', 'confidence': 1.0, 'category': 'technical'},
            {'keyword': 'business', 'confidence': 0.8, 'category': 'business'},
            {'keyword': 'professional', 'confidence': 0.8, 'category': 'business'},
            {'keyword': 'digital', 'confidence': 0.7, 'category': 'technical'}
        ]

    def verify_image_url(self, url: str) -> bool:
        """Verify if an image URL is accessible"""
        try:
            response = requests.head(url, timeout=5)
            return response.status_code == 200
        except:
            return False

    def generate_fallback_audio(self, script: str) -> AudioFileClip:
        """Generate fallback audio using gTTS"""
        try:
            audio_path = self.temp_dir / "voice.mp3"
            tts = gTTS(text=script, lang='en', slow=False)
            tts.save(str(audio_path))
            return AudioFileClip(str(audio_path))
        except Exception as e:
            print(f"Fallback audio generation failed: {e}")
            duration = len(script.split()) * 0.3
            return AudioFileClip(duration=duration)

    def scrape_pexels(self, query: str) -> List[str]:
        urls = []
        try:
            url = f"https://www.pexels.com/search/{query.replace(' ', '%20')}/"
            response = requests.get(url, headers=self.headers)
            soup = BeautifulSoup(response.text, 'html.parser')
            
            # Updated selector to target image sources
            for img in soup.find_all('img', {'data-image-width': True}):
                if img.get('src') and 'photos' in img['src']:
                    urls.append(img['src'])
        except Exception as e:
            print(f"Pexels scraping error: {e}")
        return urls

    def scrape_unsplash(self, query: str) -> List[str]:
        urls = []
        try:
            url = f"https://unsplash.com/s/photos/{query.replace(' ', '-')}"
            response = requests.get(url, headers=self.headers)
            soup = BeautifulSoup(response.text, 'html.parser')
            
            # Updated selector for Unsplash
            for img in soup.find_all('img', {'srcset': True}):
                src = img.get('src')
                if src and 'images.unsplash.com' in src:
                    urls.append(src)
        except Exception as e:
            print(f"Unsplash scraping error: {e}")
        return urls

class EnhancedVideoGenerator:
    def __init__(self):
        try:
            self.setup_logging()
            self.setup_device()
            self.initialize_models()
            self.setup_workspace()
            self.load_assets()
            self.setup_themes()
            self.image_scraper = ImageScraper()
        except Exception as e:
            logging.error(f"Initialization failed: {str(e)}")
            raise RuntimeError("Failed to initialize video generator")

            self.ELEVEN_LABS_API_KEY = "sk_acdad9d2d82d504bddbe5ed4aa290ca772c106aed5b128ba"  # Replace with your key
            

    def setup_logging(self):
        """Configure logging for the application"""
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler('video_generator.log'),
                logging.StreamHandler()
            ]
        )
        self.logger = logging.getLogger(__name__)

    def setup_device(self):
        """Set up computing device (CPU/GPU)"""
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
        self.logger.info(f"Using device: {self.device}")

    def initialize_models(self):
        """Initialize all AI models"""
        try:
            # Text generation model initialization with error handling
            try:
                self.text_generator = pipeline(
                    'text-generation',
                    model='gpt2',
                    device=0 if self.device == "cuda" else -1
                )
            except Exception as e:
                self.logger.warning(f"Text generator initialization failed: {str(e)}")
                self.text_generator = None
    
            # Skip the StableDiffusion model initialization as it requires additional setup
            self.image_model = None
            
            # Initialize stability API attribute
            self.stability_api = None
    
        except Exception as e:
            self.logger.error(f"Model initialization failed: {str(e)}")
            # Don't raise exception, allow initialization with degraded functionality
            pass

    def setup_workspace(self):
        """Set up working directory and resources"""
        self.temp_dir = Path(tempfile.mkdtemp())
        self.asset_dir = self.temp_dir / "assets"
        self.asset_dir.mkdir(exist_ok=True)

    def setup_themes(self):
        """Set up visual themes"""
        self.themes = {
            'Professional': {
                'bg': (240, 240, 240),
                'accent': (0, 120, 212),
                'text': (33, 33, 33)
            },
            'Creative': {
                'bg': (255, 250, 240),
                'accent': (255, 123, 0),
                'text': (51, 51, 51)
            },
            'Educational': {
                'bg': (248, 249, 250),
                'accent': (40, 167, 69),
                'text': (33, 37, 41)
            }
        }

    def load_assets(self):
        """Load visual assets and fonts"""
        try:
            # Try multiple font options
            font_options = [
                "arial.ttf",
                "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
                "/System/Library/Fonts/Helvetica.ttc"
            ]
            
            for font_path in font_options:
                try:
                    self.font = ImageFont.truetype(font_path, 40)
                    break
                except OSError:
                    continue
            else:
                self.font = ImageFont.load_default()
                self.logger.warning("Using default font - custom font loading failed")

        except Exception as e:
            self.logger.error(f"Asset loading failed: {str(e)}")

    def generate_visual_assets(self, script: str, style: str) -> List[Dict]:
        """Generate relevant visual assets based on script content"""
        try:
            # Extract key topics from script
            topics = self.extract_key_topics(script)
            
            assets = []
            for topic in topics:
                # Generate AI image
                image = self.generate_ai_image(topic, style)
                if image:
                    assets.append({
                        'type': 'image',
                        'data': image,
                        'topic': topic
                    })

            return assets

        except Exception as e:
            self.logger.error(f"Visual asset generation failed: {str(e)}")
            return []

    def create_enhanced_frame(
        self,
        text: str,
        theme: dict,
        frame_number: int,
        total_frames: int,
        background_image: Optional[Image.Image] = None,
        size: Tuple[int, int] = (1920, 1080)  # Upgraded to 1080p
    ) -> np.ndarray:
        """Create a visually enhanced frame with background, text, and effects"""
        try:
            # Create base frame
            if background_image:
                # Resize and crop background to fit
                bg = background_image.resize(size, Image.LANCZOS)
                frame = np.array(bg)
            else:
                frame = np.full((size[1], size[0], 3), theme['bg'], dtype=np.uint8)

            # Convert to PIL Image for drawing
            img = Image.fromarray(frame)
            draw = ImageDraw.Draw(img, 'RGBA')

            # Add subtle gradient overlay
            overlay = Image.new('RGBA', size, (0, 0, 0, 0))
            overlay_draw = ImageDraw.Draw(overlay)
            overlay_draw.rectangle(
                [0, 0, size[0], size[1]],
                fill=(255, 255, 255, 100)  # Semi-transparent white
            )
            img = Image.alpha_composite(img.convert('RGBA'), overlay)

            # Add text with improved styling
            text = self.clean_text(text)
            wrapped_text = textwrap.fill(text, width=50)
            
            # Calculate text position
            text_bbox = draw.textbbox((0, 0), wrapped_text, font=self.font)
            text_width = text_bbox[2] - text_bbox[0]
            text_height = text_bbox[3] - text_bbox[1]
            text_x = (size[0] - text_width) // 2
            text_y = size[1] - text_height - 100  # Position at bottom

            # Draw text background
            padding = 20
            draw.rectangle(
                [
                    text_x - padding,
                    text_y - padding,
                    text_x + text_width + padding,
                    text_y + text_height + padding
                ],
                fill=(0, 0, 0, 160)  # Semi-transparent black
            )

            # Draw text
            draw.text(
                (text_x, text_y),
                wrapped_text,
                fill=(255, 255, 255, 255),
                font=self.font
            )

            # Add progress bar with animation
            self.draw_animated_progress_bar(
                draw,
                frame_number,
                total_frames,
                size,
                theme
            )

            return np.array(img)

        except Exception as e:
            self.logger.error(f"Frame creation failed: {str(e)}")
            # Return fallback frame
            return np.full((size[1], size[0], 3), theme['bg'], dtype=np.uint8)

    def draw_animated_progress_bar(
        self,
        draw: ImageDraw.Draw,
        frame_number: int,
        total_frames: int,
        size: Tuple[int, int],
        theme: dict
    ):
        """Draw an animated progress bar with effects"""
        try:
            progress = frame_number / total_frames
            bar_width = int(size[0] * 0.8)  # 80% of screen width
            bar_height = 6
            x_offset = (size[0] - bar_width) // 2
            y_position = size[1] - 40

            # Draw background bar
            draw.rectangle(
                [x_offset, y_position, x_offset + bar_width, y_position + bar_height],
                fill=(200, 200, 200, 160)
            )

            # Draw progress with gradient effect
            progress_width = int(bar_width * progress)
            for x in range(progress_width):
                alpha = int(255 * (x / bar_width))  # Gradient effect
                draw.line(
                    [x_offset + x, y_position, x_offset + x, y_position + bar_height],
                    fill=(theme['accent'][0], theme['accent'][1], theme['accent'][2], alpha)
                )

            # Add animated highlight
            highlight_pos = x_offset + progress_width
            if highlight_pos < x_offset + bar_width:
                draw.rectangle(
                    [highlight_pos-2, y_position-1, highlight_pos+2, y_position + bar_height+1],
                    fill=(255, 255, 255, 200)
                )

        except Exception as e:
            self.logger.error(f"Progress bar drawing failed: {str(e)}")

    def generate_voice_over(self, script: str) -> AudioFileClip:
        try:
            # Try ElevenLabs first
            audio_path = self.temp_dir / "voice.mp3"
            
            headers = {
                "xi-api-key": self.ELEVEN_LABS_API_KEY,
                "Content-Type": "application/json"
            }
            
            data = {
                "text": script,
                "model_id": "eleven_monolingual_v1",
                "voice_settings": {
                    "stability": 0.75,
                    "similarity_boost": 0.75
                }
            }
            
            response = requests.post(
                "https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM",
                headers=headers,
                json=data
            )
            
            if response.status_code == 200:
                with open(audio_path, "wb") as f:
                    f.write(response.content)
            else:
                # Fallback to Azure TTS
                speech_config = speechsdk.SpeechConfig(
                    subscription=self.AZURE_SPEECH_KEY,
                    region=self.AZURE_REGION
                )
                speech_config.speech_synthesis_voice_name = "en-US-JennyNeural"
                
                synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config)
                result = synthesizer.speak_text_async(script).get()
                
                if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
                    with open(audio_path, "wb") as f:
                        f.write(result.audio_data)
            
            return AudioFileClip(str(audio_path))
            
        except Exception as e:
            print(f"Voice generation error: {e}")
            return self.generate_fallback_audio(script)

    def generate_subtitles(self, script: str, duration: int) -> str:
        words = script.split()
        words_per_second = len(words) / duration
        subtitle_path = self.temp_dir / "subtitles.srt"
        
        with open(subtitle_path, 'w') as f:
            current_time = 0
            words_per_subtitle = int(words_per_second * 3)  # 3 seconds per subtitle
            
            for i in range(0, len(words), words_per_subtitle):
                subtitle_words = words[i:i + words_per_subtitle]
                if subtitle_words:
                    start_time = self.format_time(current_time)
                    current_time += len(subtitle_words) / words_per_second
                    end_time = self.format_time(current_time)
                    
                    f.write(f"{i//words_per_subtitle + 1}\n")
                    f.write(f"{start_time} --> {end_time}\n")
                    f.write(f"{' '.join(subtitle_words)}\n\n")
        
        return str(subtitle_path)

    @staticmethod
    def format_time(seconds: float) -> str:
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        secs = int(seconds % 60)
        msecs = int((seconds - int(seconds)) * 1000)
        return f"{hours:02d}:{minutes:02d}:{secs:02d},{msecs:03d}"

    def create_video(self, script: str, style: str, duration: int, output_path: str, selected_images: List[str]) -> str:
        """Create video with selected images"""
        try:
            # Progress bar
            progress_bar = st.progress(0)
            status_text = st.empty()
            
            # Generate voice-over (20%)
            status_text.text("Creating voice-over...")
            audio = self.generate_voice_over(script)
            progress_bar.progress(20)
            
            # Process selected images (40%)
            status_text.text("Processing images...")
            processed_images = []
            for img_url in selected_images:
                response = requests.get(img_url)
                img = Image.open(BytesIO(response.content))
                img = img.resize((1920, 1080), Image.Resampling.LANCZOS)
                processed_images.append(np.array(img))
            progress_bar.progress(40)
                
            # Create frames with transitions
            fps = 30
            total_frames = int(duration * fps)
            frames = []
                
            status_text.text("Generating frames...")
            frames_per_image = total_frames // len(processed_images)
                
            for idx, img in enumerate(processed_images):
                for _ in range(frames_per_image):
                    frames.append(img)
                        
                    # Add transition frames
                if idx < len(processed_images) - 1:
                    next_img = processed_images[idx + 1]
                    for alpha in np.linspace(0, 1, 15):
                        transition_frame = (1 - alpha) * img + alpha * next_img
                        frames.append(transition_frame.astype(np.uint8))
                        
                progress_bar.progress(70)
                
                # Create video clip
            status_text.text("Compiling video...")
            video = ImageSequenceClip(frames, fps=fps)
            video = video.set_audio(audio)
                
            progress_bar.progress(90)
                
                # Write final video
            status_text.text("Saving video...")
            video.write_videofile(
                output_path,
                fps=fps,
                codec='libx264',
                audio_codec='aac',
                threads=4,
                preset='ultrafast'
            )
                
            progress_bar.progress(100)
            status_text.text("Video generation complete!")
                
            return output_path
                
        except Exception as e:
            self.logger.error(f"Video creation failed: {str(e)}")
            raise
    
        
    def generate_visual_assets(self, script: str, style: str) -> List[Dict]:
        """Generate relevant visual assets based on script content"""
        try:
            # Simplified asset generation for faster processing
            topics = self.extract_key_topics(script)[:3]  # Limit to 3 topics
            
            assets = []
            for topic in topics:
                # Create simple colored backgrounds instead of AI images
                img = Image.new('RGB', (1920, 1080), self.themes[style]['bg'])
                assets.append({
                    'type': 'image',
                    'data': img,
                    'topic': topic
                })
    
            return assets
    
        except Exception as e:
            self.logger.error(f"Visual asset generation failed: {str(e)}")
            return []

    @staticmethod
    def clean_text(text: str) -> str:
        """Clean and normalize text for display"""
        if not isinstance(text, str):
            text = str(text)
        
        # Normalize unicode characters
        text = unicodedata.normalize('NFKD', text)
        
        # Remove non-ASCII characters
        text = text.encode('ascii', 'ignore').decode('ascii')
        
        # Replace problematic characters
        replacements = {
            '–': '-',    # en dash
            '—': '-',    # em dash
            '"': '"',    # smart quotes
            '"': '"',    # smart quotes
            ''': "'",    # smart apostrophe
            ''': "'",    # smart apostrophe
            '…': '...',  # ellipsis
        }
        for old, new in replacements.items():
            text = text.replace(old, new)
        
        # Remove any remaining non-standard characters
        text = re.sub(r'[^\x00-\x7F]+', '', text)
        
        return text.strip()

    def generate_ai_image(self, prompt: str, style: str) -> Optional[Image.Image]:
        """Generate an AI image using Stability AI"""
        try:
            if not self.stability_api:
                return None

            # Enhance prompt based on style
            style_prompts = {
                'Professional': "professional, corporate, clean, modern",
                'Creative': "artistic, vibrant, innovative, dynamic",
                'Educational': "clear, informative, academic, detailed"
            }
            
            enhanced_prompt = f"{prompt}, {style_prompts.get(style, '')}, high quality, 4k"
            
            # Generate image
            response = self.stability_api.generate(
                prompt=enhanced_prompt,
                samples=1,
                width=1920,
                height=1080
            )
            
            if response and len(response) > 0:
                image_data = response[0].image
                return Image.open(io.BytesIO(image_data))
            
            return None

        except Exception as e:
            self.logger.error(f"AI image generation failed: {str(e)}")
            return None

    def cleanup(self):
        """Clean up temporary files and resources"""
        try:
            for file in self.temp_dir.glob('*'):
                try:
                    if file.is_file():
                        file.unlink()
                    elif file.is_dir():
                        import shutil
                        shutil.rmtree(file)
                except Exception as e:
                    self.logger.warning(f"Failed to delete {file}: {str(e)}")
            
            self.temp_dir.rmdir()
            
        except Exception as e:
            self.logger.error(f"Cleanup failed: {str(e)}")

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.cleanup()

# Streamlit UI Class
class VideoGeneratorUI:
    def __init__(self):
        self.generator = EnhancedVideoGenerator()
        self.setup_ui()

    def setup_ui(self):
        st.set_page_config(layout="wide")
        
        # Custom CSS
        st.markdown("""
            <style>
            .stApp {
                max-width: 1200px;
                margin: 0 auto;
            }
            .image-category {
                margin-top: 2rem;
                padding: 1rem;
                border-radius: 0.5rem;
                background: #f8f9fa;
            }
            .image-metadata {
                font-size: 0.8rem;
                color: #666;
                margin-top: 0.5rem;
            }
            </style>
        """, unsafe_allow_html=True)

        st.title("VaultGenix Video Generator")
        st.markdown("Create professional videos for your digital legacy management platform")
        
        with st.container():
            prompt = st.text_area("Enter your video script", height=200)
            
            if prompt:
                with st.spinner("Analyzing prompt and fetching relevant images..."):
                    try:
                        # Get categorized images
                        image_categories = self.generator.image_scraper.get_images(prompt)
                            
                        if image_categories and isinstance(image_categories, dict):  # Check if it's a dictionary
                            # Display primary matches
                            if 'primary' in image_categories and image_categories['primary']:
                                st.subheader("Most Relevant Images")
                                self.display_image_grid(image_categories['primary'])
                            
                            # Display secondary matches
                            if 'secondary' in image_categories and image_categories['secondary']:
                                st.subheader("Related Images")
                                self.display_image_grid(image_categories['secondary'])
                            
                            # Display general/fallback images
                            if 'general' in image_categories and image_categories['general']:
                                st.subheader("Additional Suggested Images")
                                self.display_image_grid(image_categories['general'])
                            
                            # Collect selected images
                            selected_images = []
                            for category in image_categories.values():
                                if isinstance(category, list):  # Ensure category is a list
                                    for img in category:
                                        key = f"img_{img['url']}"
                                        if st.session_state.get(key, False):
                                            selected_images.append(img['url'])
                            
                            # Video generation section
                            if selected_images:
                                self.show_video_settings(prompt, selected_images)
                        else:
                            st.warning("No images found. Please try a different prompt.")
                            
                    except Exception as e:
                        st.error(f"An error occurred: {str(e)}")
                        print(f"Error in UI: {str(e)}")
    
    def display_image_grid(self, images: List[Dict[str, str]], cols: int = 3):
        """Display images in a grid with metadata"""
        # Ensure images is a list and not empty
        if not images or not isinstance(images, list):
            return
        
        # Calculate number of rows needed
        n_images = len(images)
        n_rows = (n_images + cols - 1) // cols
        
        # Create grid
        for row in range(n_rows):
            with st.container():
                columns = st.columns(cols)
                for col in range(cols):
                    idx = row * cols + col
                    if idx < n_images:
                        img = images[idx]
                        with columns[col]:
                            try:
                                st.image(img['url'], use_container_width=True)
                                st.checkbox(
                                    "Select",
                                    key=f"img_{img['url']}",
                                    help=f"Keywords: {img['keyword']}\nTags: {img['tags']}"
                                )
                                st.markdown(
                                    f"<div class='image-metadata'>"
                                    f"Relevance: {img['relevance']}<br>"
                                    f"Keywords: {img['keyword']}"
                                    f"</div>",
                                    unsafe_allow_html=True
                                )
                            except Exception as e:
                                print(f"Error displaying image: {e}")
    
    def show_video_settings(self, prompt: str, selected_images: List[str]):
        """Show video generation settings and controls"""
        st.subheader("Video Settings")
        col1, col2 = st.columns(2)
        with col1:
            style = st.selectbox(
                "Choose style",
                options=["Professional", "Creative", "Educational"],
                index=0
            )
        with col2:
            duration = st.slider(
                "Video duration (seconds)",
                min_value=30,
                max_value=180,
                value=60,
                step=30
            )

        if st.button("Generate Video", type="primary"):
            self.generate_video(prompt, style, duration, selected_images)

    def generate_video(self, prompt: str, style: str, duration: int, selected_images: List[str]):
        """Handle video generation"""
        with st.spinner("Generating your video..."):
            try:
                output_path = f"vaultgenix_video_{int(time.time())}.mp4"
                video_path = self.generator.create_video(
                    prompt,
                    style,
                    duration,
                    output_path,
                    selected_images
                )
                
                if os.path.exists(video_path):
                    st.success("✨ Video generated successfully!")
                    st.video(video_path)
                    
                    with open(video_path, 'rb') as video_file:
                        st.download_button(
                            "⬇️ Download Video",
                            video_file.read(),
                            file_name=output_path,
                            mime="video/mp4"
                        )
            except Exception as e:
                st.error(f"Failed to generate video: {str(e)}")
                print(f"Video generation error: {str(e)}")

if __name__ == "__main__":
    ui = VideoGeneratorUI()