Spaces:
Runtime error
Runtime error
File size: 10,742 Bytes
eb8806e b9f4ccd eb8806e b9f4ccd eb8806e edcf253 b9f4ccd edcf253 b9f4ccd fd863f3 b9f4ccd fd863f3 b9f4ccd edcf253 b9f4ccd 9cb71c2 417aa68 b9f4ccd bcd9bb8 b9f4ccd eb8806e b9f4ccd edcf253 bcd9bb8 b9f4ccd bcd9bb8 b9f4ccd edcf253 bcd9bb8 b9f4ccd edcf253 bcd9bb8 b9f4ccd edcf253 bcd9bb8 b9f4ccd edcf253 bcd9bb8 b9f4ccd bcd9bb8 b9f4ccd edcf253 bcd9bb8 b9f4ccd bcd9bb8 b9f4ccd bcd9bb8 b9f4ccd bcd9bb8 b9f4ccd bcd9bb8 b9f4ccd edcf253 b9f4ccd bcd9bb8 b9f4ccd edcf253 bcd9bb8 edcf253 bcd9bb8 edcf253 b9f4ccd edcf253 b9f4ccd edcf253 bcd9bb8 edcf253 b9f4ccd edcf253 bcd9bb8 edcf253 b9f4ccd edcf253 b9f4ccd bcd9bb8 edcf253 bcd9bb8 edcf253 b9f4ccd edcf253 bcd9bb8 b9f4ccd bcd9bb8 b9f4ccd bcd9bb8 b9f4ccd bcd9bb8 b9f4ccd bcd9bb8 edcf253 bcd9bb8 5a1d31c b9f4ccd eb8806e b9f4ccd edcf253 eb8806e bcd9bb8 |
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 |
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)
|