import gradio as gr
import requests
import time
API_HOME = 'https://api.fliki.ai/v1'
END_GENERATE = '/generate'
END_STATUS = '/generate/status'
API_KEY = 'ZZUIQ4OZASNRQ8B8WYHNW'
def set_header():
header = {
"Content-Type": "application/json",
"Authorization": "Bearer " + API_KEY,
}
return header
# 비디오 또는 오디오 컨텐츠 생성하는 함수
def generate_contents(user_content, brand_name, aspect_ratio='landscape'):
url = API_HOME + END_GENERATE
VOICE_ID = '64ea1fbc310bccff6a4191ed' # Korean, Korea, Wolf Sea
# 멀티 라인 텍스트를 분리하여 각 줄을 별도의 씬으로 처리
scenes = [{"content": line.strip(), "voiceId": VOICE_ID} for line in user_content.split('\n') if line.strip()]
payload = {
"format": "video", # video | audio
"scenes": scenes,
"settings": {
'aspectRatio': aspect_ratio,
'subtitle': {
'fontColor': 'yellow',
'backgroundColor': 'black',
'placement': 'bottom',
'display': 'phrase',
},
},
"backgroundMusicKeywords": "happy, lofi, beats"
}
headers = set_header()
response = requests.request("POST", url, json=payload, headers=headers).json()
if response['success']:
return response['data']['id']
else:
return 'FAILED'
# 컨텐츠 생성 상태를 확인하는 함수
def generate_status(content_id):
url = API_HOME + END_STATUS
payload = {"id": content_id}
headers = set_header()
while True:
response = requests.request("POST", url, json=payload, headers=headers).json()
if response['success']:
status = response['data']['status']
if status == 'queued' or status == 'processing':
time.sleep(10) # 10초 대기
elif status == 'success':
return response['data']['file']
else:
break
return 'FAILED'
# Gradio 인터페이스 함수
def gradio_generate_contents(user_content, brand_name, aspect_ratio):
return generate_contents(user_content, brand_name, aspect_ratio)
def gradio_generate_status(content_id):
download_url = generate_status(content_id)
if download_url != 'FAILED':
display_text = download_url[:10] + '...' if len(download_url) > 10 else download_url
html_link = f'{display_text}'
html_video = f''
return html_link + '
' + html_video
else:
return "컨텐츠 생성 실패 또는 ID가 잘못되었습니다."
# 컨텐츠 생성 인터페이스
iface_create = gr.Interface(
fn=gradio_generate_contents,
inputs=[
gr.TextArea(label="컨텐츠 텍스트"),
gr.Textbox(label="브랜드명"),
gr.Dropdown(label="화면 비율", choices=['portrait', 'square', 'landscape'], value='landscape')
],
outputs=gr.Textbox(label="컨텐츠 ID"),
examples=[
[
"""Nature Republic Super Aqua Max 지성 피부용 프레시 워터 크림
아름다운 여성에게 진정 필요한것은 무엇일까요? 진정한 아름다움은 건강하고 맑은 피부에 있습니다.
아름다움의 여러가지 기준이 있겠지만, 깨끗한 피부가 그중 으뜸이자 바탕입니다.
소중한 당신의 피부 건강을 위해 보습과 미백의 기능성을 강화한 혁신적인 화장품을 추천합니다.
지금 바로 연락주시면 상세 안내를 제공해 드립니다.""",
"네이처리퍼블릭",
"landscape"
],
[
"""인생에 있어 행복이 무엇일까요?
야외에서 뛰어놀고 있는 멋진 개들을 보면 기분이 좋아집니다.
내곁에서 졸고 있는 고양이들이 사랑스럽죠?
행복은 결코 멀리 있지 않습니다. 오늘의 소중함에 감사합시다.""",
"행복",
"landscape"
]
]
)
# 상태 확인 및 비디오 다운로드 인터페이스
iface_status = gr.Interface(
fn=gradio_generate_status,
inputs=gr.Textbox(label="컨텐츠 ID"),
outputs=gr.HTML(label="다운로드 링크 및 비디오"),
examples=[
["659f5a3f096a487442e72dee"],
["659f6651d4c72225a9895ebb"]
] # 예시 추가
)
# 두 인터페이스를 탭으로 구성
iface_combined = gr.TabbedInterface([iface_create, iface_status], ["컨텐츠 생성", "상태 확인 및 다운로드"])
iface_combined.launch()