Spaces:
Runtime error
Runtime error
| 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() | |