File size: 31,237 Bytes
3e8a1f9
6985bb5
3e8a1f9
0142009
e1ffe38
799b050
0142009
 
5816824
6985bb5
5816824
 
 
3e8a1f9
5816824
799b050
101908c
799b050
6985bb5
84b7c6c
0142009
799b050
101908c
0142009
101908c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0142009
 
 
6985bb5
0142009
101908c
5816824
6985bb5
b7ad107
 
 
6985bb5
0142009
 
 
 
5816824
6985bb5
0142009
 
 
 
 
 
 
e1ffe38
 
 
 
 
 
101908c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7ad107
 
 
 
 
 
 
 
 
 
 
 
 
 
84b7c6c
b7ad107
e1ffe38
b7ad107
 
 
e1ffe38
 
 
 
b7ad107
 
 
 
e1ffe38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7ad107
 
e1ffe38
 
 
 
 
b7ad107
 
e1ffe38
 
 
 
 
b7ad107
 
 
 
 
 
 
 
 
 
 
84b7c6c
 
 
 
e1ffe38
84b7c6c
 
 
 
b7ad107
 
 
84b7c6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7ad107
 
0142009
b7ad107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1ffe38
b7ad107
 
 
 
 
5816824
 
b7ad107
 
0142009
b7ad107
0142009
 
b7ad107
 
0142009
b7ad107
5816824
0142009
 
 
b7ad107
5816824
b7ad107
e1ffe38
0142009
3e8a1f9
 
0142009
e1ffe38
 
84b7c6c
 
 
 
 
 
e1ffe38
6985bb5
b7ad107
 
e1ffe38
b7ad107
e1ffe38
 
 
 
 
 
 
b7ad107
e1ffe38
3e8a1f9
 
0142009
 
e1ffe38
0142009
e1ffe38
 
84b7c6c
e1ffe38
b7ad107
3e8a1f9
 
 
6985bb5
0142009
 
3e8a1f9
6985bb5
 
b7ad107
e1ffe38
b7ad107
6985bb5
 
b7ad107
6985bb5
 
e1ffe38
6985bb5
 
 
 
 
 
 
 
b7ad107
6985bb5
 
 
 
 
 
 
 
b7ad107
 
6985bb5
 
84b7c6c
 
 
6985bb5
e1ffe38
6985bb5
 
84b7c6c
e1ffe38
b7ad107
3e8a1f9
e1ffe38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84b7c6c
e1ffe38
101908c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1ffe38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e8a1f9
 
101908c
0142009
799b050
 
3e8a1f9
0142009
 
b7ad107
6985bb5
 
b7ad107
6985bb5
 
 
 
 
84b7c6c
0142009
b7ad107
3e8a1f9
b7ad107
e1ffe38
6985bb5
 
 
 
 
 
 
 
 
 
b7ad107
 
6985bb5
b7ad107
6985bb5
 
e1ffe38
 
b7ad107
 
6985bb5
e1ffe38
101908c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py
from fastapi import FastAPI, Body, Query
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from typing import List, Optional, Tuple, Literal
from transformers import pipeline
from datetime import datetime, timedelta
import random, re, itertools

# --- pytrends optional ---
try:
    from pytrends.request import TrendReq
    HAS_PYTRENDS = True
except Exception:
    HAS_PYTRENDS = False

app = FastAPI(title="NocoAI Title & Prompt Forge (Shorts Optimized)")

# ===== ๋ชจ๋ธ =====
MODEL_ID = "google/mt5-small"
pipe = pipeline("text2text-generation", model=MODEL_ID)

# ===== ์ตœ์‹  ํŠธ๋ Œ๋“œํ˜• ์‹œ๋“œ (AI ์ˆํผ ์นœํ™” 80+๊ฐœ) =====
SEED_TOPICS = [
    # ==== ๋Œ„์Šค / ๋ฐˆ / ์ฒผ๋ฆฐ์ง€ ====
    "AI ๋ฏธ๋…€๊ฐ€ K-ํŒ ์•ˆ๋ฌด๋ฅผ ์™„๋ฒฝํ•˜๊ฒŒ ์†Œํ™”ํ•œ๋‹ค๋ฉด",
    "AI ๊ฑธ๊ทธ๋ฃน์ด ๋‰ด์ง„์Šค ๋Œ„์Šค๋ฅผ ์ปค๋ฒ„ํ•œ๋‹ค๋ฉด",
    "AI ๋ชจ๋ธ์ด ํ‹ฑํ†ก ๋ฐˆ ๋Œ„์Šค์— ๋„์ „ํ•œ๋‹ค",
    "AI ์บ๋ฆญํ„ฐ๊ฐ€ โ€˜ํ•˜์ž…๋ณด์ดโ€™์— ๋งž์ถฐ ์ถค์ถ˜๋‹ค๋ฉด",
    "AI๊ฐ€ ์•„์ด๋Œ ์˜ค๋””์…˜์— ์ฐธ๊ฐ€ํ–ˆ๋‹ค๋ฉด",
    "AI์™€ ์ธ๊ฐ„์ด ๋™์‹œ์— ์ถค์ถœ ๋•Œ ์ƒ๊ธฐ๋Š” ํ˜„์ƒ",
    "AI ์•„์ด๋Œ์˜ ๋ฌด๋Œ€ ๋ฐฑ์—…๋Œ„์„œ๊ฐ€ ์ธ๊ฐ„์ด๋ผ๋ฉด",
    "AI ์ธํ”Œ๋ฃจ์–ธ์„œ๊ฐ€ ๋ฆด์Šค ์ฒผ๋ฆฐ์ง€์— ์ฐธ์—ฌํ•œ๋‹ค๋ฉด",
    "AI๊ฐ€ ํ‘œ์ • ํ•˜๋‚˜๋กœ ๋ฐˆ์„ ๋งŒ๋“ ๋‹ค๋ฉด",
    "AI๊ฐ€ ๋žœ๋ค ๋…ธ๋ž˜ ์Šค์œ„์น˜ ๋Œ„์Šค์— ๋„์ „ํ•œ๋‹ค๋ฉด",
    "AI๊ฐ€ ์œ ๋ช… ๋Œ„์Šค ์•ˆ๋ฌด๋ฅผ ์ดˆ์Šฌ๋กœ๋กœ ๋ณด์—ฌ์ค€๋‹ค๋ฉด",
    "AI ์บ๋ฆญํ„ฐ๊ฐ€ ๊ตญ๊ฐ€๋ณ„ ์ „ํ†ต์ถค์„ ์ปค๋ฒ„ํ•œ๋‹ค๋ฉด",

    # ==== ํŒจ์…˜ / ๋ทฐํ‹ฐ / ๋ผ์ดํ”„ ====
    "AI ๋ชจ๋ธ์ด 2025 ํŒจ์…˜์œ„ํฌ๋ฅผ ์žฅ์•…ํ•œ ์ด์œ ",
    "AI ๋ฏธ๋…€์˜ ํ•˜๋ฃจ: ์ถœ๊ทผ๋ถ€ํ„ฐ ๋ฐ์ดํŠธ๊นŒ์ง€",
    "AI ์ธํ”Œ๋ฃจ์–ธ์„œ์˜ ์…€์นด ๋ฃจํ‹ด (ํ˜„์‹ค๊ฐ 200%)",
    "AI๊ฐ€ ์ง์ ‘ ๊ณ ๋ฅธ ์˜ค๋Š˜์˜ ๋ฐ์ผ๋ฆฌ๋ฃฉ",
    "AI ์บ๋ฆญํ„ฐ๊ฐ€ ๊พธ๋ฏผ ๋ฏธ๋‹ˆ๋ฉ€ ์ธํ…Œ๋ฆฌ์–ด",
    "AI ์—ฌ์นœ์˜ VLOG: ๋‚˜๋ž‘ ํ•˜๋ฃจ ์‚ด์•„๋ณด๊ธฐ",
    "AI๊ฐ€ ์ฝ”๋””ํ•œ ๋‚จ์ž ํŒจ์…˜, ํ˜„์‹ค๋ณด๋‹ค ๋‚ซ๋‹ค",
    "AI ํ—ค์–ด์Šคํƒ€์ผ ์ถ”์ฒœ TOP5",
    "AI๊ฐ€ ์•Œ๋ ค์ฃผ๋Š” ์—ฌ๋ฆ„ ๋ฐ์ดํŠธ๋ฃฉ ๊ฟ€์กฐํ•ฉ",
    "AI๋กœ ๋งŒ๋“  ์ด์ƒํ˜• ์–ผ๊ตด, ์‹ค์ œ๋กœ ๋ณด๋ฉด ์ด๋Ÿฐ ๋А๋‚Œ",
    "AI ๋ชจ๋ธ์ด ํŒจ์…˜์‡ผ๋ฅผ ์žฅ์•…ํ•œ ๋‚ ",
    "AI๊ฐ€ ๊ณ„์ ˆ๋ณ„ ์ฝ”๋”” 10์ดˆ ์…”ํ”Œ์„ ๋ณด์—ฌ์ค€๋‹ค๋ฉด",

    # ==== ์ผ์ƒ / ๋“œ๋ผ๋งˆํ‹ฑ / ๋ฆฌ์–ผ๋ฃจํ‹ด ====
    "AI๋กœ ๋ฐ”๋€ ๋‚ด ํ•˜๋ฃจ, ์ถœ๊ทผ๋ถ€ํ„ฐ ์ž ๋“ค๊ธฐ๊นŒ์ง€",
    "AI๊ฐ€ ์ธ๊ฐ„์˜ ํ•˜๋ฃจ๋ฅผ ์™„๋ฒฝํ•˜๊ฒŒ ๋ณต์ œํ•œ๋‹ค๋ฉด",
    "AI๊ฐ€ ๋‚˜ ๋Œ€์‹  ์ถœ๊ทผํ•˜๋ฉด ์ƒ๊ธฐ๋Š” ์ผ",
    "AI ์—ฌ์ž์นœ๊ตฌ์™€ ํ˜„์‹ค ๋‚จ์ž์˜ ํ•˜๋ฃจ ๋ธŒ์ด๋กœ๊ทธ",
    "AI๊ฐ€ ์ง‘์•ˆ์ผ์„ ๋งก์œผ๋ฉด ์ง„์งœ ํŽธํ• ๊นŒ",
    "AI๊ฐ€ ๋ฐ˜๋ ค๊ฒฌ ์‚ฐ์ฑ…์„ ๋Œ€์‹ ํ•˜๋ฉด ๋ฒŒ์–ด์ง€๋Š” ์ผ",
    "AI ์ธํ”Œ๋ฃจ์–ธ์„œ์˜ ๋ชจ๋‹ ๋ฃจํ‹ด์ด ์‹ค์ œ๋กœ ์กด์žฌํ•œ๋‹ค๋ฉด",
    "AI๊ฐ€ ์ง์ ‘ ๋งŒ๋“  ์š”๋ฆฌ, ๋ง›์žˆ์„๊นŒ?",
    "AI๊ฐ€ ์ฃผ์‹ ํˆฌ์žํ•˜๋ฉด ์–ผ๋งˆ๋‚˜ ๋ฒŒ๊นŒ?",
    "AI ๋น„์„œ์™€ 24์‹œ๊ฐ„ ํ•จ๊ป˜ ์‚ด์•„๋ณด๊ธฐ",
    "AI๊ฐ€ ๋‚˜ ๋Œ€์‹  ํšŒ์˜์— ์ฐธ์„ํ•œ๋‹ค๋ฉด",
    "AI๊ฐ€ ์—ฌํ–‰ ์ฝ”์Šค๋ฅผ ํ•˜๋ฃจ ๋งŒ์— ์งœ์ค€๋‹ค๋ฉด",

    # ==== ์—ฐ์•  / ๊ฐ์ • / ๋ฆฌ์•ก์…˜ ====
    "AI ์—ฌ์ž์นœ๊ตฌ๊ฐ€ ์งˆํˆฌ๋ฅผ ๋А๋‚€๋‹ค๋ฉด",
    "AI ๋‚จ์นœ์ด ์นดํ†กๆ—ข่ชญ็„ก่ฆ– ํ•œ๋‹ค๋ฉด",
    "AI ์บ๋ฆญํ„ฐ๊ฐ€ ๊ณ ๋ฐฑ์„ ๋ฐ›์•„์ค„๊นŒ?",
    "AI์™€ ์ธ๊ฐ„์˜ ์ฒซ ๋ฐ์ดํŠธ (์‹œ๋ฎฌ๋ ˆ์ด์…˜)",
    "AI๊ฐ€ ์—ฐ์•  ์กฐ์–ธ์„ ํ•ด์ค€๋‹ค๋ฉด ์ง„์งœ ํ†ตํ• ๊นŒ?",
    "AI๊ฐ€ ์šธ๋ฉด ์ง„์งœ ๊ฐ์ •์ผ๊นŒ?",
    "AI๊ฐ€ ์‚ฌ๋ž‘์„ ๋ฐฐ์šด๋‹ค๋ฉด ์ƒ๊ธฐ๋Š” ๋ณ€ํ™”",
    "AI๊ฐ€ ํ—ค์–ด์ง„ ์—ฐ์ธ์„ ๋‹ค์‹œ ๋งŒ๋‚ฌ์„ ๋•Œ",
    "AI๊ฐ€ ๋‚ด ์‚ฌ์ง„์œผ๋กœ ๋‚˜๋ฅผ ์‚ฌ๋ž‘ํ•˜๊ฒŒ ๋œ๋‹ค๋ฉด",
    "AI์™€ ์ธ๊ฐ„์ด ์‹ธ์šฐ๋ฉด ๋ˆ„๊ฐ€ ๋จผ์ € ์‚ฌ๊ณผํ• ๊นŒ?",
    "AI๊ฐ€ ์†Œ๊ฐœํŒ…์—์„œ ๋ง์‹ค์ˆ˜ํ•œ๋‹ค๋ฉด",
    "AI๊ฐ€ ์ปคํ”Œ ์‚ฌ์ง„์„ ์žฌํ•ด์„ํ•ด ์ค€๋‹ค๋ฉด",

    # ==== ์Œ์‹ / ์ฑŒ๋ฆฐ์ง€ / ๊ฟ€์กฐํ•ฉ ====
    "ํŽธ์˜์  ๊ฟ€์กฐํ•ฉ TOP5, ์ง„์งœ ๋ฐ˜์น™๊ธ‰ ์กฐํ•ฉ ๋ชจ์Œ",
    "AI ์…ฐํ”„๊ฐ€ ๋งŒ๋“  ๋ผ๋ฉด ๊ฟ€์กฐํ•ฉ",
    "AI๊ฐ€ ์Œ์‹์‚ฌ์ง„์„ ๋ณด๊ณ  ๋ ˆ์‹œํ”ผ๋ฅผ ๋งŒ๋“ ๋‹ค๋ฉด",
    "AI ๋จน๋ฐฉ: ์ธ๊ฐ„๋ณด๋‹ค ๋” ๋ฆฌ์–ผํ•˜๊ฒŒ ๋จน๋Š”๋‹ค",
    "AI ์บ๋ฆญํ„ฐ๊ฐ€ ์นดํŽ˜ ์Œ๋ฃŒ ์ถ”์ฒœํ•ด์ค€๋‹ค",
    "AI๊ฐ€ ๊ฐ€์žฅ ์ข‹์•„ํ•˜๋Š” ๊ฐ„์‹ TOP3",
    "AI ๋‹ค์ด์–ดํŠธ ๋ฃจํ‹ด, ํ˜„์‹ค๋ณด๋‹ค ์ •ํ™•ํ•˜๋‹ค",
    "AI๊ฐ€ ์š”๋ฆฌํ•˜๋ฉด ์ง„์งœ ๋ง›์žˆ์„๊นŒ?",
    "AI๊ฐ€ ๊ณ ๋ฅธ ํŽธ์˜์  ๋„์‹œ๋ฝ 1๋“ฑ ๋ฉ”๋‰ด",
    "AI๊ฐ€ ํ•œ๊ตญ ์Œ์‹ ์ฒ˜์Œ ๋จน์—ˆ์„ ๋•Œ ๋ฐ˜์‘",
    "AI๊ฐ€ 10๋ถ„ ๋งŒ์— ํ™ˆ์นดํŽ˜๋ฅผ ๊ตฌํ˜„ํ•œ๋‹ค๋ฉด",
    "AI๊ฐ€ ์„ธ๊ณ„ ๊ธธ๊ฑฐ๋ฆฌ ์Œ์‹์„ ์žฌํ˜„ํ•œ๋‹ค๋ฉด",

    # ==== ํ•™์Šต / ์ž๊ธฐ๊ณ„๋ฐœ / ์ง€์‹ ====
    "ํ•œ ๋‹ฌ ๋งŒ์— ์˜์–ด ๋ฆฌ์Šค๋‹ ํญ๋ฐœ์ ์œผ๋กœ ์˜ฌ๋ฆฌ๋Š” ๋ฒ•",
    "AI๊ฐ€ ์•Œ๋ ค์ฃผ๋Š” ๊ณต๋ถ€ ์ง‘์ค‘๋ ฅ ๋ฃจํ‹ด",
    "AI๊ฐ€ ์ง์ ‘ ์„ค๊ณ„ํ•œ โ€˜๊ธฐ์–ต๋ ฅ ํ›ˆ๋ จ๋ฒ•โ€™",
    "AI๊ฐ€ ์ฝ”๋”ฉ ๋ฐฐ์›Œ์„œ ๋งŒ๋“  ์ฒซ ํ”„๋กœ์ ํŠธ",
    "AI ํŠœํ„ฐ์™€ ํ•จ๊ป˜ ์˜์–ดํšŒํ™” ์—ฐ์Šตํ•˜๊ธฐ",
    "AI๊ฐ€ ์Šค๋งˆํŠธํฐ ์ค‘๋…์„ ๊ณ ์น˜๋Š” ๋ฒ•",
    "AI๊ฐ€ ์ธ๊ฐ„๋ณด๋‹ค ๋น ๋ฅด๊ฒŒ ์ฑ… ์š”์•ฝํ•˜๋Š” ๋ฒ•",
    "AI๊ฐ€ ๋งŒ๋“  ์‹œํ—˜ ๋Œ€๋น„ ๊ณต๋ถ€ ๋ฃจํ‹ด",
    "AI๊ฐ€ ๋‡Œ ๊ณผํ•™์œผ๋กœ ์ง‘์ค‘๋ ฅ์„ ๋†’์ธ๋‹ค",
    "AI ์„ ์ƒ๋‹˜์ด ์•Œ๋ ค์ฃผ๋Š” ํ† ์ต ๋ฆฌ์Šค๋‹ ๋น„๋ฒ•",
    "AI๊ฐ€ ํ•˜๋ฃจ 10๋ถ„ ์Šคํ”ผํ‚น ํ›ˆ๋ จ ๋ฃจํ‹ด์„ ์งœ์ค€๋‹ค๋ฉด",

    # ==== ์‚ฌํšŒ / ๋‰ด์Šค / ๋ฐ˜์ „ ====
    "AI๊ฐ€ ๋งŒ๋“  ๊ฐ€์งœ ๋‰ด์Šค, ๋‹น์‹ ์€ ์†์„๊นŒ",
    "AI ์บ๋ฆญํ„ฐ๊ฐ€ ๋Œ€ํ†ต๋ น์— ์ถœ๋งˆํ•œ๋‹ค๋ฉด",
    "AI ๊ธฐ์ž๊ฐ€ ์ง์ ‘ ๋‰ด์Šค ์ง„ํ–‰์„ ๋งก๋Š”๋‹ค๋ฉด",
    "AI๊ฐ€ ์ธํ”Œ๋ฃจ์–ธ์„œ๋ฅผ ๋Œ€์ฒดํ•œ ์„ธ์ƒ",
    "AI๊ฐ€ ๋งŒ๋“  ๊ด‘๊ณ , ์ง„์งœ๋ณด๋‹ค ์„ค๋“๋ ฅ ์žˆ๋‹ค",
    "AI ์บ๋ฆญํ„ฐ๊ฐ€ ํ† ๋ก  ํ”„๋กœ๊ทธ๋žจ์— ๋‚˜์˜จ๋‹ค๋ฉด",
    "AI ๋ชจ๋ธ์ด SNS๋ฅผ ์ ๋ นํ•˜๋Š” ์ด์œ ",
    "AI๊ฐ€ ์„ ๊ฑฐ์— ๊ฐœ์ž…ํ•œ๋‹ค๋ฉด ์ƒ๊ธธ ์ผ",
    "AI์˜ ๊ฐ์ • ํ‘œํ˜„์ด ์ง„์งœ์ฒ˜๋Ÿผ ๋ณด์ผ ๋•Œ",
    "ํŠน์ด์ ์ด ์˜จ AI ์„ธ์ƒ, ์›ƒ๊ธฐ์ง€๋งŒ ๋ฌด์„ญ๋‹ค",
    "AI๋กœ ๋งŒ๋“  ์˜ํ™” ์˜ˆ๊ณ ํŽธ์ด ์ง„์งœ ์˜ํ™”๋ณด๋‹ค ๋ฉ‹์ง€๋‹ค",
    "๊ฐค๋Ÿญ์‹œ vs ์•„์ดํฐ ์นด๋ฉ”๋ผ, ์ง„์งœ ์ฐจ์ด 1์ดˆ ๋น„๊ต",
    "AI ์•„์ด๋Œ์ด ๋ถ€๋ฅด๋Š” K-POP ์ปค๋ฒ„ ๋ฌด๋Œ€",
    "AI๋กœ ๋งŒ๋“  ๊ฐ€์ƒ ์•„์ด๋Œ, ์ง„์งœ๋ณด๋‹ค ์˜ˆ์œ ์ด์œ ",
]
_seed_iter = itertools.cycle(SEED_TOPICS)

# ===== ์š”์ฒญ/์‘๋‹ต =====
class GenerateReq(BaseModel):
    mode: Optional[str] = Field(None, description="auto | topic")
    topic: Optional[str] = None
    count: int = Field(30, ge=1, le=80, description="์ƒ์„ฑํ•  ์ œ๋ชฉ ์ˆ˜(์ตœ๋Œ€ 80)")
    # ์–ธ์–ด/๊ตญ๊ฐ€ (ํ˜„์ง€ํ™”)
    lang: str = Field("ํ•œ๊ตญ์–ด", description="์˜ˆ: ํ•œ๊ตญ์–ด/Korean/ko/ko-KR/English/en/zh ๋“ฑ")
    country: Optional[str] = Field(None, description="์˜ˆ: KR, US, JP, ES, MX, CN ๋“ฑ. ์—†์œผ๋ฉด ์–ธ์–ด์— ๋งž์ถฐ ์ถ”๋ก ")
    length: str = Field("medium", description="short | medium | long")
    style: str = Field("meme-shock", description="meme-shock | wholesome | informative | clickbait")
    emoji: int = Field(1, ge=0, le=2)
    numberless: bool = Field(True)
    extra_hint: Optional[str] = None
    trend_source: str = Field("pytrends", description="pytrends | seed")
    passes: int = Field(3, ge=1, le=6, description="๋‹ค์–‘์„ฑ ํ™•๋ณด์šฉ ์ƒ˜ํ”Œ๋ง ํšŸ์ˆ˜")

class GenerateResp(BaseModel):
    topic: str
    titles: List[str]
    used_prompt: str
    trend_source: str

class TopicResp(BaseModel):
    topics: List[str]
    lang: str
    country: str
    category: Optional[str] = None

class ShortsPromptReq(BaseModel):
    topic: str = Field(..., description="์ฃผ์ œ(์˜ˆ: ํŽธ์˜์  ๊ฟ€์กฐํ•ฉ TOP5)")
    title: str = Field(..., description="์„ ์ •๋œ ์ œ๋ชฉ(ํ•œ ์ค„)")
    lang: str = Field("ko")
    style: str = Field("meme-shock")
    tone: Optional[str] = Field(None, description="energetic | wholesome | informative | edgy ๋“ฑ")
    duration_sec: int = Field(30, ge=15, le=60)
    cuts: int = Field(5, ge=5, le=8)
    emoji: int = Field(1, ge=0, le=2)

class ShortsPromptResp(BaseModel):
    topic: str
    title: str
    prompt: str
    lang: str
    style: str
    cuts: int
    duration_sec: int

# ===== ์–ธ์–ด/๊ตญ๊ฐ€ ์ •๊ทœํ™” =====
LANG_MAP = {
    "ko": ("ko", "ํ•œ๊ตญ์–ด"), "ko-kr": ("ko", "ํ•œ๊ตญ์–ด"), "korean": ("ko", "ํ•œ๊ตญ์–ด"), "ํ•œ๊ตญ์–ด": ("ko", "ํ•œ๊ตญ์–ด"),
    "en": ("en", "English"), "en-us": ("en", "English"), "english": ("en", "English"), "์˜์–ด": ("en", "English"),
    "ja": ("ja", "ๆ—ฅๆœฌ่ชž"), "ja-jp": ("ja", "ๆ—ฅๆœฌ่ชž"), "japanese": ("ja", "ๆ—ฅๆœฌ่ชž"), "์ผ๋ณธ์–ด": ("ja", "ๆ—ฅๆœฌ่ชž"),
    "es": ("es", "Espaรฑol"), "es-es": ("es", "Espaรฑol"), "es-mx": ("es", "Espaรฑol"), "spanish": ("es", "Espaรฑol"), "์ŠคํŽ˜์ธ์–ด": ("es", "Espaรฑol"),
    "zh": ("zh", "ไธญๆ–‡"), "zh-cn": ("zh", "ไธญๆ–‡"), "chinese": ("zh", "ไธญๆ–‡"), "์ค‘๊ตญ์–ด": ("zh", "ไธญๆ–‡"), "ไธญๆ–‡": ("zh", "ไธญๆ–‡"),
}
PNT_MAP = {
    "KR": ("south_korea", "ko-KR"),
    "US": ("united_states", "en-US"),
    "JP": ("japan", "ja-JP"),
    "ES": ("spain", "es-ES"),
    "MX": ("mexico", "es-419"),
    "CN": ("china", "zh-CN"),  # pytrends ๋ฏธ์ง€์›/๋ถˆ์•ˆ์ • ๊ฐ€๋Šฅ์„ฑ ์žˆ์Œ
}
LANG_DEFAULT_COUNTRY = {"ko": "KR", "en": "US", "ja": "JP", "es": "ES", "zh": "CN"}

def normalize_lang_and_country(lang_in: str, country_in: Optional[str]) -> Tuple[str, str, str]:
    key = (lang_in or "").strip().lower().replace("_", "-")
    if key in LANG_MAP: lang_code, pretty = LANG_MAP[key]
    else:               lang_code, pretty = ("ko", "ํ•œ๊ตญ์–ด")
    country = (country_in or "").upper().strip() or LANG_DEFAULT_COUNTRY.get(lang_code, "US")
    if country not in PNT_MAP: country = LANG_DEFAULT_COUNTRY.get(lang_code, "US")
    return lang_code, pretty, country

# ===== ํ˜„์ง€ํ™” ๋ฆฌ์†Œ์Šค =====
EXAMPLES = {
    "ko": ("์˜ˆ์‹œ(ํ˜•์‹๋งŒ ์ฐธ๊ณ ):\n"
           "์•„์ดํฐ๋„ ํ”๋“ค๋ฆฐ ๊ฐค๋Ÿญ์‹œ ๊ธฐ๋Šฅ, ์ด๊ฑด ๋ชฐ๋ž์ฃ ?\n"
           "AI๋กœ 1๋ถ„ ์ปท ์˜์ƒ ๋งŒ๋“ค๊ธฐโ€ฆ ์‹คํ™”๋ƒ ๐Ÿคฏ\n"
           "ํŽธ์˜์  ์กฐํ•ฉ TOP5, ๋งˆ์ง€๋ง‰์ด ๋ฏธ์ณค๋‹ค ใ„ทใ„ท\n"),
    "en": ("Examples (format only):\n"
           "iPhone users switching? This Galaxy feature is wild ๐Ÿคฏ\n"
           "Make a viral short in 60sโ€ฆ actually works\n"
           "Top 5 convenience-store hacks (the last one is insane)\n"),
    "ja": ("ไพ‹๏ผˆๅฝขๅผใฎใฟๅ‚่€ƒ๏ผ‰:\n"
           "iPhoneๆดพใ‚‚ๆบใ‚ŒใŸGalaxyๆฉŸ่ƒฝใ€็ŸฅใฃใฆใŸ๏ผŸ\n"
           "AIใง60็ง’ใ‚ทใƒงใƒผใƒˆไฝœๆˆโ€ฆใƒžใ‚ธใ‹ ๐Ÿคฏ\n"
           "ใ‚ณใƒณใƒ“ใƒ‹็ฅžใ‚ขใƒฌใƒณใ‚ธTOP5ใ€ๆœ€ๅพŒใŒใƒคใƒใ„\n"),
    "es": ("Ejemplos (solo formato):\n"
           "ยฟUsuarios de iPhone dudando? Esta funciรณn de Galaxy es una locura ๐Ÿคฏ\n"
           "Crea un short viral en 60sโ€ฆ funciona de verdad\n"
           "Top 5 trucos de tienda, el รบltimo te vuela la cabeza\n"),
    "zh": ("็คบไพ‹๏ผˆไป…ไพ›ๆ ผๅผๅ‚่€ƒ๏ผ‰๏ผš\n"
           "iPhone็”จๆˆท้ƒฝ้œ‡ๆƒŠไบ†๏ผ่ฟ™้กนGalaxyๅŠŸ่ƒฝๅคช็ฆป่ฐฑไบ† ๐Ÿคฏ\n"
           "AIไธ€ๅˆ†้’Ÿๅš็ˆ†ๆฌพ็Ÿญ่ง†้ข‘๏ผŒ็œŸ็š„ๅ‡็š„๏ผŸ\n"
           "ไพฟๅˆฉๅบ—็ฅž็ป„ๅˆTOP5๏ผŒๆœ€ๅŽไธ€ไธช็›ดๆŽฅ็‚ธ่ฃ‚๏ผ\n"),
}
HOOKS = {
    "ko": ["์ด๊ฑด ๋ชฐ๋ž์ฃ ?", "์†Œ๋ฆ„", "์ถฉ๊ฒฉ", "์‹คํ™”๋ƒ", "TOP5", "ใ„นใ…‡", "๋Œ€๋ฐ•", "๋ฏธ์ณค๋‹ค", "๋ฐ˜์ „ ์žˆ์Œ", "ํ•œ์ค„ ์š”์•ฝ", "์ง€๊ธˆ ์•ˆ ๋ณด๋ฉด ์†ํ•ด", "30์ดˆ ์ปท", "๋๊นŒ์ง€ ๋ณด์„ธ์š”", "์•Œ๊ณ  ๋ณด๋ฉด ๋” ์†Œ๋ฆ„", "์ดˆ๊ฐ„๋‹จ"],
    "en": ["did you know?", "shocking", "insane", "is this real?", "TOP 5", "no way", "viral", "mind-blown", "plot twist", "one-line tip", "donโ€™t miss this", "30s hack", "watch till the end", "low-key genius"],
    "ja": ["็ŸฅใฃใฆใŸ๏ผŸ", "้ณฅ่‚Œ", "่กๆ’ƒ", "ใƒžใ‚ธ๏ผŸ", "TOP5", "ใ‚„ใฐใ„", "ใƒใ‚บใ‚‹", "็ฅž", "ใพใ•ใ‹ใฎๅฑ•้–‹", "่ฆ็‚นใ ใ‘", "่ฆ‹้€ƒใ—ๅŽณ็ฆ", "30็ง’ใงOK", "ๆœ€ๅพŒใพใง่ฆ‹ใฆ", "ๅฎŸใฏใ‚ณใƒฌ"],
    "es": ["ยฟlo sabรญas?", "impactante", "una locura", "ยฟes real?", "TOP 5", "no puede ser", "viral", "mente en blanco", "giro inesperado", "tip en una lรญnea", "no te lo pierdas", "truco de 30s", "hasta el final", "dato clave"],
    "zh": ["้œ‡ๆƒŠ", "ๅคช็ฆป่ฐฑไบ†ๅง", "ไฝ ็ปๅฏนๆƒณไธๅˆฐ", "TOP5", "็ฝ‘ๅ‹้ƒฝๆƒŠๅ‘†ไบ†", "ๅคช็‚ธไบ†", "็ฌ‘ๆญป", "็ ด้˜ฒไบ†", "่ฟ™ๆ“ไฝœ้€†ๅคฉ", "็œŸๆ•ขๆ‹", "ไธ็œ‹ๅŽๆ‚”", "็ป†ๆ€ๆžๆ", "็ปไบ†", "ๅคช็‹ ไบ†"],
}
TAILS = {
    "ko": ["๋ฐฉ๋ฒ• ๊ณต๊ฐœ", "์‹œ์ฒญ์ž ํ›„๊ธฐ ํ„ฐ์ง", "์ „/ํ›„ ๋น„๊ต", "์ดˆ๋ณด๋„ ๊ฐ€๋Šฅ", "์ˆจ์€ ๊ธฐ๋Šฅ", "๋ฐ˜์ „ ์ฃผ์˜", "์‹ค์ „ ๊ฟ€ํŒ", "๋ชจ๋ฅด๋ฉด ์†ํ•ด", "ํ•œ ๋ฒˆ์— ๋", "๋ฐ”๋กœ ์จ๋จน๋Š” ์Šคํ‚ฌ", "ํ•ต์‹ฌ๋งŒ ์š”์•ฝ", "์ •๋ฆฌํ•ด๋“œ๋ฆผ"],
    "en": ["method revealed", "viewers went crazy", "before vs after", "beginner friendly", "hidden feature", "twist ahead", "pro tips", "donโ€™t miss out", "done in one go", "instant skill", "key points only", "quick recap"],
    "ja": ["ใ‚„ใ‚Šๆ–นๅ…ฌ้–‹", "่ฆ–่ด่€…ใฎๅๅฟœใŒ็ฅž", "ใƒ“ใƒ•ใ‚ฉใƒผ/ใ‚ขใƒ•ใ‚ฟใƒผ", "ๅˆๅฟƒ่€…OK", "้š ใ—ๆฉŸ่ƒฝ", "ใƒใ‚ฟใƒใƒฌๆณจๆ„", "ๅฎŸ็”จใƒ†ใ‚ฏ", "็Ÿฅใ‚‰ใชใใ‚ƒๆ", "ไธ€็™บใงๅฎŒไบ†", "ใ™ใไฝฟใˆใ‚‹ใƒฏใ‚ถ", "่ฆ็‚นใ ใ‘", "ใพใจใ‚ใฆ่งฃ่ชฌ"],
    "es": ["mรฉtodo revelado", "los viewers enloquecen", "antes vs despuรฉs", "para principiantes", "funciรณn oculta", "plot twist", "tips pro", "no te lo pierdas", "todo de una", "skill al instante", "puntos clave", "resumen rรกpido"],
    "zh": ["ๅฎŒๆ•ด็‰ˆๆฅไบ†", "็ฝ‘ๅ‹็ƒญ่ฎฎไธญ", "็œ‹ๅฎŒๆˆ‘ๆฒ‰้ป˜ไบ†", "ๅ‰ๅŽๅฏนๆฏ”็ฆป่ฐฑ", "ๆ–ฐๆ‰‹ไนŸ่ƒฝๅš", "้š่—ๅŠŸ่ƒฝๆ›ๅ…‰", "่ƒŒๅŽๅŽŸๅ› ้œ‡ๆ’ผ", "ไธ็œ‹็œŸ็š„ไบ", "ๆ•™็จ‹ๆฅไบ†", "ๅ…จ็ฝ‘็ˆ†็ซ", "ไบฒๆต‹ๆœ‰ๆ•ˆ", "ๅนฒ่ดงๆ€ป็ป“"],
}
PROMPT_HEADER = {
    "ko": "์—ญํ• : ๋‹น์‹ ์€ ํ•ด๋‹น ๊ตญ๊ฐ€์˜ ์œ ํŠœ๋ธŒ ์‡ผ์ธ  ์นดํ”ผ๋ผ์ดํ„ฐ๋‹ค.\n๊ณผ์—…: ์•„๋ž˜ โ€˜์ฃผ์ œโ€™๋กœ ํ˜„์ง€ ์‹œ์ฒญ์ž๊ฐ€ ๋งŽ์ด ๋ณด๊ฒŒ๋” ๋ฐ”์ด๋Ÿด ์ œ๋ชฉ์„ ์ƒ์„ฑํ•˜๋ผ.\n",
    "en": "Role: You are a YouTube Shorts copywriter for the target country.\nTask: Generate viral titles so local viewers want to watch.\n",
    "ja": "ๅฝนๅ‰ฒ: ใ‚ใชใŸใฏๅฏพ่ฑกๅ›ฝๅ‘ใ‘ใฎYouTubeใ‚ทใƒงใƒผใƒˆใ‚ณใƒ”ใƒผใƒฉใ‚คใ‚ฟใƒผใงใ™ใ€‚\n่ชฒ้กŒ: ็พๅœฐ่ฆ–่ด่€…ใŒ่ฆ‹ใŸใใชใ‚‹ใƒใ‚คใƒฉใƒซใ‚ฟใ‚คใƒˆใƒซใ‚’ไฝœๆˆใ—ใฆใใ ใ•ใ„ใ€‚\n",
    "es": "Rol: Eres copywriter de YouTube Shorts para el paรญs objetivo.\nTarea: Genera tรญtulos virales para atraer a los espectadores locales.\n",
    "zh": "่ง’่‰ฒ: ไฝ ๆ˜ฏไธ€ๅ้ขๅ‘ไธญๅ›ฝ่ง‚ไผ—็š„YouTube Shortsๆ–‡ๆกˆๅˆ›ไฝœ่€…ใ€‚\nไปปๅŠก: ๆ นๆฎไธป้ข˜็”Ÿๆˆ่ƒฝ่ฎฉๅฝ“ๅœฐ่ง‚ไผ—ๅœไธ‹ๆป‘ๅŠจใ€็‚นๅผ€่ง‚็œ‹็š„็ˆ†ๆฌพๆ ‡้ข˜ใ€‚\n",
}

def length_rule(length: str, lang_code: str) -> str:
    if lang_code in ("ko", "ja", "zh"):
        return {"short": "๊ฐ ์ œ๋ชฉ์€ 10~18์ž (์ž„ํŒฉํŠธ)",
                "medium": "๊ฐ ์ œ๋ชฉ์€ 16~28์ž (์งง๊ณ  ๊ฐ•๋ ฌ)",
                "long": "๊ฐ ์ œ๋ชฉ์€ 24~38์ž (๋ฐ˜์ „/์Šคํ† ๋ฆฌ)"}\
            .get(length, "๊ฐ ์ œ๋ชฉ์€ 16~28์ž")
    else:
        return {"short": "Each title 3โ€“6 words (punchy)",
                "medium": "Each title 5โ€“9 words (concise, strong hook)",
                "long": "Each title 8โ€“14 words (with twist/story)"}\
            .get(length, "Each title 5โ€“9 words")

def style_block(style: str, lang_code: str) -> str:
    blocks = {
        "ko": {"meme-shock": "- ๋ฐˆ/๋ฐ˜์ „/๊ฐ์ • ์ž๊ทน ์ ๊ทน ํ™œ์šฉ\n- ใ…‹ใ…‹ใ…‹, ใ„ทใ„ท, ใ… ใ… , ๐Ÿคฏ ํ—ˆ์šฉ\n- ํ˜ธ๊ธฐ์‹ฌ/์ถฉ๊ฒฉ ๋‹จ์–ด ์ ๊ทน ์‚ฌ์šฉ",
               "wholesome": "- ๊ณต๊ฐ/ํž๋ง ์ค‘์‹ฌ, ๋”ฐ๋œปํ•œ ์–ดํœ˜",
               "informative": "- ํ•ต์‹ฌ ํ‚ค์›Œ๋“œ ์ค‘์‹ฌ, ์‹ ๋ขฐ/๊ฐ„๊ฒฐ",
               "clickbait": "- ๊ณผ์žฅ/๋ฏธ์Šคํ„ฐ๋ฆฌ ํ†ค, ๊ถ๊ธˆ์ฆ ์œ ๋ฐœ(์‚ฌ์‹ค ์™œ๊ณก ๊ธˆ์ง€)"},
        "en": {"meme-shock": "- Use memes/twist/emotion\n- Allow ๐Ÿคฏ/omg vibe\n- Strong curiosity/shock words",
               "wholesome": "- Relatable/warm tone",
               "informative": "- Key facts first, concise & credible",
               "clickbait": "- Tease mystery, no deception"},
        "ja": {"meme-shock": "- ใƒใ‚ฟ/ใ‚ฎใƒฃใƒƒใƒ—/ๆ„Ÿๆƒ…ๅˆบๆฟ€ใ‚’ๆดป็”จ\n- ๐Ÿคฏ/ใ‚„ใฐใ„ ็ญ‰OK\n- ๅฅฝๅฅ‡ๅฟƒใƒป้ฉšใใƒฏใƒผใƒ‰ใ‚’ๅผทใ‚ใซ",
               "wholesome": "- ๅ…ฑๆ„Ÿใƒปใปใฃใ“ใ‚Š็ณปใฎ่ชžๅฝ™",
               "informative": "- ่ฆ็‚น้‡่ฆ–ใ€็ฐกๆฝ”",
               "clickbait": "- ใƒŸใ‚นใƒ†ใƒชใƒผ่ชฟใงๅผ•ใใ€่ช‡ๅผตใฏใ—ใคใคใ‚‚่ชคๆƒ…ๅ ฑ็ฆๆญข"},
        "es": {"meme-shock": "- Usa memes/giros/emociรณn\n- Se permite ๐Ÿคฏ vibes\n- Palabras de curiosidad/sorpresa fuertes",
               "wholesome": "- Tono cercano y cรกlido",
               "informative": "- Datos clave primero, conciso y fiable",
               "clickbait": "- Genera misterio sin engaรฑo"},
        "zh": {"meme-shock": "- ๅผบๅŒ–ๆข—/ๅ่ฝฌ/ๆƒ…็ปชๅผ ๅŠ›\n- ๅ…่ฎธ ๐Ÿคฏ/็ฆป่ฐฑ/ๆ— ่ฏญ ็ญ‰่ฏญๆฐ”\n- ไฝฟ็”จๅผบ็ƒˆๅฅฝๅฅ‡/้œ‡ๆƒŠ่ฏ",
               "wholesome": "- ๅ…ฑๆƒ…/ๆฒปๆ„ˆ้ฃŽ๏ผŒ่ฏญๆฐ”ๆธฉๆš–",
               "informative": "- ๅ…ณ้”ฎไฟกๆฏไผ˜ๅ…ˆ๏ผŒ็ฎ€ๆดๅฏไฟก",
               "clickbait": "- ๅŠ่ถณ่ƒƒๅฃ๏ผŒ้ฟๅ…่™šๅ‡ๅคธๅคง"},
    }
    return blocks.get(lang_code, {}).get(style, "")

def build_prompt(lang_code: str, pretty_lang: str, topic: str, count: int, length: str,
                 style: str, emoji: int, numberless: bool, extra_hint: Optional[str]) -> str:
    example = EXAMPLES.get(lang_code, EXAMPLES["ko"])
    header = PROMPT_HEADER.get(lang_code, PROMPT_HEADER["ko"])
    rules = [
        f"- ์ฃผ์ œ/Topic: {topic}",
        "- ์œ ํŠœ๋ธŒ ์‡ผ์ธ ์šฉ ๋ฐ”์ด๋Ÿด ์ œ๋ชฉ๋งŒ ์ƒ์„ฑ / Generate only viral titles for Shorts",
        "- ๊ฐ•๋ ฅํ•œ ํ›…(์ฒซ 5์ž)ยทํ˜ธ๊ธฐ์‹ฌ ๊ฐญยท๋ฐ˜์ „/๊ฐํƒ„ ํฌํ•จ / Strong hook, curiosity gap, twist",
        length_rule(length, lang_code),
        f"- ์ด๋ชจ์ง€๋Š” ์ตœ๋Œ€ {emoji}๊ฐœ / Up to {emoji} emoji(s)",
        "- ๋ฒˆํ˜ธยท๋ถˆ๋ฆฟยท๋”ฐ์˜ดํ‘œยท์„ค๋ช… ์—†์ด, ์ œ๋ชฉ๋งŒ ํ•œ ์ค„์”ฉ / No numbers/quotes/explanations",
        "- ์„œ๋กœ ๋‹ค๋ฅธ ์•„์ด๋””์–ด๋กœ ๋‹ค์–‘ํ•˜๊ฒŒ(์ค‘๋ณต ๊ธˆ์ง€) / Ensure diversity, no duplicates",
        "- ๊ณผ๋„ํ•œ ์š•์„ค/์„ ์ •์„ฑยท์ €์ž‘๊ถŒ/๋ช…์˜ˆํ›ผ์† ๊ธˆ์ง€ / No slurs/adult content/defamation",
        style_block(style, lang_code),
        (f"- ์ถ”๊ฐ€ ํžŒํŠธ / Extra hint: {extra_hint}" if extra_hint else ""),
        f"- ๋ฐ˜๋“œ์‹œ ์ด {count}์ค„ ์ถœ๋ ฅ / Exactly {count} lines",
    ]
    rule_text = "\n".join([r for r in rules if r])
    return f"{header}{rule_text}\n\n{example}\n์ถœ๋ ฅ/Output: ์ œ๋ชฉ๋งŒ ์ค„๋ฐ”๊ฟˆ์œผ๋กœ ๋‚˜์—ด / One title per line.\n"

# ===== ํŠธ๋ Œ๋“œ ์บ์‹œ/์กฐํšŒ =====
_cache = {"topics": [], "ts": datetime.min, "key": ""}

def fetch_trends_pytrends(n: int, country: str) -> List[str]:
    if not HAS_PYTRENDS:
        return []
    pn, hl = PNT_MAP.get(country, ("south_korea", "ko-KR"))
    cache_key = f"{pn}:{hl}"
    global _cache
    if _cache["topics"] and _cache["key"] == cache_key and datetime.utcnow() - _cache["ts"] < timedelta(minutes=10):
        return _cache["topics"][:n]
    try:
        pt = TrendReq(hl=hl, tz=540)
        df = pt.trending_searches(pn=pn)
        topics = [x for x in df[0].tolist() if isinstance(x, str)]
        _cache = {"topics": topics, "ts": datetime.utcnow(), "key": cache_key}
        return topics[:n]
    except Exception:
        return []

def pick_auto_topic(source: str, country: str) -> str:
    if source == "pytrends" and HAS_PYTRENDS:
        topics = fetch_trends_pytrends(8, country)
        if topics: return random.choice(topics)
    base = next(_seed_iter)
    pool = [base] + random.sample(SEED_TOPICS, k=min(3, len(SEED_TOPICS)))
    return random.choice(pool)

# ===== ์ œ๋ชฉ ํ›„์ฒ˜๋ฆฌ(๊ฐ•ํ™”) =====
_LEAK_PATTERNS = [
    r'^\s*(์ฃผ์ œ|topic)\s*[:/]',
    r'^\s*(์ถœ๋ ฅ|output)\s*[:/]',
    r'^\s*์˜ˆ์‹œ',
    r'์ƒ์„ฑํ•˜๋ผ[.!?]?\s*$',
    r'^\s*[-โ€ข]\s*$',
    r'^\s*๊ฐ ์ œ๋ชฉ์€',
]
def _fingerprint(s: str) -> str:
    return re.sub(r"[\s\W]+", "", s.lower())
def _valid_len(s: str, lang_code: str) -> bool:
    if lang_code in ("en", "es"):
        words = re.findall(r"\w+", s)
        return 3 <= len(words) <= 14
    return 6 <= len(s) <= 36  # ko/ja/zh
def _leak(s: str) -> bool:
    for p in _LEAK_PATTERNS:
        if re.search(p, s, flags=re.I):
            return True
    return False
def postprocess(raw: str, lang_code: str, numberless: bool = True) -> List[str]:
    if not raw: return []
    raw = re.sub(r"<extra_id_\d+>", "", raw)
    out = []
    for line in raw.splitlines():
        s = line.strip()
        if not s: continue
        if numberless:
            s = re.sub(r'^[\-\*\d]+\s*[\.\)]?\s*', '', s)
        s = re.sub(r'^[\"\':โ€œโ€โ€˜โ€™]+', '', s).strip()
        if _leak(s):
            continue
        if _valid_len(s, lang_code):
            out.append(s)
    seen, dedup = set(), []
    for s in out:
        key = _fingerprint(s)
        if key not in seen:
            seen.add(key)
            dedup.append(s)
    return dedup

def generate_titles(topic: str, count: int, req, lang_code: str, pretty_lang: str) -> Tuple[List[str], str]:
    base_params = [(0.9,0.9),(1.0,0.92),(0.85,0.95),(1.05,0.88),(0.95,0.97),(1.1,0.9)]
    param_grid = base_params[:max(1, min(req.passes, len(base_params)))]
    collected, used_prompts = [], []
    for (temperature, top_p) in param_grid:
        prompt = build_prompt(lang_code, pretty_lang, topic, count, req.length, req.style, req.emoji, req.numberless, req.extra_hint)
        gen = pipe(
            prompt,
            max_new_tokens=180 if req.length in ("medium","long") else 120,
            temperature=float(temperature),
            top_p=float(top_p),
            do_sample=True,
            repetition_penalty=1.12,
            no_repeat_ngram_size=3,
        )
        text = gen[0].get("generated_text", "").strip()
        used_prompts.append(prompt)
        batch = postprocess(text, lang_code, numberless=req.numberless)
        collected.extend(batch)
    seen, dedup = set(), []
    for s in collected:
        key = _fingerprint(s)
        if key not in seen:
            seen.add(key)
            dedup.append(s)
    if len(dedup) < count:
        hooks = HOOKS.get(lang_code, HOOKS["ko"])
        tails = TAILS.get(lang_code, TAILS["ko"])
        templates = []
        for _ in range(count * 2):
            h = random.choice(hooks); t = random.choice(tails)
            if lang_code in ("en", "es"): templates.append(f"{topic}: {h}, {t}")
            else:                          templates.append(f"{topic} {h} {t}")
        for s in templates:
            if not _valid_len(s, lang_code): continue
            key = _fingerprint(s)
            if key not in seen:
                seen.add(key); dedup.append(s)
            if len(dedup) >= count: break
    return dedup[:count], (used_prompts[-1] if used_prompts else "")

# ===== ํ† ํ”ฝ ํฌ์ง€(์˜์ƒํ™” ๊ฐ€๋Šฅํ•œ ์ฃผ์ œ ์ž๋™ ์ƒ์„ฑ) =====
TOPIC_CATEGORIES = ("ai-slice","ai-teach","ai-transform","ai-battle","ai-micro","mixed")
OBJ = {
    "ko": {
        "fruit": ["์ˆ˜๋ฐ•","๋ง๊ณ ","ํŒŒ์ธ์• ํ”Œ","์‚ฌ๊ณผ","ํ‚ค์œ„","์šฉ๊ณผ","๋ณต์ˆญ์•„","๋ฐ”๋‚˜๋‚˜","์ฝ”์ฝ”๋„›","ํฌ๋„"],
        "planet": ["์ง€๊ตฌ","ํ™”์„ฑ","ํ† ์„ฑ","๋ชฉ์„ฑ","๋‹ฌ","๊ธˆ์„ฑ","ํ•ด์™•์„ฑ","์ฒœ์™•์„ฑ","ํƒœ์–‘(๋ฏธ๋‹ˆ๋ฒ„์ „)"],
        "animal": ["๊ณ ์–‘์ด","๊ฐ•์•„์ง€","ํŒ๋‹ค","์ˆ˜๋‹ฌ","์•ต๋ฌด์ƒˆ","๊ณ ์Šด๋„์น˜","์นดํ”ผ๋ฐ”๋ผ"],
        "item": ["๋ฃจ๋น…์Šคํ๋ธŒ","์ดˆ์ฝœ๋ฆฟ๋ฐ”","๋ผ๋ฉด","๋–ก๋ณถ์ด","์Šค๋‹ˆ์ปค์ฆˆ","์ถ•๊ตฌ๊ณต","๋“œ๋ก "],
        "subject": ["์˜์–ด","ํ•œ๊ตญ์–ด","์ˆ˜ํ•™","์ถค","์š”๋ฆฌ","๊ฒŒ์ž„","๋“œ๋กœ์ž‰"],
        "elder": ["ํ• ๋จธ๋‹ˆ","ํ• ์•„๋ฒ„์ง€"],
        "persona": ["์™ธ๊ตญ์ธ","๋กœ๋ด‡","๋งˆ๋ฒ•์‚ฌ","์Šˆํผํžˆ์–ด๋กœ","AI ๋น„์„œ","์œ ํŠœ๋ฒ„"],
        "micro": ["๋ฏธ์„ธ๋จผ์ง€","์„ธํฌ","๋ฐ”์ด๋Ÿฌ์Šค","๋ฐ•ํ…Œ๋ฆฌ์•„","๋ฌผ๋ฐฉ์šธ","์„คํƒ• ๊ฒฐ์ •"],
    },
    "en": {
        "fruit": ["watermelon","mango","pineapple","apple","kiwi","dragon fruit","peach","banana","coconut","grapes"],
        "planet": ["Earth","Mars","Saturn","Jupiter","Moon","Venus","Neptune","Uranus","mini Sun"],
        "animal": ["cat","dog","panda","otter","parrot","hedgehog","capybara"],
        "item": ["Rubikโ€™s cube","chocolate bar","ramen","spicy rice cake","sneakers","soccer ball","drone"],
        "subject": ["English","Korean","Math","Dance","Cooking","Gaming","Drawing"],
        "elder": ["grandma","grandpa"],
        "persona": ["foreigner","robot","wizard","superhero","AI assistant","YouTuber"],
        "micro": ["fine dust","cells","virus","bacteria","droplet","sugar crystal"],
    },
}
def _obj(lang: str) -> dict:
    return OBJ.get(lang, OBJ["ko"])
def forge_topic(lang_code: str, category: str) -> str:
    o = _obj(lang_code)
    if category == "ai-slice":
        thing = random.choice(o["fruit"] + o["planet"] + o["item"])
        return f"AI๊ฐ€ {thing}๋ฅผ ๋ ˆ์ด์ € ์นผ๋กœ ์ž๋ฅด๋Š” ์˜์ƒ"
    if category == "ai-teach":
        who = random.choice(o["persona"] + o["elder"])
        subj = random.choice(o["subject"])
        return f"{who}๊ฐ€ ์œ ๋จธ๋Ÿฌ์Šคํ•˜๊ฒŒ {subj}๋ฅผ ๊ฐ€๋ฅด์น˜๋Š” 15์ดˆ ์‡ผ์ธ "
    if category == "ai-transform":
        a = random.choice(o["animal"] + o["item"])
        b = random.choice(o["fruit"] + o["planet"])
        return f"AI๊ฐ€ {a}๋ฅผ {b}(์œผ)๋กœ ๋ณ€์‹ ์‹œํ‚ค๋Š” ํƒ€์ž„๋žฉ์Šค"
    if category == "ai-battle":
        a = random.choice(o["animal"] + o["item"])
        b = random.choice(o["planet"] + o["fruit"])
        return f"AI๊ฐ€ {a} vs {b} ๋Œ€๊ฒฐ์„ ์‹œ๋ฎฌ๋ ˆ์ด์…˜ํ•˜๋Š” ์˜์ƒ"
    if category == "ai-micro":
        m = random.choice(o["micro"])
        t = random.choice(o["fruit"] + o["item"])
        return f"AI ๋งˆ์ดํฌ๋กœ ์„ธ๊ณ„ ํƒํ—˜: {t} ์† {m} ํ™•๋Œ€ ๊ด€์ฐฐ"
    return forge_topic(lang_code, random.choice(TOPIC_CATEGORIES[:-1]))  # mixed

# ===== ์‡ผ์ธ  ํ”„๋กฌํ”„ํŠธ(์ƒท๋ฆฌ์ŠคํŠธ) ์ƒ์„ฑ =====
def build_shorts_prompt(topic: str, title: str, lang_code: str, style: str, tone: Optional[str], cuts: int, duration_sec: int, emoji: int) -> str:
    # ์ปท ๊ฐœ์ˆ˜ ๋ณด์ •
    cuts = max(5, min(8, cuts))
    per_cut = max(4, min(7, duration_sec // cuts))  # ์ปท๋‹น ์ดˆ
    style_note = {
        "meme-shock": "๊ฐ•ํ•œ ํ›… + ๋ฐ˜์ „ + ๋ฆฌ๋“ฌ. ์ž๋ง‰ ์นœํ™”. ์งง์€ ๊ตฌ/๋ช…๋ น๋ฌธ.",
        "wholesome": "๊ณต๊ฐ/ํž๋ง ํ†ค. ์นœ์ ˆํ•œ ๋งํˆฌ. ํฌ๋ง/์‘์›.",
        "informative": "ํ•ต์‹ฌ ๋จผ์ €, ํŒฉํŠธ ์ค‘์‹ฌ. ๊ฐ„๊ฒฐ/์‹ ๋ขฐ.",
        "clickbait": "๊ถ๊ธˆ์ฆ ์œ ๋ฐœ, ๊ณผ์žฅ ํ—ˆ์šฉ(์‚ฌ์‹ค ์™œ๊ณก ๊ธˆ์ง€).",
    }.get(style, "๋ฆฌ๋“ฌยทํ˜ธ๊ธฐ์‹ฌ ์ค‘์‹ฌ.")
    tone_note = f"์ถ”๊ฐ€ ํ†ค: {tone}." if tone else ""
    emj = " ์ด๋ชจ์ง€ ์ ๋‹นํžˆ ์‚ฌ์šฉ" if emoji > 0 else " ์ด๋ชจ์ง€ ์‚ฌ์šฉ ๊ธˆ์ง€"

    header = (
        f"์—ญํ• : ์œ ํŠœ๋ธŒ ์‡ผ์ธ  ์ฝ˜ํ…์ธ  ํ”Œ๋ž˜๋„ˆ & ์นดํ”ผ๋ผ์ดํ„ฐ\n"
        f"๋ชฉํ‘œ: ์•„๋ž˜ '์ œ๋ชฉ'์„ ๊ธฐ๋ฐ˜์œผ๋กœ {duration_sec}์ดˆ ์ด๋‚ด ์˜์ƒ ํ”„๋กฌํ”„ํŠธ(๋Œ€๋ณธ ์ง€์‹œ๋ฌธ)๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.\n"
        f"๊ทœ์น™:\n"
        f"- ์ดˆ๋ฐ˜ 3์ดˆ ๊ฐ•ํ•œ ํ›…, 3~4๊ฐœ์˜ ํ•ต์‹ฌ ํฌ์ธํŠธ, ๋งˆ์ง€๋ง‰์— ์•ก์…˜์ฝœ(์ข‹์•„์š”/๋Œ“๊ธ€ ์œ ๋„)\n"
        f"- ์งง๊ณ  ๋ฆฌ๋“ฌ๊ฐ ์žˆ๊ฒŒ, ์ž๋ง‰์šฉ ๋ฌธ์žฅ\n"
        f"- ์ปท(์žฅ๋ฉด)์„ ๋ฒˆํ˜ธ๋กœ ๊ตฌ๋ถ„, ๊ฐ ์ปท 1~2๋ฌธ์žฅ\n"
        f"- ์ดฌ์˜ ์†Œ์Šค ์—†์–ด๋„ ์ƒ์„ฑํ˜• ์˜์ƒํˆด์— ๋ฐ”๋กœ ๋„ฃ์„ ์ˆ˜ ์žˆ๋Š” ๋ฌ˜์‚ฌ ํฌํ•จ\n"
        f"- ์Šคํƒ€์ผ: {style} ({style_note}), ์–ธ์–ด: {lang_code}, {tone_note}{emj}\n"
        f"- ์ปท ์ˆ˜: {cuts}๊ฐœ, ์ปท๋‹น {per_cut}์ดˆ ๋‚ด์™ธ\n\n"
        f"๋ฉ”ํƒ€:\n"
        f"โ€ข ์ฃผ์ œ(Topic): {topic}\n"
        f"โ€ข ์ œ๋ชฉ(Title): {title}\n\n"
        f"์ถœ๋ ฅ ํฌ๋งท ์˜ˆ์‹œ(ํ˜•์‹๋งŒ ์ฐธ๊ณ ):\n"
        f"1) ํ›…: ์‹œ์ฒญ์ž ํ˜ธ๊ธฐ์‹ฌ ํญ๋ฐœ ํ•œ ์ค„\n"
        f"2) ํฌ์ธํŠธ1: ๊ตฌ์ฒด ์˜ˆ์‹œ/๋ธŒ๋žœ๋“œ/๊ฐ€๊ฒฉ ๋“ฑ\n"
        f"3) ํฌ์ธํŠธ2: ๋น„๊ต/๋ฐ˜์ „/์ฃผ์˜\n"
        f"4) ํฌ์ธํŠธ3: ์‹ค์ „ ํŒ/๋ฐ”๋กœ ์จ๋จน๊ธฐ\n"
        f"5) ๋งˆ๋ฌด๋ฆฌ: ํ•œ ์ค„ ์š”์•ฝ + ์•ก์…˜์ฝœ(๋Œ“๊ธ€/์ข‹์•„์š” ์œ ๋„)\n\n"
        f"์ด์ œ ์œ„ ๊ทœ์น™์„ ์ฒ ์ €ํžˆ ์ง€์ผœ {cuts}๊ฐœ์˜ ์ปท์œผ๋กœ ํ•œ๊ตญ์–ด ํ”„๋กฌํ”„ํŠธ๋ฅผ ์ถœ๋ ฅํ•˜๋ผ."
    )
    return header

# ===== ์—”๋“œํฌ์ธํŠธ =====
@app.get("/topic/auto", response_model=TopicResp)
def topic_auto(
    count: int = Query(10, ge=1, le=100),
    lang: str = Query("ko"),
    country: Optional[str] = Query(None),
    category: Optional[Literal["ai-slice","ai-teach","ai-transform","ai-battle","ai-micro","mixed"]] = Query("mixed")
):
    lang_code, pretty_lang, country_code = normalize_lang_and_country(lang, country)
    cats = [category] if category and category != "mixed" else None
    topics = []
    if HAS_PYTRENDS:
        trendy = fetch_trends_pytrends(min(5, count), country_code)
        topics.extend(trendy)
    while len(topics) < count:
        cat = random.choice(cats) if cats else random.choice(TOPIC_CATEGORIES[:-1])
        topics.append(forge_topic(lang_code, cat))
    seen, uniq = set(), []
    for t in topics:
        k = re.sub(r"\s+", "", t.lower())
        if k not in seen:
            seen.add(k)
            uniq.append(t)
        if len(uniq) >= count: break
    return JSONResponse({"topics": uniq, "lang": pretty_lang, "country": country_code, "category": category}, media_type="application/json; charset=utf-8")

@app.get("/")
def root():
    return JSONResponse({"message": "NocoAI Title & Prompt Forge. Try GET /topic/auto, POST /generate, GET /generate/auto, POST /prompt/shorts"}, media_type="application/json; charset=utf-8")

@app.get("/health")
def health():
    return JSONResponse({"status": "ok", "model": MODEL_ID, "cache_size": len(_cache.get("topics", []))}, media_type="application/json; charset=utf-8")

@app.post("/generate", response_model=GenerateResp)
def generate(req: Optional[GenerateReq] = Body(default=None)):
    if req is None:
        req = GenerateReq()
    lang_code, pretty_lang, country = normalize_lang_and_country(req.lang, req.country)
    if req.topic and (req.mode is None or req.mode == "auto"):
        mode = "topic"
    else:
        mode = req.mode or ("topic" if req.topic else "auto")
    if mode == "topic" and req.topic:
        topic = req.topic; used_source = "custom"
    else:
        topic = pick_auto_topic(req.trend_source, country)
        used_source = req.trend_source if (req.trend_source == "pytrends" and HAS_PYTRENDS) else "seed"
    titles, used_prompt = generate_titles(topic, req.count, req, lang_code, pretty_lang)
    return JSONResponse({"topic": topic, "titles": titles, "used_prompt": used_prompt, "trend_source": used_source}, media_type="application/json; charset=utf-8")

@app.get("/generate/auto", response_model=GenerateResp)
def generate_auto(
    count: int = Query(30, ge=1, le=80),
    length: str = Query("medium"),
    style: str = Query("meme-shock"),
    emoji: int = Query(1, ge=0, le=2),
    numberless: bool = Query(True),
    trend_source: str = Query("pytrends"),
    passes: int = Query(3, ge=1, le=6),
    lang: str = Query("ko"),
    country: Optional[str] = Query(None),
):
    lang_code, pretty_lang, country_code = normalize_lang_and_country(lang, country)
    class _Req: pass
    req = _Req()
    req.lang = pretty_lang; req.length = length; req.style = style; req.emoji = emoji
    req.numberless = numberless; req.extra_hint = None; req.trend_source = trend_source; req.passes = passes
    topic = pick_auto_topic(trend_source, country_code)
    titles, used_prompt = generate_titles(topic, count, req, lang_code, pretty_lang)
    used_source = trend_source if (trend_source == "pytrends" and HAS_PYTRENDS) else "seed"
    return JSONResponse({"topic": topic, "titles": titles, "used_prompt": used_prompt, "trend_source": used_source}, media_type="application/json; charset=utf-8")

@app.post("/prompt/shorts", response_model=ShortsPromptResp)
def prompt_shorts(body: ShortsPromptReq):
    lang_code, _, _ = normalize_lang_and_country(body.lang, None)
    prompt = build_shorts_prompt(
        topic=body.topic,
        title=body.title,
        lang_code=lang_code,
        style=body.style,
        tone=body.tone,
        cuts=body.cuts,
        duration_sec=body.duration_sec,
        emoji=body.emoji
    )
    return JSONResponse({
        "topic": body.topic,
        "title": body.title,
        "prompt": prompt,
        "lang": lang_code,
        "style": body.style,
        "cuts": body.cuts,
        "duration_sec": body.duration_sec
    }, media_type="application/json; charset=utf-8")