Spaces:
Sleeping
Sleeping
File size: 2,713 Bytes
077e44e b59f0da 5b0e95f f91f1da a0b6e16 79eed57 eef17a1 b8bab42 f91f1da 532321b f91f1da 532321b f91f1da 532321b f91f1da 532321b 3bdb854 f91f1da 9e2cf4f 53d3deb f91f1da b4a6b7a 53d3deb f91f1da |
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 |
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()
|