File size: 20,739 Bytes
1ccab01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# NCAKit Complete API Documentation

> **Base URL:** `https://YOUR_SPACE.hf.space` or `http://localhost:7860`

---

## πŸ“š Table of Contents

1. [Video Creator (Short Videos)](#1-video-creator-short-videos)
2. [Story Reels (AI Image Videos)](#2-story-reels-ai-image-videos)
3. [Fact Image (Quote Videos)](#3-fact-image-quote-videos)
4. [Quiz Reel (Interactive Quizzes)](#4-quiz-reel-interactive-quizzes)
5. [Text Story (Chat Story Videos)](#5-text-story-chat-story-videos)
6. [Trends (Google Trends)](#6-trends-google-trends)
7. [Common Patterns](#7-common-patterns)
8. [HF Cloud Storage & Download](#8-hf-cloud-storage--download)
9. [Environment Variables](#9-environment-variables)

---

## 1. Video Creator (Short Videos)

Create short-form videos with multiple scenes, background videos/images, TTS narration, and background music.

### Base Path: `/api`

---

### ▢️ POST `/api/short-video` - Create Video

Create a new short video with multiple scenes.

**Request Body:**
```json
{
  "scenes": [
    {
      "text": "Scene 1 narration text",
      "searchTerms": ["nature", "forest", "peaceful"]
    },
    {
      "text": "Scene 2 narration text",
      "searchTerms": ["city", "night", "lights"]
    }
  ],
  "config": {
    "voice": "af_heart",
    "music": "chill",
    "musicVolume": "medium",
    "captionPosition": "bottom",
    "captionBackgroundColor": "blue",
    "orientation": "portrait",
    "paddingBack": 2000
  }
}
```

**Scene Parameters:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `text` | string | βœ… | Narration text (will be converted to TTS) |
| `searchTerms` | string[] | βœ… | Keywords for finding background video from Pexels/Pixabay |

**Config Parameters:**
| Field | Type | Default | Options |
|-------|------|---------|---------|
| `voice` | string | `af_heart` | See [Voice Options](#voice-options) |
| `music` | string | `null` | `sad`, `happy`, `chill`, `dark`, `hopeful`, etc. |
| `musicVolume` | string | `high` | `low`, `medium`, `high`, `muted` |
| `captionPosition` | string | `bottom` | `top`, `center`, `bottom` |
| `captionBackgroundColor` | string | `blue` | Any CSS color name |
| `orientation` | string | `portrait` | `portrait`, `landscape` |
| `paddingBack` | int | `0` | End screen duration in milliseconds |

**Response (201):**
```json
{
  "videoId": "abc123def456..."
}
```

---

### πŸ“Š GET `/api/short-video/{video_id}/status` - Check Status

**Response:**
```json
{
  "status": "processing"
}
```

**Status Values:**
| Status | Description |
|--------|-------------|
| `processing` | Video is being generated |
| `ready` | Video is ready to download |
| `failed` | Generation failed |

---

### ⬇️ GET `/api/short-video/{video_id}` - Download Video

Returns the MP4 video file directly for download.

**Headers:**
```
Content-Type: video/mp4
Content-Disposition: attachment; filename="{video_id}.mp4"
```

---

### πŸ“‹ GET `/api/short-videos` - List All Videos

**Response:**
```json
{
  "videos": [
    {"id": "abc123", "status": "ready"},
    {"id": "def456", "status": "processing"}
  ]
}
```

---

### πŸ—‘οΈ DELETE `/api/short-video/{video_id}` - Delete Video

**Response:**
```json
{"success": true}
```

---

### 🎀 GET `/api/voices` - List Available Voices

**Response:** Array of available Kokoro TTS voices.

### 🎡 GET `/api/music-tags` - List Music Moods

**Response:** Array of available background music moods.

---

## 2. Story Reels (AI Image Videos)

Create story videos with AI-generated images matching the script.

### Base Path: `/api`

---

### ▢️ POST `/api/story-reel` - Create Story Reel

**Request Body:**
```json
{
  "script": "Once upon a time, in a magical forest, a young boy discovered a hidden door...",
  "image_style": "semi-realistic",
  "voice": "af_heart"
}
```

**Parameters:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `script` | string | βœ… | Full story script text |
| `image_style` | string | ❌ | Image generation style |
| `voice` | string | ❌ | TTS voice |

**Image Styles:**
- `semi-realistic` (default)
- `anime`
- `cartoon`
- `realistic`
- `watercolor`
- `sticky animation`

**Response (201):**
```json
{
  "job_id": "abc123",
  "status": "queued",
  "message": "Video generation started"
}
```

---

### πŸ“Š GET `/api/story-reel/{video_id}/status` - Check Status

**Response:**
```json
{
  "job_id": "abc123",
  "status": "processing",
  "progress": 45,
  "video_url": null,
  "duration": null,
  "error": null
}
```

**Status Values:**
- `queued` - Waiting in queue
- `processing` - Being generated
- `generating_audio` - TTS in progress
- `generating_images` - AI images being created
- `composing_video` - Final video composition
- `ready` - Complete
- `failed` - Error occurred

---

### ⬇️ GET `/api/story-reel/{video_id}` - Download Video

Returns MP4 file or redirects to HF Hub cloud URL.

---

### πŸ“‹ GET `/api/story-reels` - List All Story Reels

### πŸ—‘οΈ DELETE `/api/story-reel/{video_id}` - Delete Story Reel

### 🎨 GET `/api/styles` - List Image Styles

### 🎀 GET `/api/voices` - List TTS Voices

---

## 3. Fact Image (Quote Videos)

Create short videos with AI-generated or stock background images and text overlays.

### Base Path: `/api/fact-image`

---

### ▢️ POST `/api/fact-image/` - Create Fact Video

**Request Body:**
```json
{
  "model": "nvidia",
  "image_prompt": "A serene mountain landscape at sunset with golden light",
  "fact_heading": "DID YOU KNOW?",
  "heading_background": {
    "enabled": true,
    "color": "rgba(255, 109, 128, 0.95)",
    "padding": 22,
    "corner_radius": 28
  },
  "fact_text": "The human brain can process images in as little as 13 milliseconds.",
  "duration": 5
}
```

**Parameters:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `model` | string | ❌ | `nvidia`, `cloudflare`, `pexels` |
| `image_prompt` | string | βœ… | Background image description (10-500 chars) |
| `fact_heading` | string | ❌ | Heading text (max 50 chars) |
| `heading_background` | object | ❌ | Heading background style |
| `fact_text` | string | βœ… | Main fact text (5-200 chars) |
| `duration` | int | ❌ | Video duration 4-7 seconds |

**Heading Background Options:**
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | bool | `true` | Show/hide background |
| `color` | string | `rgba(0,0,0,0.45)` | RGBA or hex color |
| `padding` | int | `22` | Padding around text (5-50) |
| `corner_radius` | int | `28` | Border radius (0-50) |

**Response:**
```json
{
  "job_id": "abc123",
  "status": "processing",
  "status_url": "/api/fact-image/abc123/status",
  "download_url": "/api/fact-image/abc123"
}
```

---

### πŸ“Š GET `/api/fact-image/{job_id}/status` - Check Status

**Response:**
```json
{
  "job_id": "abc123",
  "status": "generating_image",
  "progress": 30,
  "video_url": null,
  "error": null
}
```

**Status Values:**
- `queued`
- `generating_image`
- `adding_text`
- `creating_video`
- `ready`
- `failed`

---

### ⬇️ GET `/api/fact-image/{job_id}` - Download Video

### πŸ—‘οΈ DELETE `/api/fact-image/{job_id}` - Delete Video

---

## 4. Quiz Reel (Interactive Quizzes)

Create quiz videos with multiple questions, TTS, and animated answers.

### Base Path: `/api/quiz`

---

### ▢️ POST `/api/quiz/generate` - Create Quiz Video

**Request Body:**
```json
{
  "quizzes": [
    {
      "hook": "GEOGRAPHY QUIZ",
      "question": "What is the highest mountain in the world?",
      "options": {
        "A": "Mount Everest",
        "B": "K2",
        "C": "Kangchenjunga"
      },
      "correct": "A",
      "explain": "Mount Everest stands at 8,848 meters"
    },
    {
      "hook": "SCIENCE QUIZ",
      "question": "What is the chemical symbol for water?",
      "options": {
        "A": "O2",
        "B": "H2O",
        "C": "CO2"
      },
      "correct": "B",
      "explain": "Water is composed of 2 hydrogen and 1 oxygen atom"
    }
  ],
  "voice": "af_heart"
}
```

**Quiz Scene Parameters:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `hook` | string | ❌ | Category label (e.g., "IQ TEST") |
| `question` | string | βœ… | The quiz question |
| `options` | object | βœ… | Must have exactly A, B, C keys |
| `correct` | string | βœ… | Correct answer: "A", "B", or "C" |
| `explain` | string | ❌ | Explanation shown after reveal |

**Response:**
```json
{
  "job_id": "abc123",
  "status": "queued",
  "message": "Quiz video generation started with 2 quizzes"
}
```

---

### πŸ“Š GET `/api/quiz/{job_id}/status` - Check Status

**Response:**
```json
{
  "job_id": "abc123",
  "status": "processing",
  "progress": 60,
  "video_url": null,
  "error": null
}
```

---

### ⬇️ GET `/api/quiz/video/{job_id}` - Download Video

---

## 5. Text Story (Chat Story Videos)

Create fake iMessage/Messenger chat story videos with gameplay background.

### Base Path: `/api/text-story`

---

### ▢️ POST `/api/text-story/generate` - Create Text Story

**Request Body (Manual Mode):**
```json
{
  "person_a_name": "You",
  "person_b_name": "My Ex",
  "person_b_avatar": "M",
  "messages": [
    {"sender": "B", "text": "Hey... we need to talk"},
    {"sender": "A", "text": "What's up?"},
    {"sender": "B", "text": "I've been thinking about us"},
    {"sender": "B", "text": "A lot actually"},
    {"sender": "A", "text": "What do you mean?"},
    {"sender": "B", "text": "I miss you..."}
  ],
  "ending_text": "To be continued...",
  "voice_a": "af_heart",
  "voice_b": "am_fenrir"
}
```

**Parameters:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `person_a_name` | string | ❌ | Your name (right side, blue bubbles) |
| `person_b_name` | string | ❌ | Other person's name (shown in header) |
| `person_b_avatar` | string | ❌ | Avatar letter or emoji |
| `messages` | array | βœ… | Chat messages (2-50 messages) |
| `ending_text` | string | ❌ | Optional ending text overlay |
| `voice_a` | string | ❌ | Voice for Person A (default: af_heart) |
| `voice_b` | string | ❌ | Voice for Person B (default: am_fenrir) |

**Message Object:**
| Field | Type | Description |
|-------|------|-------------|
| `sender` | string | `"A"` = You (right, blue), `"B"` = Other (left, gray) |
| `text` | string | Message text (1-500 chars) |

> **Note:** The same sender CAN send multiple messages in a row for natural conversation flow!

**Response:**
```json
{
  "job_id": "abc123",
  "status": "processing",
  "message": "Started generating text story with 6 messages"
}
```

---

### πŸ€– POST `/api/text-story/ai-generate` - AI Generate Conversation

Use Groq AI to generate a conversation from a prompt.

**Request Body:**
```json
{
  "prompt": "A breakup conversation where she reveals she's getting married to someone else",
  "person_a_name": "You",
  "person_b_name": "My Ex",
  "message_count": 7,
  "tone": "emotional"
}
```

**Parameters:**
| Field | Type | Default | Options |
|-------|------|---------|---------|
| `prompt` | string | - | Conversation scenario |
| `person_a_name` | string | "You" | - |
| `person_b_name` | string | "My Ex" | - |
| `message_count` | int | 7 | Approximate message count |
| `tone` | string | "emotional" | `emotional`, `funny`, `shocking`, `romantic`, `angry` |

**Response:**
```json
{
  "messages": [
    {"sender": "B", "text": "Hey..."},
    {"sender": "A", "text": "What's up?"}
  ],
  "ending_text": "To be continued..."
}
```

> **Workflow:** Use `/ai-generate` first β†’ Get messages β†’ Send to `/generate`

---

### πŸ“Š GET `/api/text-story/{job_id}/status` - Check Status

**Response:**
```json
{
  "job_id": "abc123",
  "status": "processing",
  "progress": 45,
  "current_step": "Rendering chat UI...",
  "video_url": null,
  "error": null
}
```

---

### ⬇️ GET `/api/text-story/{job_id}/video` - Download Video

---

## 6. Trends (Google Trends)

Get trending topics and keyword research data.

### Base Path: `/api/trends`

---

### ▢️ POST `/api/trends/trending-now` - Get Trending Topics

**Request Body:**
```json
{
  "country": "bangladesh",
  "limit": 20
}
```

**Countries:** `united_states`, `united_kingdom`, `india`, `bangladesh`, `japan`, `germany`, `france`, `brazil`, `canada`, `australia`

**Response:**
```json
{
  "success": true,
  "count": 20,
  "trends": [
    {"rank": 1, "topic": "Cricket World Cup", "country": "bangladesh", "traffic": "100K+"},
    {"rank": 2, "topic": "BPL 2024", "country": "bangladesh", "traffic": "50K+"}
  ]
}
```

---

### πŸ” POST `/api/trends/keyword-research` - Keyword Research

**Request Body:**
```json
{
  "keyword": "weight loss",
  "region": "US",
  "timeframe": "today_12m",
  "category": "health",
  "search_type": "web"
}
```

**Parameters:**
| Field | Type | Options |
|-------|------|---------|
| `timeframe` | string | `now_1h`, `now_4h`, `now_1d`, `now_7d`, `today_1m`, `today_3m`, `today_12m`, `today_5y` |
| `category` | string | `all`, `arts_entertainment`, `health`, `sports`, etc. |
| `search_type` | string | `web`, `youtube`, `news`, `images`, `shopping` |

**Response:**
```json
{
  "success": true,
  "keyword": "weight loss",
  "region": "US",
  "timeframe": "today_12m",
  "category": "health",
  "search_type": "web",
  "related_topics": {
    "top": [{"topic": "Diet", "value": 100}],
    "rising": [{"topic": "Ozempic", "value": 5000}]
  },
  "related_queries": {
    "top": [{"query": "best diet for weight loss", "value": "100"}],
    "rising": [{"query": "semaglutide weight loss", "value": "2400%"}]
  }
}
```

---

### πŸ“Ί POST `/api/trends/youtube-trends` - YouTube Trends

**Request Body:**
```json
{
  "keyword": "coding tutorial",
  "region": "US",
  "timeframe": "today_12m"
}
```

---

### πŸ“‹ GET `/api/trends/categories` - List Categories

### 🌍 GET `/api/trends/countries` - List Countries

---

## 7. Common Patterns

### Status Polling Pattern

All video generation endpoints follow this pattern:

```
1. POST /create  β†’  Returns job_id
2. GET /status   β†’  Poll until status = "ready"
3. GET /download β†’  Get video file
```

**Python Example:**
```python
import requests
import time

# 1. Create video
response = requests.post(
    "https://your-space.hf.space/api/short-video",
    json={
        "scenes": [{"text": "Hello world", "searchTerms": ["nature"]}],
        "config": {"voice": "af_heart"}
    }
)
video_id = response.json()["videoId"]

# 2. Poll status
while True:
    status = requests.get(f"https://your-space.hf.space/api/short-video/{video_id}/status").json()
    if status["status"] == "ready":
        break
    elif status["status"] == "failed":
        raise Exception("Video generation failed")
    time.sleep(5)

# 3. Download video
video = requests.get(f"https://your-space.hf.space/api/short-video/{video_id}")
with open("output.mp4", "wb") as f:
    f.write(video.content)
```

---

## 8. HF Cloud Storage & Download

Videos are automatically uploaded to Hugging Face Dataset when `HF_REPO` and `HF_TOKEN` are configured. Here's how to get the download URL:

---

### πŸ“₯ Method 1: Get URL from Status Response

When video is ready, `video_url` field contains the direct cloud URL:

```python
import requests
import time

BASE_URL = "https://your-space.hf.space"
job_id = "abc123"

# Poll until ready
while True:
    response = requests.get(f"{BASE_URL}/api/story-reel/{job_id}/status")
    data = response.json()
    
    if data["status"] == "ready":
        # βœ… Cloud URL is in video_url field!
        cloud_url = data["video_url"]
        print(f"Download URL: {cloud_url}")
        # Output: https://huggingface.co/datasets/username/repo/resolve/main/story_reels/abc123.mp4?download=true
        break
    elif data["status"] == "failed":
        print(f"Error: {data.get('error')}")
        break
    
    time.sleep(3)
```

**Status Response with Cloud URL:**
```json
{
  "job_id": "abc123",
  "status": "ready",
  "progress": 100,
  "video_url": "https://huggingface.co/datasets/username/repo/resolve/main/story_reels/abc123.mp4?download=true",
  "error": null
}
```

---

### πŸ“₯ Method 2: Download Endpoint Auto-Redirect

The download endpoint automatically redirects to HF Hub URL:

```python
# Download endpoint auto-redirects to cloud
response = requests.get(
    f"{BASE_URL}/api/story-reel/{job_id}",
    allow_redirects=True  # Default
)

# Get the final URL after redirect
final_url = response.url
print(f"Final URL: {final_url}")
# Output: https://huggingface.co/datasets/...

# Or get redirect URL without following
response = requests.get(
    f"{BASE_URL}/api/story-reel/{job_id}",
    allow_redirects=False
)
if response.status_code == 302:
    cloud_url = response.headers["Location"]
```

---

### πŸ“‹ Module Support Matrix

| Module | Status Endpoint | `video_url` in Status | Auto-Redirect |
|--------|----------------|----------------------|---------------|
| Story Reels | `/api/story-reel/{id}/status` | βœ… Yes | βœ… Yes |
| Fact Image | `/api/fact-image/{id}/status` | βœ… Yes | βœ… Yes |
| Quiz Reel | `/api/quiz/{id}/status` | βœ… Yes | βœ… Yes |
| Text Story | `/api/text-story/{id}/status` | βœ… Yes | βœ… Yes |
| Video Creator | `/api/short-video/{id}/status` | ❌ No | βœ… Yes |

---

### πŸ”— Cloud URL Format

```
https://huggingface.co/datasets/{HF_REPO}/resolve/main/{folder}/{video_id}.mp4?download=true
```

**Folders by Module:**
| Module | Folder |
|--------|--------|
| Video Creator | `short_video` |
| Story Reels | `story_reels` |
| Fact Image | `fact_image` |
| Quiz Reel | `quiz_reel` |
| Text Story | `text_story` |

---

### ⚑ Complete Python Example

```python
import requests
import time

def create_and_download_video(base_url, script, voice="af_heart"):
    """
    Complete workflow: Create β†’ Poll β†’ Get Cloud URL
    """
    
    # 1. Create video
    response = requests.post(
        f"{base_url}/api/story-reel",
        json={
            "script": script,
            "voice": voice,
            "image_style": "semi-realistic"
        }
    )
    job_id = response.json()["job_id"]
    print(f"Job created: {job_id}")
    
    # 2. Poll status until ready
    while True:
        status_resp = requests.get(f"{base_url}/api/story-reel/{job_id}/status")
        status = status_resp.json()
        
        print(f"Status: {status['status']} | Progress: {status.get('progress', 0)}%")
        
        if status["status"] == "ready":
            # 3. Get cloud URL from status response
            cloud_url = status["video_url"]
            print(f"\nβœ… Video Ready!")
            print(f"Cloud URL: {cloud_url}")
            return cloud_url
            
        elif status["status"] == "failed":
            raise Exception(f"Failed: {status.get('error')}")
        
        time.sleep(5)


# Usage
cloud_url = create_and_download_video(
    base_url="https://your-space.hf.space",
    script="Once upon a time in a magical forest..."
)

# Download to file
video = requests.get(cloud_url)
with open("output.mp4", "wb") as f:
    f.write(video.content)
```

---

## 9. Environment Variables

Configure these in your HF Space secrets or `.env` file:

| Variable | Required | Description |
|----------|----------|-------------|
| `HF_TTS` | βœ… | Kokoro TTS API URL |
| `PEXELS_API` | ❌ | Pexels API key for stock videos |
| `PIXABAY_API` | ❌ | Pixabay API key for stock videos |
| `NVIDIA_API` | ❌ | NVIDIA Cosmos API key for AI images |
| `CLOUDFLARE_API` | ❌ | Cloudflare AI API key |
| `GROQ_API` | ❌ | Groq API key for AI text generation |
| `HF_REPO` | ❌ | HF Dataset repo for cloud storage |
| `HF_TOKEN` | ❌ | HF token with write access |

---

## Voice Options

### Female Voices (af_)
- `af_heart` ⭐ - Warm, engaging
- `af_bella` - Soft, natural
- `af_sarah` - Clear, professional
- `af_nova` - Energetic
- `af_sky` - Youthful

### Male Voices (am_)
- `am_adam` - Deep, authoritative
- `am_fenrir` ⭐ - Natural, conversational
- `am_michael` - Clear, professional
- `am_liam` - Friendly

### British Voices (bf_, bm_)
- `bf_emma` - British female
- `bm_george` - British male

---

## Error Handling

All endpoints return standard HTTP error codes:

| Code | Description |
|------|-------------|
| `400` | Bad request (validation error) |
| `404` | Resource not found |
| `500` | Internal server error |
| `503` | Service not initialized |

**Error Response Format:**
```json
{
  "detail": "Error message here"
}
```

---

## Interactive API Docs

FastAPI provides automatic interactive documentation:

- **Swagger UI:** `https://YOUR-SPACE.hf.space/docs`
- **ReDoc:** `https://YOUR-SPACE.hf.space/redoc`

---

*Last Updated: December 2024*