video / app.py
seawolf2357's picture
Update app.py
f91f1da verified
raw
history blame
2.71 kB
import gradio as gr
import openai
import os
import requests
# OpenAI API ν‚€ μ„€μ •
openai.api_key = os.getenv("OPENAI_API_KEY")
# Pexels API ν‚€ μ„€μ •
PEXELS_API_KEY = "5woz23MGx1QrSY0WHFb0BRi29JvbXPu97Hg0xnklYgHUI8G0w23FKH62"
def generate_keyword_from_text(input_text):
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{
'role': 'user',
'content': f"λ‹€μŒ ν…μŠ€νŠΈλ₯Ό λ°”νƒ•μœΌλ‘œ Pexelsμ—μ„œ 잘 검색될 영문 ν‚€μ›Œλ“œ ν•œ 쀄을 μƒμ„±ν•˜μ„Έμš”: '{input_text}'"
}]
)
keyword_full_response = response['choices'][0]['message']['content']
keyword = keyword_full_response.split('\n', 1)[0].strip()
if keyword.startswith('"') and keyword.endswith('"'):
keyword = keyword[1:-1].strip()
return keyword
except Exception as e:
print(f"μ—λŸ¬ λ°œμƒ: {e}")
return f"ν‚€μ›Œλ“œ 생성 쀑 μ—λŸ¬ λ°œμƒ: {e}"
def search_pexels(keyword):
headers = {
'Authorization': PEXELS_API_KEY
}
params = {
'query': keyword,
'per_page': 10
}
try:
response = requests.get('https://api.pexels.com/v1/search', headers=headers, params=params)
response.raise_for_status()
data = response.json()
image_urls = [photo['src']['medium'] for photo in data['photos']]
return image_urls
except Exception as e:
print(f"Pexels API μ—λŸ¬: {e}")
return []
def keyword_to_images(input_text):
lines = input_text.split('\n') # μž…λ ₯ ν…μŠ€νŠΈλ₯Ό 쀄 λ‹¨μœ„λ‘œ 뢄리
all_image_urls = []
for line in lines:
if not line.strip(): # λΉ„μ–΄ μžˆλŠ” 쀄은 κ±΄λ„ˆλœ€
continue
keyword = generate_keyword_from_text(line)
if keyword.startswith("ν‚€μ›Œλ“œ 생성 쀑 μ—λŸ¬ λ°œμƒ"):
continue # ν‚€μ›Œλ“œ 생성 쀑 μ—λŸ¬κ°€ λ°œμƒν•œ 경우, κ·Έ 쀄은 κ±΄λ„ˆλœ€
image_urls = search_pexels(keyword)
all_image_urls.extend(image_urls) # 각 ν‚€μ›Œλ“œλ³„ 검색 κ²°κ³Όλ₯Ό λͺ¨λ‘ ν•©μΉ¨
return all_image_urls
# Gradio μΈν„°νŽ˜μ΄μŠ€ μ„€μ •κ³Ό μ‹€ν–‰
iface = gr.Interface(
fn=keyword_to_images,
inputs=gr.Textbox(lines=10, placeholder="여기에 Pexels 검색을 μœ„ν•œ ν…μŠ€νŠΈλ₯Ό μž…λ ₯ν•˜μ„Έμš”. 각 μ€„λ§ˆλ‹€ λ³„λ„μ˜ 검색 ν‚€μ›Œλ“œκ°€ μƒμ„±λ©λ‹ˆλ‹€."),
outputs=gr.Gallery(),
title="GPT 및 Pexels APIλ₯Ό μ΄μš©ν•œ 닀쀑 이미지 검색",
description="제곡된 ν…μŠ€νŠΈμ˜ 각 쀄을 λ°”νƒ•μœΌλ‘œ Pexels 검색에 μ‚¬μš©ν•  영문 ν‚€μ›Œλ“œλ₯Ό μžλ™ μƒμ„±ν•˜κ³ , ν•΄λ‹Ή ν‚€μ›Œλ“œλ‘œ Pexelsμ—μ„œ 이미지λ₯Ό κ²€μƒ‰ν•©λ‹ˆλ‹€."
)
iface.launch()