Spaces:
Runtime error
Runtime error
import os | |
import gradio as gr | |
import random | |
import time | |
import logging | |
import google.generativeai as genai | |
logging.basicConfig( | |
level=logging.INFO, | |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', | |
handlers=[ | |
logging.FileHandler("api_debug.log"), | |
logging.StreamHandler() | |
] | |
) | |
logger = logging.getLogger("idea_generator") | |
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") | |
genai.configure(api_key=GEMINI_API_KEY) | |
def choose_alternative(transformation): | |
if "/" not in transformation: | |
return transformation | |
parts = transformation.split("/") | |
if len(parts) != 2: | |
return random.choice([part.strip() for part in parts]) | |
left = parts[0].strip() | |
right = parts[1].strip() | |
if " " in left: | |
tokens = left.split(" ", 1) | |
prefix = tokens[0] | |
if not right.startswith(prefix): | |
option1 = left | |
option2 = prefix + " " + right | |
else: | |
option1 = left | |
option2 = right | |
return random.choice([option1, option2]) | |
else: | |
return random.choice([left, right]) | |
physical_transformation_categories = { | |
"κ³΅κ° μ΄λ": [ | |
"μ/λ€ μ΄λ", "μ’/μ° μ΄λ", "μ/μλ μ΄λ", "μΈλ‘μΆ νμ (κ³ κ° λλμ)", | |
"κ°λ‘μΆ νμ (κ³ κ° μ κΈ°)", "κΈΈμ΄μΆ νμ (μμΌλ‘ κΈ°μΈμ)", "μ μ΄λ", "λμ ν μ΄λ", | |
"κ΄μ±μ μν λ―Έλλ¬μ§", "νμ μΆ λ³ν", "λΆκ·μΉ νμ ", "νλ€λ¦Ό μ΄λ", "ν¬λ¬Όμ μ΄λ", | |
"무μ€λ ₯ λΆμ ", "μλ©΄ μ λΆμ ", "μ ν/λμ½", "μ¬λΌμ΄λ©", "λ‘€λ§", "μμ λν", | |
"μ볡 μ΄λ", "νμ± νκΉ", "κ΄ν΅", "ννΌ μμ§μ", "μ§κ·Έμ¬κ·Έ μ΄λ", "μ€μ μ΄λ" | |
], | |
"ν¬κΈ°μ νν λ³ν": [ | |
"λΆνΌ λμ΄λ¨/μ€μ΄λ¦", "κΈΈμ΄ λμ΄λ¨/μ€μ΄λ¦", "λλΉ λμ΄λ¨/μ€μ΄λ¦", "λμ΄ λμ΄λ¨/μ€μ΄λ¦", | |
"λ°λ λ³ν", "λ¬΄κ² μ¦κ°/κ°μ", "λͺ¨μ λ³ν", "μν λ³ν", "λΆκ· λ± λ³ν", | |
"볡μ‘ν νν λ³ν", "λΉνλ¦Ό/κΌ¬μ", "λΆκ· μΌν νμ₯/μΆμ", "λͺ¨μ리 λ₯κΈκ²/λ μΉ΄λ‘κ²", | |
"κΉ¨μ§/κ°λΌμ§", "μ¬λ¬ μ‘°κ° λλ μ§", "λ¬Ό μ ν", "λ¨Όμ§ μ ν", "μ°κ·Έλ¬μ§/볡μ", | |
"μ ν/νΌμ³μ§", "μμ°©/ν½μ°½", "λμ΄λ¨/μμΆ", "ꡬ겨μ§/ννν΄μ§", "λκ°μ§/λ¨λ¨ν΄μ§", | |
"λ§λ¦Ό/ν΄μ§", "κΊΎμ/ꡬλΆλ¬μ§" | |
], | |
# ... (μ€κ° μλ΅: λλ¨Έμ§ μΉ΄ν κ³ λ¦¬λ λμΌ) | |
# μλ΅λ λΆλΆλ κΈ°μ‘΄ μ½λ κ·Έλλ‘ μ μ§ | |
} | |
def query_gemini_api(prompt): | |
try: | |
model = genai.GenerativeModel('gemini-2.0-flash-thinking-exp-01-21') | |
response = model.generate_content(prompt) | |
try: | |
if hasattr(response, 'text'): | |
return response.text | |
if hasattr(response, 'candidates') and response.candidates: | |
if len(response.candidates) > 0: | |
candidate = response.candidates[0] | |
if hasattr(candidate, 'content'): | |
content = candidate.content | |
if hasattr(content, 'parts') and content.parts: | |
if len(content.parts) > 0: | |
return content.parts[0].text | |
if hasattr(response, 'parts') and response.parts: | |
if len(response.parts) > 0: | |
return response.parts[0].text | |
return "Unable to generate a response. API response structure is different than expected." | |
except Exception as inner_e: | |
logger.error(f"Error processing response: {inner_e}") | |
return f"An error occurred while processing the response: {str(inner_e)}" | |
except Exception as e: | |
logger.error(f"Error calling Gemini API: {e}") | |
if "API key not valid" in str(e): | |
return "API key is not valid. Please check your GEMINI_API_KEY environment variable." | |
return f"An error occurred while calling the API: {str(e)}" | |
def enhance_with_llm(base_description, obj_name, category): | |
prompt = f""" | |
λ€μμ '{obj_name}'μ '{category}' κ΄λ ¨ κ°λ¨ν μ€λͺ μ λλ€: | |
"{base_description}" | |
μ λ΄μ©μ λ³΄λ€ κ΅¬μ²΄ννμ¬, | |
1) μ°½μμ μΈ λͺ¨λΈ/컨μ /νμμ λ³νμ λν μ΄ν΄, | |
2) νμ ν¬μΈνΈμ κΈ°λ₯μ± λ±μ μ€μ¬μΌλ‘ | |
3~4λ¬Έμ₯μ μμ΄λμ΄λ‘ νμ₯ν΄ μ£ΌμΈμ. | |
""" | |
return query_gemini_api(prompt) | |
def generate_single_object_transformations(obj): | |
results = {} | |
for category, transformations in physical_transformation_categories.items(): | |
transformation = choose_alternative(random.choice(transformations)) | |
base_description = f"{obj}μ΄(κ°) {transformation} νμμ 보μΈλ€" | |
results[category] = {"base": base_description, "enhanced": None} | |
return results | |
def generate_two_objects_interaction(obj1, obj2): | |
results = {} | |
for category, transformations in physical_transformation_categories.items(): | |
transformation = choose_alternative(random.choice(transformations)) | |
template = random.choice([ | |
"{obj1}μ΄(κ°) {obj2}μ κ²°ν©νμ¬ {change}κ° λ°μνλ€", | |
"{obj1}κ³Ό(μ) {obj2}μ΄(κ°) μΆ©λνλ©΄μ {change}κ° μΌμ΄λ¬λ€" | |
]) | |
base_description = template.format(obj1=obj1, obj2=obj2, change=transformation) | |
results[category] = {"base": base_description, "enhanced": None} | |
return results | |
def generate_three_objects_interaction(obj1, obj2, obj3): | |
results = {} | |
for category, transformations in physical_transformation_categories.items(): | |
transformation = choose_alternative(random.choice(transformations)) | |
template = random.choice([ | |
"{obj1}, {obj2}, {obj3}μ΄(κ°) μΌκ°ν κ΅¬μ‘°λ‘ κ²°ν©νμ¬ {change}κ° λ°μνλ€", | |
"{obj1}μ΄(κ°) {obj2}μ(κ³Ό) {obj3} μ¬μ΄μμ λ§€κ°μ²΄ μν μ νλ©° {change}λ₯Ό μ΄μ§νλ€" | |
]) | |
base_description = template.format(obj1=obj1, obj2=obj2, obj3=obj3, change=transformation) | |
results[category] = {"base": base_description, "enhanced": None} | |
return results | |
def enhance_descriptions(results, objects): | |
obj_name = " λ° ".join([obj for obj in objects if obj]) | |
for category, result in results.items(): | |
result["enhanced"] = enhance_with_llm(result["base"], obj_name, category) | |
return results | |
def generate_transformations(text1, text2=None, text3=None): | |
if text2 and text3: | |
results = generate_three_objects_interaction(text1, text2, text3) | |
objects = [text1, text2, text3] | |
elif text2: | |
results = generate_two_objects_interaction(text1, text2) | |
objects = [text1, text2] | |
else: | |
results = generate_single_object_transformations(text1) | |
objects = [text1] | |
return enhance_descriptions(results, objects) | |
def format_results(results): | |
formatted = "" | |
for category, result in results.items(): | |
formatted += f"## {category}\n**κΈ°λ³Έ μμ΄λμ΄**: {result['base']}\n\n**νμ₯λ μμ΄λμ΄**: {result['enhanced']}\n\n---\n\n" | |
return formatted | |
############################################################################## | |
# μ€νΈλ¦¬λ°(Streaming) λ°©μμΌλ‘ μΆλ ₯νλ ν¨μ: yieldλ₯Ό μ¬μ© | |
############################################################################## | |
def process_inputs_stream(text1, text2, text3): | |
# 1) 첫 λ©μμ§ | |
yield "μ λ ₯κ° νμΈ μ€..." | |
time.sleep(0.3) | |
text1 = text1.strip() if text1 else None | |
text2 = text2.strip() if text2 else None | |
text3 = text3.strip() if text3 else None | |
if not text1: | |
yield "μ€λ₯: μ΅μ νλμ ν€μλλ₯Ό μ λ ₯ν΄μ£ΌμΈμ." | |
return # μ¬κΈ°μ ν¨μ μ’ λ£ | |
# 2) λ€μ λ©μμ§ | |
yield "μ°½μμ μΈ λͺ¨λΈ/컨μ /νμ λ³ν μμ΄λμ΄ μμ± μ€..." | |
time.sleep(0.3) | |
# 3) μ€μ μμ΄λμ΄ μμ± | |
results = generate_transformations(text1, text2, text3) | |
# 4) μ€κ° λ¨κ³ μΆλ ₯ | |
yield "κ²°κ³Ό ν¬λ§·ν μ€..." | |
time.sleep(0.3) | |
# 5) μ΅μ’ κ²°κ³Ό μ 리 | |
formatted = format_results(results) | |
# 6) κ²°κ³Ό μΆλ ₯ | |
yield formatted | |
# 7) μλ£ | |
yield "μλ£!" | |
def get_warning_message(): | |
if not GEMINI_API_KEY: | |
return "β οΈ νκ²½ λ³μ GEMINI_API_KEYκ° μ€μ λμ§ μμμ΅λλ€. Gemini API ν€λ₯Ό μ€μ νμΈμ." | |
return "" | |
with gr.Blocks(title="ν€μλ κΈ°λ° μ°½μμ λ³ν μμ΄λμ΄ μμ±κΈ°", | |
theme=gr.themes.Soft(primary_hue="teal", secondary_hue="slate", neutral_hue="neutral")) as demo: | |
gr.HTML(""" | |
<style> | |
body { background: linear-gradient(135deg, #e0eafc, #cfdef3); font-family: 'Arial', sans-serif; } | |
.gradio-container { padding: 20px; } | |
h1, h2 { text-align: center; } | |
h1 { color: #333; } | |
h2 { color: #555; } | |
.output { background-color: #ffffff; padding: 15px; border-radius: 8px; } | |
.gr-button { background-color: #4CAF50; color: white; border: none; border-radius: 4px; padding: 8px 16px; } | |
</style> | |
""") | |
gr.Markdown("# π ν€μλ κΈ°λ° μ°½μμ λ³ν μμ΄λμ΄ μμ±κΈ°") | |
gr.Markdown("μ λ ₯ν **ν€μλ**(μ΅λ 3κ°)λ₯Ό λ°νμΌλ‘, **μ°½μμ μΈ λͺ¨λΈ/컨μ /νμ λ³ν**μ λν μ΄ν΄μ **νμ ν¬μΈνΈ**, **κΈ°λ₯μ±** λ±μ μ€μ¬μΌλ‘ νμ₯λ μμ΄λμ΄λ₯Ό μ μν©λλ€.") | |
warning = gr.Markdown(get_warning_message()) | |
with gr.Row(): | |
with gr.Column(scale=1): | |
text_input1 = gr.Textbox(label="ν€μλ 1 (νμ)", placeholder="μ: μ€λ§νΈν°") | |
text_input2 = gr.Textbox(label="ν€μλ 2 (μ ν)", placeholder="μ: μΈκ³΅μ§λ₯") | |
text_input3 = gr.Textbox(label="ν€μλ 3 (μ ν)", placeholder="μ: ν¬μ€μΌμ΄") | |
submit_button = gr.Button("μμ΄λμ΄ μμ±νκΈ°") | |
with gr.Column(scale=2): | |
with gr.TabItem("μ°½μμ μΈ λͺ¨λΈ/컨μ /νμ λ³ν μμ΄λμ΄", id="creative_tab"): | |
# Markdown μΆλ ₯ | |
idea_output = gr.Markdown(label="μμ΄λμ΄ κ²°κ³Ό") | |
gr.Examples( | |
examples=[ | |
["μ€λ§νΈν°", "", ""], | |
["컀νΌ", "μ± ", ""], | |
["μλμ°¨", "λ‘λ΄", "μΈκ³΅μ§λ₯"], | |
["μ΄λν", "μ¨μ΄λ¬λΈ", "건κ°"], | |
], | |
inputs=[text_input1, text_input2, text_input3], | |
) | |
# stream=True μ΅μ μ ν΅ν΄ ν¨μκ° yieldνλ λ¬Έμμ΄μ μ€μκ° μΆλ ₯ | |
submit_button.click( | |
fn=process_inputs_stream, | |
inputs=[text_input1, text_input2, text_input3], | |
outputs=idea_output, | |
stream=True | |
) | |
if __name__ == "__main__": | |
demo.launch(debug=True) | |