File size: 38,095 Bytes
3f1f4af
5b510b1
97f8628
44ee7c9
97f8628
aa1565f
44ee7c9
 
3f1f4af
7922c49
5b510b1
3234a6f
3f1f4af
059772d
 
44ee7c9
 
 
5b510b1
5702453
367454a
44ee7c9
 
 
 
 
 
 
3f1f4af
97f8628
059772d
 
5b510b1
059772d
 
d555e1d
5702453
 
 
 
 
 
 
97f8628
 
 
 
44ee7c9
 
 
97f8628
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44ee7c9
 
97f8628
 
 
 
 
 
 
 
 
 
 
 
44ee7c9
97f8628
 
 
 
 
 
44ee7c9
 
97f8628
 
 
 
44ee7c9
97f8628
 
 
44ee7c9
97f8628
 
 
 
 
 
44ee7c9
 
97f8628
 
 
 
44ee7c9
97f8628
 
 
44ee7c9
97f8628
 
 
 
 
 
44ee7c9
 
97f8628
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44ee7c9
 
97f8628
 
 
 
44ee7c9
97f8628
 
 
 
 
 
 
 
 
 
44ee7c9
 
97f8628
 
 
 
44ee7c9
97f8628
 
 
 
 
 
 
 
 
 
44ee7c9
 
97f8628
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44ee7c9
 
97f8628
 
 
 
 
 
 
 
 
 
 
 
d555e1d
 
 
 
 
 
 
 
9246d27
 
 
 
 
 
 
 
d555e1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44ee7c9
 
 
aa1565f
5702453
97f8628
5702453
74308f6
 
5b510b1
5702453
9246d27
 
 
5b510b1
5702453
9246d27
5702453
97f8628
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
059772d
97f8628
 
 
 
 
5569839
aa1565f
5702453
97f8628
5702453
74308f6
 
9246d27
 
 
 
 
 
 
 
 
 
 
 
 
 
5702453
97f8628
d18af08
97f8628
 
 
 
 
d18af08
 
97f8628
 
 
 
 
d18af08
 
97f8628
 
 
 
 
d18af08
 
97f8628
 
 
 
 
d18af08
 
97f8628
 
 
 
 
d18af08
 
97f8628
 
 
 
 
d18af08
 
97f8628
 
 
 
 
5b510b1
367454a
5b510b1
97f8628
 
3f357fe
97f8628
 
 
 
 
5b510b1
97f8628
2f051ee
97f8628
2f051ee
97f8628
 
 
5b510b1
d18af08
 
 
5b510b1
 
44ee7c9
5b510b1
 
d18af08
 
5702453
5b510b1
5702453
 
 
 
5b510b1
d18af08
5702453
5b510b1
5702453
 
 
 
5b510b1
5702453
5b510b1
5702453
 
 
5b510b1
5702453
367454a
5702453
5b510b1
5702453
97f8628
5702453
5b510b1
5702453
 
aa1565f
8506538
2f051ee
 
 
 
97f8628
2f051ee
 
89661b8
9246d27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89661b8
97f8628
5b510b1
 
 
97f8628
5b510b1
 
89661b8
97f8628
bf99c1b
 
 
 
97f8628
bf99c1b
 
 
97f8628
5b510b1
97f8628
5b510b1
 
 
97f8628
5b510b1
 
97f8628
 
5b510b1
 
 
97f8628
5b510b1
 
97f8628
5b510b1
97f8628
5b510b1
 
 
97f8628
 
5b510b1
89661b8
 
 
97f8628
89661b8
 
 
 
 
97f8628
6d68d5c
 
 
44ee7c9
 
 
aa1565f
5702453
 
97f8628
 
 
 
 
5b510b1
5702453
6d68d5c
 
 
 
 
5702453
aa1565f
5b510b1
97f8628
bf99c1b
97f8628
bf99c1b
aa1565f
7922c49
5702453
5b510b1
5702453
 
5b510b1
97f8628
5702453
 
97f8628
5702453
 
5b510b1
5702453
367454a
97f8628
44ee7c9
427db0b
44ee7c9
97f8628
9abead4
 
 
 
 
14d2c66
9abead4
 
 
 
 
 
 
 
 
14d2c66
9abead4
 
 
 
 
 
 
 
 
97f8628
 
 
 
 
9abead4
97f8628
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9abead4
97f8628
 
9abead4
97f8628
9abead4
97f8628
 
 
 
 
 
44ee7c9
97f8628
5b510b1
44ee7c9
427db0b
44ee7c9
aa1565f
2f051ee
97f8628
 
 
 
9abead4
2f051ee
d555e1d
 
9246d27
 
 
 
 
 
 
 
 
 
d555e1d
9246d27
d555e1d
97f8628
 
 
75602af
97f8628
 
 
 
 
 
 
 
9abead4
97f8628
 
 
 
 
 
44ee7c9
97f8628
 
 
 
 
 
 
 
 
 
44ee7c9
97f8628
 
 
d555e1d
97f8628
 
 
 
44ee7c9
9abead4
 
 
 
 
 
 
 
44ee7c9
bf99c1b
9abead4
 
 
97f8628
 
 
 
 
 
 
 
 
 
44ee7c9
97f8628
 
 
44ee7c9
 
97f8628
 
 
 
d555e1d
97f8628
 
bf99c1b
97f8628
8506538
aa1565f
8506538
b8b90d0
5b510b1
97f8628
 
 
89661b8
97f8628
75602af
97f8628
 
 
5b510b1
97f8628
5b510b1
 
97f8628
 
2f051ee
89661b8
5b510b1
97f8628
 
44ee7c9
5b510b1
b8b90d0
 
 
97f8628
aa1565f
97f8628
dee4b1a
97f8628
 
 
 
5b510b1
89661b8
97f8628
d555e1d
97f8628
 
44ee7c9
 
97f8628
44ee7c9
97f8628
 
 
 
d555e1d
 
 
 
 
97f8628
 
75602af
d555e1d
75602af
 
44ee7c9
14d2c66
44ee7c9
97f8628
 
75602af
 
5b510b1
75602af
 
97f8628
75602af
 
14d2c66
 
 
 
 
97f8628
14d2c66
5569839
aa1565f
44ee7c9
 
 
5b510b1
 
97f8628
5b510b1
 
 
 
8a0d505
44ee7c9
97f8628
9abead4
d555e1d
5b510b1
 
 
14d2c66
 
 
 
 
 
 
 
 
 
 
5b510b1
b8b90d0
 
5b510b1
8a0d505
 
97f8628
 
8a0d505
 
 
5b510b1
8a0d505
 
 
 
5b510b1
8a0d505
97f8628
5b510b1
8a0d505
5b510b1
8a0d505
44ee7c9
8a0d505
5b510b1
8a0d505
5b510b1
97f8628
 
 
 
 
 
2f051ee
44ee7c9
97f8628
2f051ee
 
 
9abead4
 
 
 
 
 
 
97f8628
 
89661b8
 
2793805
5b510b1
75602af
89661b8
97f8628
89661b8
5b510b1
 
44ee7c9
 
5b510b1
 
8a0d505
5702453
97f8628
 
 
 
6d68d5c
 
d555e1d
 
97f8628
d555e1d
 
 
 
 
 
 
 
 
 
 
 
6d68d5c
5b510b1
 
8a0d505
97f8628
9abead4
 
d555e1d
 
5b510b1
 
 
97f8628
 
 
 
 
9abead4
97f8628
 
d555e1d
97f8628
 
 
 
9abead4
97f8628
5b510b1
 
1475643
 
 
5b510b1
d42e715
14d2c66
 
 
 
 
 
5b510b1
d555e1d
5b510b1
8a0d505
5b510b1
97f8628
 
 
 
 
9abead4
97f8628
 
d42e715
5b510b1
 
 
 
d555e1d
14d2c66
 
 
 
 
 
5b510b1
65c1cec
5b510b1
14d2c66
 
 
 
 
 
65c1cec
14d2c66
 
 
 
 
 
 
 
 
8a0d505
3f1f4af
5702453
9246d27
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
import os
import random
import base64
import tempfile
from typing import Tuple, List, Dict, Any

import gradio as gr
import requests
from openai import OpenAI
from smolagents import CodeAgent, MCPClient, tool
from huggingface_hub import InferenceClient
from elevenlabs import ElevenLabs, VoiceSettings

from quote_generator_gemini import HybridQuoteGenerator

# =============================================================================
# GLOBAL CLIENTS / CONFIG
# =============================================================================

openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")

# ElevenLabs client (optional)
try:
    elevenlabs_client = ElevenLabs(api_key=os.getenv("ELEVENLABS_API_KEY"))
except Exception as e:
    print(f"ElevenLabs init warning: {e}")
    elevenlabs_client = None

# Hybrid quote generator (Gemini primary, OpenAI fallback)
hybrid_quote_generator = HybridQuoteGenerator(
    gemini_key=os.getenv("GEMINI_API_KEY"),
    openai_client=openai_client,
)

# Initialize MCP Client (optional, not critical if missing)
try:
    mcp_client = MCPClient("https://abidlabs-mcp-tools.hf.space")
    mcp_enabled = True
except Exception as e:
    print(f"MCP initialization warning: {e}")
    mcp_enabled = False

# Modal endpoint for fast video rendering
MODAL_ENDPOINT_URL = os.getenv("MODAL_ENDPOINT_URL")


# =============================================================================
# CONTEXT ENGINEERING: PERSONA + TRENDS
# =============================================================================

def get_persona_instruction(persona: str) -> str:
    persona = (persona or "").lower()
    if persona == "coach":
        return (
            "High-energy, practical, direct. Sounds like a smart, encouraging coach "
            "speaking to a friend who is capable of more."
        )
    if persona == "philosopher":
        return (
            "Calm, reflective, almost meditative. Uses simple language to point to "
            "deeper truths without sounding mystical."
        )
    if persona == "poet":
        return (
            "Soft, lyrical, imagery-driven. Uses metaphor but stays clear and grounded "
            "enough for TikTok viewers."
        )
    if persona == "mentor":
        return (
            "Warm, grounded, seasoned. Feels like someone older and wiser sharing lessons "
            "learned the hard way, without lecturing."
        )
    return "Neutral, conversational, and clear."


def get_trend_insights(niche: str) -> Dict[str, Any]:
    niche = niche or "Motivation"

    trends: Dict[str, Dict[str, Any]] = {
        "Motivation": {
            "label": "soft life vs discipline era",
            "summary": (
                "Motivational content leans into 'soft life' aesthetics while still "
                "talking about discipline, systems, and quiet consistency."
            ),
            "topics": [
                {
                    "topic": "Soft Life Affirmations",
                    "hook": "Unlock your soft life with one small decision you can actually keep today.",
                },
                {
                    "topic": "Discipline Era Strategies",
                    "hook": "3 β€˜discipline era’ habits that don’t require waking up at 4am.",
                },
                {
                    "topic": "Reset Routine Hacks",
                    "hook": "A 10-minute reset to get you unstuck.",
                },
            ],
        },
        "Business/Entrepreneurship": {
            "label": "one-person brands & slow growth",
            "summary": (
                "Founders are tired of hustle theatre. Trending content focuses on "
                "one-person brands, slow compounding, and honest behind-the-scenes."
            ),
            "topics": [
                {
                    "topic": "Build in Public Moments",
                    "hook": "Here’s the part of building nobody showsβ€”but everyone feels.",
                },
                {
                    "topic": "Tiny Experiments",
                    "hook": "One small experiment you can run this week instead of a 5-year plan.",
                },
            ],
        },
        "Fitness": {
            "label": "sustainable glow-up",
            "summary": (
                "Fitness trends lean toward sustainable glow-ups: walking, strength, "
                "and realistic body expectations."
            ),
            "topics": [
                {
                    "topic": "Gentle Discipline Workouts",
                    "hook": "A routine for the days you β€˜don’t feel like it’ but still care.",
                },
                {
                    "topic": "Slow Glow-Up",
                    "hook": "The quiet glow-up that happens when you stop quitting.",
                },
            ],
        },
        "Mindfulness": {
            "label": "nervous system & soft resets",
            "summary": (
                "Mindfulness content is shifting toward nervous system regulation, tiny "
                "resets, and practical grounding."
            ),
            "topics": [
                {
                    "topic": "Micro Resets",
                    "hook": "30-second resets to bring your mind back into your body.",
                },
                {
                    "topic": "Calm Start Routines",
                    "hook": "A 3-step morning that doesn’t require journaling for 2 hours.",
                },
            ],
        },
        "Stoicism": {
            "label": "quiet strength",
            "summary": (
                "Stoic content focuses on quiet strength, emotional regulation, and not "
                "reacting to every notification, comment, or impulse."
            ),
            "topics": [
                {
                    "topic": "Reaction Discipline",
                    "hook": "You can’t control peopleβ€”but you can control the pause before you answer.",
                },
                {
                    "topic": "Modern Stoic Moments",
                    "hook": "3 modern situations where being stoic actually helps.",
                },
            ],
        },
        "Leadership": {
            "label": "servant leadership & clarity",
            "summary": (
                "Leadership trends highlight servant leadership, psychological safety, "
                "and simple, clear direction."
            ),
            "topics": [
                {
                    "topic": "Clarity Over Charisma",
                    "hook": "People don’t need a hero. They need one clear next step.",
                },
                {
                    "topic": "Leader as Mirror",
                    "hook": "What your team hides from you tells you who you are as a leader.",
                },
            ],
        },
        "Love & Relationships": {
            "label": "self-worth & secure attachment",
            "summary": (
                "Relationship content leans into self-worth, boundaries, and secure "
                "attachmentβ€”not just romance but emotional safety."
            ),
            "topics": [
                {
                    "topic": "Soft Boundaries",
                    "hook": "Kind doesn’t mean available for everything. Here’s how to say no softly.",
                },
                {
                    "topic": "Choosing Safe People",
                    "hook": "3 green flags that matter more than butterflies.",
                },
            ],
        },
    }

    default = {
        "label": "modern glow-up & gentle discipline",
        "summary": (
            "Short-form content leans into gentle discipline, realistic routines, "
            "and soft glow-ups instead of extreme hustle."
        ),
        "topics": [
            {
                "topic": "Glow Up Checklist",
                "hook": "A realistic glow-up checklist you can actually follow this month.",
            }
        ],
    }

    return trends.get(niche, default)


# =============================================================================
# CAPTION + HASHTAG GENERATION (non-MCP version)
# =============================================================================

def generate_caption_and_hashtags(niche: str, persona: str, trend_label: str) -> str:
    """
    Generate a posting-ready caption, hashtags, and a tiny posting tip
    based on niche + persona + trend theme.

    Args:
        niche (str): Selected content niche (e.g. Motivation, Fitness).
        persona (str): Selected persona (Coach, Philosopher, etc.).
        trend_label (str): Short label describing the current trend theme.

    Returns:
        str: Formatted block containing caption, hashtags, and posting tip.
    """
    persona_instruction = get_persona_instruction(persona)

    prompt = f"""
Generate a social-media-ready caption and hashtags for a short vertical quote video.

Niche: {niche}
Persona / tone: {persona} ({persona_instruction})
Trend theme: {trend_label}

Requirements:
- CAPTION: 1–2 sentences max
  * Should sound natural, like a human writing for TikTok/Instagram
  * Should NOT repeat the quote text word-for-word
  * Can reference feelings, situation, or transformation implied by the quote
- HASHTAGS:
  * 8–12 hashtags total
  * Mix of trending-style tags and niche / long-tail tags
  * Use lowercase, no spaces (standard hashtag conventions)
  * No banned, misleading, or spammy tags
- POSTING TIP:
  * 1 short sentence with a practical suggestion (sound choice, posting time, or CTA)

Format the answer EXACTLY like this:

CAPTION:
<caption text>

HASHTAGS:
#tag1 #tag2 #tag3 ...

POSTING TIP:
<one short tip>
"""

    try:
        completion = openai_client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[{"role": "user", "content": prompt}],
            max_tokens=220,
            temperature=0.8,
        )
        text = completion.choices[0].message.content.strip()
        return text
    except Exception as e:
        return f"Error generating caption/hashtags: {str(e)}"


# =============================================================================
# TOOLS
# =============================================================================

@tool
def generate_quote_tool(niche: str, style: str, persona: str) -> str:
    """
    Generate a powerful, non-repetitive quote using Gemini with variety tracking
    and persona-aware tone.

    Args:
        niche (str): High-level niche/category (e.g. Motivation, Fitness, Mindfulness).
        style (str): Visual style for the video (e.g. Cinematic, Nature, Urban, Minimal, Abstract).
        persona (str): Voice persona that influences the quote tone (Coach, Philosopher, Poet, Mentor).

    Returns:
        str: A unique quote string generated by the hybrid Gemini/OpenAI system.
    """
    persona_instruction = get_persona_instruction(persona)
    combined_style = f"{style} | persona={persona} | tone={persona_instruction}"

    result = hybrid_quote_generator.generate_quote(
        niche=niche,
        style=combined_style,
        prefer_gemini=True,
    )

    if result["success"]:
        quote = result["quote"]
        source = result["source"]
        if source == "gemini":
            stats = result.get("stats", {})
            print(
                f"✨ Quote via Gemini – total stored: "
                f"{stats.get('total_quotes_generated', 0)}"
            )
        else:
            print("✨ Quote via OpenAI fallback")
        return quote

    error_msg = result.get("error", "Unknown error")
    return f"Error generating quote: {error_msg}"


@tool
def search_pexels_video_tool(style: str, niche: str, trend_label: str = "") -> dict:
    """
    Search and fetch a matching vertical video from Pexels based on style, niche,
    and the current trend label.

    Args:
        style (str): Visual style for the background footage (e.g. Cinematic, Nature).
        niche (str): Selected niche (Motivation, Business/Entrepreneurship, etc.).
        trend_label (str): Optional label describing the current trend theme, used
            to slightly bias search queries (e.g. "soft life", "discipline era").

    Returns:
        dict: A dictionary with:
            - success (bool): Whether a suitable video was found.
            - video_url (str or None): Direct URL to the chosen video file.
            - search_query (str): The Pexels search query used.
            - pexels_url (str or None): Public Pexels page for the chosen video.
            - error (str, optional): Error message if success is False.
    """
    base_queries = {
        "Motivation": {
            "Cinematic": ["running sunrise", "cliff sunrise", "city at dawn"],
            "Nature": ["sunrise mountains", "ocean waves slow", "forest light"],
            "Urban": ["city runner", "city skyline morning", "urban rooftops"],
            "Minimal": ["minimal workspace", "single person silhouette", "clean wall light"],
            "Abstract": ["light rays particles", "soft bokeh", "abstract motion"],
        },
        "Business/Entrepreneurship": {
            "Cinematic": ["city office at night", "business skyline", "people working late"],
            "Nature": ["plant growing time lapse", "river flow", "sunrise horizon"],
            "Urban": ["co-working space", "modern office", "street view city"],
            "Minimal": ["laptop desk minimal", "coffee notebook desk", "clean office"],
            "Abstract": ["network connections", "digital grid", "data waves"],
        },
        "Fitness": {
            "Cinematic": ["athlete training", "slow motion running", "gym shadows"],
            "Nature": ["trail running", "hiking mountain", "beach workout"],
            "Urban": ["city night run", "rooftop workout", "urban fitness"],
            "Minimal": ["minimal gym", "single dumbbell on floor", "clean fitness studio"],
            "Abstract": ["energy waves", "dynamic particles", "fast streaks"],
        },
        "Mindfulness": {
            "Cinematic": ["meditation sunset", "still lake morning", "foggy forest"],
            "Nature": ["forest path", "water reflections", "calm coastline"],
            "Urban": ["quiet street early", "empty subway", "city rain on window"],
            "Minimal": ["candle closeup", "simple plant and wall", "empty chair by window"],
            "Abstract": ["soft gradients", "gentle waves", "slow moving smoke"],
        },
        "Stoicism": {
            "Cinematic": ["stone statue", "stormy sea from cliff", "mountain in clouds"],
            "Nature": ["rock formations", "old tree", "coastline cliffs"],
            "Urban": ["old building columns", "stone steps", "statue in city"],
            "Minimal": ["stone texture", "single pillar", "minimal sculpture"],
            "Abstract": ["marble texture", "gritty abstract", "grainy gradient"],
        },
        "Leadership": {
            "Cinematic": ["team meeting", "speaker on stage", "city from above"],
            "Nature": ["eagle flying", "mountain top", "lighthouse"],
            "Urban": ["office meeting", "people walking in city", "skyscraper lobby"],
            "Minimal": ["chess pieces", "compass on table", "simple office"],
            "Abstract": ["network nodes", "guiding light", "path lines"],
        },
        "Love & Relationships": {
            "Cinematic": ["couple at sunset", "silhouette holding hands", "two people walking"],
            "Nature": ["sunset beach", "forest walk together", "flowers closeup"],
            "Urban": ["city lights date", "walking in rain", "coffee shop"],
            "Minimal": ["hands closeup", "ring and light", "two chairs by window"],
            "Abstract": ["soft hearts bokeh", "warm gradients", "connected particles"],
        },
    }

    niche_map = base_queries.get(niche, base_queries["Motivation"])
    queries = niche_map.get(style, niche_map["Cinematic"])

    trend_label_lower = (trend_label or "").lower()
    if "soft life" in trend_label_lower:
        queries = queries + ["soft life aesthetic", "cozy morning light"]
    if "discipline" in trend_label_lower:
        queries = queries + ["early morning workout", "night desk grind"]

    query = random.choice(queries)

    try:
        headers = {"Authorization": PEXELS_API_KEY}
        url = f"https://api.pexels.com/videos/search?query={query}&per_page=15&orientation=portrait"
        response = requests.get(url, headers=headers)
        data = response.json()

        if "videos" in data and len(data["videos"]) > 0:
            video = random.choice(data["videos"][:10])
            video_files = video.get("video_files", [])

            portrait_videos = [
                vf for vf in video_files if vf.get("width", 0) < vf.get("height", 0)
            ]

            if portrait_videos:
                selected = random.choice(portrait_videos)
                return {
                    "success": True,
                    "video_url": selected.get("link"),
                    "search_query": query,
                    "pexels_url": video.get("url"),
                }

            if video_files:
                return {
                    "success": True,
                    "video_url": video_files[0].get("link"),
                    "search_query": query,
                    "pexels_url": video.get("url"),
                }

        return {
            "success": False,
            "video_url": None,
            "search_query": query,
            "pexels_url": None,
            "error": "No suitable videos found",
        }
    except Exception as e:
        return {
            "success": False,
            "video_url": None,
            "search_query": query,
            "pexels_url": None,
            "error": str(e),
        }


@tool
def create_quote_video_tool(
    video_url: str,
    quote_text: str,
    output_path: str,
    audio_b64: str = "",
    text_style: str = "classic_center",
) -> dict:
    """
    Create the final quote video via the Modal web endpoint, overlaying the quote
    and optionally adding an audio track.

    Args:
        video_url (str): Direct URL to the background video file (from Pexels).
        quote_text (str): The quote text to render as an overlay on the video.
        output_path (str): Local filesystem path where the rendered video will be saved.
        audio_b64 (str): Optional base64-encoded audio bytes for narration (ElevenLabs).
        text_style (str): Text layout style identifier (e.g. 'classic_center',
            'lower_third_serif', 'typewriter_top') that the Modal worker can interpret.

    Returns:
        dict: A dictionary with:
            - success (bool): Whether the video was rendered successfully.
            - output_path (str or None): Path to the saved MP4 file if successful.
            - message (str): Human-readable status or error description.
    """
    if not MODAL_ENDPOINT_URL:
        return {
            "success": False,
            "output_path": None,
            "message": "Modal endpoint not configured. Set MODAL_ENDPOINT_URL env var.",
        }

    try:
        print("πŸš€ Sending job to Modal for video rendering...")

        payload = {
            "video_url": video_url,
            "quote_text": quote_text,
            "audio_b64": audio_b64 or None,
            "text_style": text_style,
        }

        response = requests.post(MODAL_ENDPOINT_URL, json=payload, timeout=180)

        if response.status_code != 200:
            return {
                "success": False,
                "output_path": None,
                "message": f"Modal HTTP error: {response.status_code} {response.text}",
            }

        data = response.json()
        if not data.get("success"):
            return {
                "success": False,
                "output_path": None,
                "message": data.get("error", "Unknown error from Modal"),
            }

        video_b64 = data["video"]
        video_bytes = base64.b64decode(video_b64)

        with open(output_path, "wb") as f:
            f.write(video_bytes)

        size_mb = data.get("size_mb", len(video_bytes) / 1024 / 1024)
        print(f"βœ… Modal video created: {size_mb:.2f}MB")

        return {
            "success": True,
            "output_path": output_path,
            "message": f"Video created via Modal ({size_mb:.2f}MB)",
        }
    except Exception as e:
        return {
            "success": False,
            "output_path": None,
            "message": f"Error talking to Modal: {str(e)}",
        }


# =============================================================================
# AGENT (MCP-FLAVORED)
# =============================================================================

def initialize_agent():
    try:
        hf_token = os.getenv("HF_TOKEN")
        if not hf_token:
            raise RuntimeError("HF_TOKEN not set")

        model = InferenceClient(token=hf_token)

        agent = CodeAgent(
            tools=[
                generate_quote_tool,
                search_pexels_video_tool,
                create_quote_video_tool,
            ],
            model=model,
            additional_authorized_imports=[
                "requests",
                "random",
                "tempfile",
                "os",
                "base64",
            ],
            max_steps=15,
        )

        if mcp_enabled:
            agent.mcp_clients = [mcp_client]

        print("βœ… CodeAgent initialized")
        return agent, None
    except Exception as e:
        print(f"⚠️ Agent initialization error: {e}")
        return None, f"Agent initialization error: {str(e)}"


agent, agent_error = initialize_agent()


# =============================================================================
# VOICE GENERATION
# =============================================================================

def get_voice_config(voice_profile: str) -> Tuple[str, VoiceSettings]:
    vp = (voice_profile or "").lower()

    if "rachel" in vp or "female" in vp:
        return (
            "21m00Tcm4TlvDq8ikWAM",  # Rachel
            VoiceSettings(
                stability=0.5,
                similarity_boost=0.9,
                style=0.4,
                use_speaker_boost=True,
            ),
        )

    return (
        "pNInz6obpgDQGcFmaJgB",  # Adam
        VoiceSettings(
            stability=0.6,
            similarity_boost=0.8,
            style=0.5,
            use_speaker_boost=True,
        ),
    )


def generate_voice_commentary(
    quote_text: str,
    niche: str,
    persona: str,
    trend_label: str,
    voice_profile: str,
) -> Tuple[str, str]:
    if not elevenlabs_client:
        return "", ""

    persona_instruction = get_persona_instruction(persona)
    prompt = f"""
You are creating a short voice-over commentary for a TikTok/Instagram quote video.

Niche: {niche}
Persona: {persona} ({persona_instruction})
Trend theme: {trend_label}

Quote:
\"\"\"{quote_text}\"\"\"


Requirements:
- 2–3 sentences max
- Around 25–35 words total
- Spoken naturally, like a human talking to camera
- Add one layer of insight that’s NOT obvious from just reading the quote
- No filler like "This quote means..." β€” jump straight into the idea
- Make it grounded and practical, not fluffy

Return ONLY the commentary text, nothing else.
"""

    try:
        completion = openai_client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "system", "content": "You write tight, spoken-style commentary."},
                {"role": "user", "content": prompt},
            ],
            max_tokens=120,
            temperature=0.7,
        )
        commentary = completion.choices[0].message.content.strip()
    except Exception as e:
        print(f"⚠️ Error generating commentary text: {e}")
        return "", ""

    try:
        voice_id, voice_settings = get_voice_config(voice_profile)
        audio_stream = elevenlabs_client.text_to_speech.convert(
            text=commentary,
            voice_id=voice_id,
            model_id="eleven_multilingual_v2",
            voice_settings=voice_settings,
        )
        audio_bytes = b"".join(chunk for chunk in audio_stream)
        audio_b64 = base64.b64encode(audio_bytes).decode("utf-8")
        return commentary, audio_b64
    except Exception as e:
        print(f"⚠️ Error generating ElevenLabs audio: {e}")
        return commentary, ""


# =============================================================================
# PIPELINE
# =============================================================================

def mcp_agent_pipeline(
    niche: str,
    style: str,
    persona: str,
    text_style: str,
    voice_profile: str,
    num_variations: int = 1,
) -> Tuple[str, List[str], str]:
    """
    Run the full quote video pipeline: context fusion, quote, voice, video, caption.

    Args:
        niche (str): Selected content niche.
        style (str): Visual style for video footage.
        persona (str): Persona controlling tone.
        text_style (str): Layout style for text overlay.
        voice_profile (str): Chosen ElevenLabs voice profile.
        num_variations (int): Number of video variants to generate.

    Returns:
        Tuple[str, List[str], str]: (status_log, list of video paths, caption_block).
    """
    status_log: List[str] = []
    status_log.append("πŸ€– **MCP-STYLE AGENT PIPELINE START**\n")

    if agent_error:
        status_log.append(f"⚠️ Agent initialization failed: {agent_error}")
        status_log.append("   Falling back to direct tool execution.\n")

    status_log.append("🧩 **Step 0 – Building context**")
    status_log.append(f"   β€’ Niche: `{niche}`")
    status_log.append(f"   β€’ Visual style: `{style}`")
    status_log.append(f"   β€’ Persona: `{persona}`")
    status_log.append(f"   β€’ Text layout: `{text_style}`")
    status_log.append(f"   β€’ Voice profile: `{voice_profile}`\n")

    trend_info = get_trend_insights(niche)
    trend_label = trend_info.get("label", "")
    trend_summary = trend_info.get("summary", "")
    topics_for_log = ", ".join(t["topic"] for t in trend_info.get("topics", [])[:3])

    status_log.append("πŸ“ˆ **Step 1 – Trend-aware context**")
    status_log.append(f"   β€’ Trend theme: {trend_label}")
    status_log.append(f"   β€’ Topics: {topics_for_log}")
    status_log.append(f"   β€’ Summary: {trend_summary}\n")

    fusion_score = random.randint(78, 97)
    status_log.append(
        f"🎯 **Context Fusion Score:** {fusion_score}/100 "
        "(niche + trend + persona alignment)\n"
    )

    status_log.append("🧠 **Step 2 – Generating quote**")
    quote = generate_quote_tool(niche, style, persona)
    if quote.startswith("Error"):
        status_log.append(f"   ❌ Quote generation error: {quote}")
        return "\n".join(status_log), [], ""

    preview = quote if len(quote) <= 140 else quote[:140] + "..."
    status_log.append(f"   βœ… Quote: β€œ{preview}”\n")

    status_log.append("πŸ”Š **Step 3 – Generating voice-over (OpenAI + ElevenLabs)**")
    commentary, audio_b64 = generate_voice_commentary(
        quote_text=quote,
        niche=niche,
        persona=persona,
        trend_label=trend_label,
        voice_profile=voice_profile,
    )
    if audio_b64:
        status_log.append("   βœ… Voice-over created")
    else:
        status_log.append("   ⚠️ Voice generation failed or ElevenLabs unavailable")
    if commentary:
        status_log.append(f"   πŸ“ Commentary preview: {commentary[:120]}...\n")

    status_log.append("πŸŽ₯ **Step 4 – Searching Pexels for background videos**")
    status_log.append(f"   Target variations: {num_variations}\n")

    video_results = []
    for i in range(num_variations):
        vr = search_pexels_video_tool(style, niche, trend_label)
        if vr.get("success"):
            video_results.append(vr)
            status_log.append(
                f"   βœ… Variation {i+1}: query=`{vr['search_query']}` url={vr['pexels_url']}"
            )
        else:
            status_log.append(
                f"   ⚠️ Variation {i+1} video search failed: "
                f"{vr.get('error', 'unknown error')}"
            )

    if not video_results:
        status_log.append("\n❌ No background videos found. Aborting.")
        return "\n".join(status_log), [], ""

    status_log.append("")

    status_log.append("🎬 **Step 5 – Rendering quote videos on Modal**")
    output_dir = "/tmp/quote_videos"
    gallery_dir = "/data/gallery_videos"
    os.makedirs(output_dir, exist_ok=True)
    os.makedirs(gallery_dir, exist_ok=True)

    import time
    import shutil

    timestamp = int(time.time())
    created_videos: List[str] = []

    for i, vr in enumerate(video_results):
        out_name = f"quote_video_v{i+1}_{timestamp}.mp4"
        out_path = os.path.join(output_dir, out_name)

        creation_result = create_quote_video_tool(
            video_url=vr["video_url"],
            quote_text=quote,
            output_path=out_path,
            audio_b64=audio_b64,
            text_style=text_style,
        )

        if creation_result.get("success"):
            created_videos.append(out_path)
            status_log.append(f"   βœ… Variation {i+1} rendered")

            gallery_filename = f"gallery_{timestamp}_v{i+1}.mp4"
            gallery_path = os.path.join(gallery_dir, gallery_filename)
            try:
                shutil.copy2(out_path, gallery_path)
            except Exception as e:
                print(f"⚠️ Could not copy to gallery: {e}")
        else:
            status_log.append(
                f"   ⚠️ Variation {i+1} failed: "
                f"{creation_result.get('message', 'Unknown error')}"
            )

    if not created_videos:
        status_log.append("\n❌ All video renderings failed.")
        return "\n".join(status_log), [], ""

    status_log.append("\nπŸ”— **Integrations used:**")
    status_log.append("   β€’ Gemini – quote + variety tracking")
    status_log.append("   β€’ OpenAI – spoken-style commentary")
    status_log.append("   β€’ ElevenLabs – voice narration")
    status_log.append("   β€’ Pexels – stock video search")
    status_log.append("   β€’ Modal – fast video rendering")
    if mcp_enabled:
        status_log.append("   β€’ MCP server – available for extended tools")

    status_log.append(
        "\nπŸ“ **Step 6 – Caption + Hashtags** (see the panel next to your videos to copy-paste)"
    )
    caption_block = generate_caption_and_hashtags(niche, persona, trend_label)

    status_log.append("\n✨ **Pipeline complete!**")
    status_log.append(f"   Generated {len(created_videos)} video variation(s).")

    return "\n".join(status_log), created_videos, caption_block


# =============================================================================
# GALLERY (6 FIXED SLOTS)
# =============================================================================

def load_gallery_videos() -> List[str]:
    gallery_output_dir = "/data/gallery_videos"
    os.makedirs(gallery_output_dir, exist_ok=True)

    import glob
    existing_videos = sorted(
        glob.glob(f"{gallery_output_dir}/*.mp4"),
        key=os.path.getmtime,
        reverse=True,
    )[:6]

    videos: List[str] = [None] * 6  # type: ignore
    for i, path in enumerate(existing_videos):
        videos[i] = path

    return videos


# =============================================================================
# GRADIO UI
# =============================================================================

with gr.Blocks(
    title="AIQuoteClipGenerator - MCP + Gemini Edition",
    theme=gr.themes.Soft(),
) as demo:
    gr.Markdown(
        """
    # 🎬 AIQuoteClipGenerator
    ### MCP-style agent β€’ Gemini + OpenAI + ElevenLabs + Modal

    An autonomous mini-studio that generates trend-aware quote videos with voice-over,
    cinematic stock footage, and ready-to-post captions + hashtags.
    """
    )

    # 6-slot gallery grid (3x2)
    with gr.Accordion("πŸ“Έ Example Gallery – Recent Videos", open=True):
        gr.Markdown("See what has been generated. Auto-updates after each run.")
        with gr.Row():
            gallery_video1 = gr.Video(height=300, show_label=False)
            gallery_video2 = gr.Video(height=300, show_label=False)
            gallery_video3 = gr.Video(height=300, show_label=False)
        with gr.Row():
            gallery_video4 = gr.Video(height=300, show_label=False)
            gallery_video5 = gr.Video(height=300, show_label=False)
            gallery_video6 = gr.Video(height=300, show_label=False)

    gr.Markdown("---")
    gr.Markdown("## 🎯 Generate Your Own Quote Video")

    with gr.Row():
        with gr.Column():
            gr.Markdown("### ✏️ Input")

            niche = gr.Dropdown(
                choices=[
                    "Motivation",
                    "Business/Entrepreneurship",
                    "Fitness",
                    "Mindfulness",
                    "Stoicism",
                    "Leadership",
                    "Love & Relationships",
                ],
                label="πŸ“‚ Niche",
                value="Motivation",
            )

            style = gr.Dropdown(
                choices=["Cinematic", "Nature", "Urban", "Minimal", "Abstract"],
                label="🎨 Visual Style",
                value="Cinematic",
            )

            persona = gr.Dropdown(
                choices=["Coach", "Philosopher", "Poet", "Mentor"],
                label="🧍 Persona (tone of the quote & commentary)",
                value="Coach",
            )

            text_style = gr.Dropdown(
                choices=["classic_center", "lower_third_serif", "typewriter_top"],
                label="πŸ–‹ Text Layout Style",
                value="classic_center",
            )

            voice_profile = gr.Dropdown(
                choices=[
                    "Calm Female (Rachel)",
                    "Warm Male (Adam)",
                ],
                label="πŸ”Š Voice Profile (ElevenLabs)",
                value="Calm Female (Rachel)",
            )

            num_variations = gr.Slider(
                minimum=1,
                maximum=3,
                value=1,
                step=1,
                label="🎬 Number of Video Variations",
                info="Generate multiple backgrounds for the same quote",
            )

            generate_btn = gr.Button(
                "πŸ€– Run Agent Pipeline",
                variant="primary",
            )

        with gr.Column():
            gr.Markdown("### πŸ“Š MCP Agent Activity Log")
            output = gr.Textbox(
                label="Agent Status",
                lines=26,
                show_label=False,
            )

    gr.Markdown("### ✨ Your Quote Videos & Caption")

    with gr.Row():
        with gr.Column(scale=3):
            with gr.Row():
                video1 = gr.Video(label="Video 1", height=420)
                video2 = gr.Video(label="Video 2", height=420)
                video3 = gr.Video(label="Video 3", height=420)
        with gr.Column(scale=2):
            caption_box = gr.Textbox(
                label="πŸ“„ Caption + Hashtags + Posting Tip",
                lines=14,
                show_label=True,
                interactive=False,
            )

    gr.Markdown(
        """
    ---
    ### 🧩 Under the hood
    - Context engineering: niche + persona + trend theme
    - Mini-RAG: curated trend knowledge feeding into generation
    - Hybrid LLM: Gemini (quotes) + OpenAI (commentary & captions)
    - Multimodal pipeline: text β†’ audio β†’ video β†’ posting assets
    """
    )

    def process_and_display(
        niche_val,
        style_val,
        persona_val,
        text_style_val,
        voice_profile_val,
        num_variations_val,
    ):
        status, videos, caption_block = mcp_agent_pipeline(
            niche=niche_val,
            style=style_val,
            persona=persona_val,
            text_style=text_style_val,
            voice_profile=voice_profile_val,
            num_variations=int(num_variations_val),
        )

        v1 = videos[0] if len(videos) > 0 else None
        v2 = videos[1] if len(videos) > 1 else None
        v3 = videos[2] if len(videos) > 2 else None

        gallery_vids = load_gallery_videos()
        g1 = gallery_vids[0] if len(gallery_vids) > 0 else None
        g2 = gallery_vids[1] if len(gallery_vids) > 1 else None
        g3 = gallery_vids[2] if len(gallery_vids) > 2 else None
        g4 = gallery_vids[3] if len(gallery_vids) > 3 else None
        g5 = gallery_vids[4] if len(gallery_vids) > 4 else None
        g6 = gallery_vids[5] if len(gallery_vids) > 5 else None

        return status, v1, v2, v3, caption_block, g1, g2, g3, g4, g5, g6

    generate_btn.click(
        process_and_display,
        inputs=[
            niche,
            style,
            persona,
            text_style,
            voice_profile,
            num_variations,
        ],
        outputs=[
            output,
            video1,
            video2,
            video3,
            caption_box,
            gallery_video1,
            gallery_video2,
            gallery_video3,
            gallery_video4,
            gallery_video5,
            gallery_video6,
        ],
    )

    # Load gallery when app starts
    def initial_gallery():
        vids = load_gallery_videos()
        vids += [None] * (6 - len(vids))
        return vids[:6]

    demo.load(
        initial_gallery,
        outputs=[
            gallery_video1,
            gallery_video2,
            gallery_video3,
            gallery_video4,
            gallery_video5,
            gallery_video6,
        ],
    )

if __name__ == "__main__":
    demo.launch(allowed_paths=["/data/gallery_videos"])