Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,258 +1,257 @@
|
|
| 1 |
-
from smolagents import CodeAgent, HfApiModel, tool
|
|
|
|
|
|
|
|
|
|
| 2 |
import yaml
|
| 3 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
from tools.final_answer import FinalAnswerTool
|
| 5 |
from Gradio_UI import GradioUI
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
@tool
|
| 8 |
-
def
|
| 9 |
-
"""
|
| 10 |
-
|
| 11 |
Args:
|
| 12 |
-
|
| 13 |
-
risk_profile: Risk profile (low, medium, high)
|
| 14 |
-
age: Age of the investor
|
| 15 |
-
|
| 16 |
Returns:
|
| 17 |
-
|
| 18 |
"""
|
| 19 |
-
if
|
| 20 |
-
return "Error:
|
| 21 |
-
|
| 22 |
-
if age <= 0 or age > 120:
|
| 23 |
-
return "Error: Please provide a valid age."
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
|
| 30 |
-
return "Error: Risk profile must be 'low', 'medium', or 'high'."
|
| 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 |
-
# Basic rule: 120 - age = % stocks (for medium risk)
|
| 57 |
-
base_stocks = max(0, min(100, 120 - age))
|
| 58 |
-
|
| 59 |
-
if risk == "low":
|
| 60 |
-
stocks = max(0, base_stocks - 20)
|
| 61 |
-
elif risk == "high":
|
| 62 |
-
stocks = min(100, base_stocks + 20)
|
| 63 |
-
else: # medium risk
|
| 64 |
-
stocks = base_stocks
|
| 65 |
-
|
| 66 |
-
bonds = min(100 - stocks, 80)
|
| 67 |
-
cash = 100 - stocks - bonds
|
| 68 |
-
|
| 69 |
-
return {
|
| 70 |
-
"stocks": stocks,
|
| 71 |
-
"bonds": bonds,
|
| 72 |
-
"cash": cash
|
| 73 |
-
}
|
| 74 |
-
|
| 75 |
-
# Get asset allocation
|
| 76 |
-
allocation = get_allocation(age, risk_profile)
|
| 77 |
-
|
| 78 |
-
# Find suitable funds based on available amount and allocation
|
| 79 |
-
suitable_funds = []
|
| 80 |
-
funds_for_profile = israeli_funds[risk_profile]
|
| 81 |
-
|
| 82 |
-
# Distribute amount by asset class
|
| 83 |
-
stock_amount = amount * allocation["stocks"] / 100
|
| 84 |
-
bond_amount = amount * allocation["bonds"] / 100
|
| 85 |
-
cash_amount = amount * allocation["cash"] / 100
|
| 86 |
-
|
| 87 |
-
# Fund recommendations
|
| 88 |
-
stock_funds = [f for f in funds_for_profile if f["type"] in ["Index", "Technology", "US", "International", "Sector"]]
|
| 89 |
-
bond_funds = [f for f in funds_for_profile if f["type"] in ["Bonds", "Gov Bonds", "Corp Bonds"]]
|
| 90 |
-
cash_funds = [f for f in funds_for_profile if f["type"] in ["Deposits", "Currency"]]
|
| 91 |
-
|
| 92 |
-
# Build recommendations
|
| 93 |
-
recommendations = []
|
| 94 |
-
|
| 95 |
-
if stock_amount >= 1000 and stock_funds:
|
| 96 |
-
for fund in stock_funds:
|
| 97 |
-
if fund["min_investment"] <= stock_amount:
|
| 98 |
-
amount_to_invest = min(stock_amount * 0.8, stock_amount)
|
| 99 |
-
recommendations.append({
|
| 100 |
-
"fund": fund,
|
| 101 |
-
"amount": math.floor(amount_to_invest / 100) * 100,
|
| 102 |
-
"asset_class": "Stocks"
|
| 103 |
-
})
|
| 104 |
-
break
|
| 105 |
-
|
| 106 |
-
if bond_amount >= 1000 and bond_funds:
|
| 107 |
-
for fund in bond_funds:
|
| 108 |
-
if fund["min_investment"] <= bond_amount:
|
| 109 |
-
amount_to_invest = min(bond_amount * 0.8, bond_amount)
|
| 110 |
-
recommendations.append({
|
| 111 |
-
"fund": fund,
|
| 112 |
-
"amount": math.floor(amount_to_invest / 100) * 100,
|
| 113 |
-
"asset_class": "Bonds"
|
| 114 |
-
})
|
| 115 |
-
break
|
| 116 |
-
|
| 117 |
-
if cash_amount >= 500 and cash_funds:
|
| 118 |
-
for fund in cash_funds:
|
| 119 |
-
if fund["min_investment"] <= cash_amount:
|
| 120 |
-
amount_to_invest = min(cash_amount * 0.9, cash_amount)
|
| 121 |
-
recommendations.append({
|
| 122 |
-
"fund": fund,
|
| 123 |
-
"amount": math.floor(amount_to_invest / 100) * 100,
|
| 124 |
-
"asset_class": "Cash"
|
| 125 |
-
})
|
| 126 |
-
break
|
| 127 |
|
| 128 |
-
#
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
response += f"**{fund['name']}** ({fund['ticker']})\n"
|
| 149 |
-
response += f"- Type: {fund['type']} ({rec['asset_class']})\n"
|
| 150 |
-
response += f"- Risk: {fund['risk']}\n"
|
| 151 |
-
response += f"- Recommended amount: {amount_to_invest:,} ₪\n"
|
| 152 |
-
response += f"- Description: {fund['description']}\n\n"
|
| 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 |
-
"react-system": """You are
|
| 180 |
You have access to the following tools:
|
| 181 |
|
| 182 |
{tools_string}
|
| 183 |
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
2. The user's risk profile (low, medium, or high)
|
| 187 |
-
3. The user's age
|
| 188 |
|
| 189 |
-
|
|
|
|
| 190 |
|
| 191 |
To use a tool, output an action in this format:
|
| 192 |
```py
|
| 193 |
action = tool_name(arg1=value1, arg2=value2, ...)
|
| 194 |
```
|
| 195 |
|
| 196 |
-
Always use Python syntax for calling tools. After using a tool, analyze the result to determine what to do next. Use final_answer to return your
|
| 197 |
""",
|
| 198 |
"react-human": "{input_string}",
|
| 199 |
"react-assistant": "{agent_response}",
|
| 200 |
}
|
| 201 |
|
| 202 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
try:
|
| 204 |
with open("prompts.yaml", 'r') as stream:
|
| 205 |
prompt_templates = yaml.safe_load(stream)
|
| 206 |
-
|
|
|
|
| 207 |
except:
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
agent = CodeAgent(
|
| 212 |
model=model,
|
| 213 |
-
tools=[final_answer,
|
| 214 |
-
max_steps=
|
| 215 |
verbosity_level=1,
|
| 216 |
prompt_templates=prompt_templates
|
| 217 |
)
|
| 218 |
|
| 219 |
-
#
|
| 220 |
-
|
| 221 |
-
def launch(self, **kwargs):
|
| 222 |
-
import gradio as gr
|
| 223 |
-
|
| 224 |
-
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 225 |
-
gr.Markdown("# Investment Advisor for the Israeli Market")
|
| 226 |
-
gr.Markdown("Get personalized investment recommendations based on your profile")
|
| 227 |
-
|
| 228 |
-
with gr.Row():
|
| 229 |
-
with gr.Column():
|
| 230 |
-
amount_input = gr.Number(label="Amount to invest (in shekels)", minimum=100)
|
| 231 |
-
risk_input = gr.Radio(["Low", "Medium", "High"], label="Risk Profile")
|
| 232 |
-
age_input = gr.Slider(minimum=18, maximum=100, step=1, label="Your Age")
|
| 233 |
-
submit_btn = gr.Button("Get Recommendations", variant="primary")
|
| 234 |
-
|
| 235 |
-
with gr.Row():
|
| 236 |
-
with gr.Column():
|
| 237 |
-
recommendation_output = gr.Markdown(label="Investment Recommendations")
|
| 238 |
-
|
| 239 |
-
def get_recommendations(amount, risk, age):
|
| 240 |
-
if not amount or amount < 100:
|
| 241 |
-
return "Please enter an amount of at least 100 shekels."
|
| 242 |
-
if not risk:
|
| 243 |
-
return "Please select a risk profile."
|
| 244 |
-
if not age or age < 18:
|
| 245 |
-
return "Please provide a valid age (18 years or older)."
|
| 246 |
-
|
| 247 |
-
try:
|
| 248 |
-
recommendations = investment_advisor(int(amount), risk.lower(), int(age))
|
| 249 |
-
return recommendations
|
| 250 |
-
except Exception as e:
|
| 251 |
-
return f"Error generating recommendations: {str(e)}"
|
| 252 |
-
|
| 253 |
-
submit_btn.click(get_recommendations, inputs=[amount_input, risk_input, age_input], outputs=recommendation_output)
|
| 254 |
-
|
| 255 |
-
demo.launch(**kwargs)
|
| 256 |
-
|
| 257 |
-
# Launch the interface
|
| 258 |
-
InvestmentAdvisorUI(agent).launch()
|
|
|
|
| 1 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
|
| 2 |
+
import datetime
|
| 3 |
+
import requests
|
| 4 |
+
import pytz
|
| 5 |
import yaml
|
| 6 |
+
import re
|
| 7 |
+
import tempfile
|
| 8 |
+
import os
|
| 9 |
+
import time
|
| 10 |
+
import shutil
|
| 11 |
+
from PIL import Image
|
| 12 |
from tools.final_answer import FinalAnswerTool
|
| 13 |
from Gradio_UI import GradioUI
|
| 14 |
|
| 15 |
+
# Создаем постоянную директорию для хранения изображений
|
| 16 |
+
IMAGES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "coloring_images")
|
| 17 |
+
os.makedirs(IMAGES_DIR, exist_ok=True)
|
| 18 |
+
|
| 19 |
@tool
|
| 20 |
+
def generate_passover_coloring_pages(age: int) -> str:
|
| 21 |
+
"""
|
| 22 |
+
Generates Jewish Passover/Pesach-themed coloring pages based on a child's age.
|
| 23 |
Args:
|
| 24 |
+
age (int): The age of the child (1-12).
|
|
|
|
|
|
|
|
|
|
| 25 |
Returns:
|
| 26 |
+
str: A list of suggested Passover-themed coloring pages.
|
| 27 |
"""
|
| 28 |
+
if not isinstance(age, int) or not (1 <= age <= 12):
|
| 29 |
+
return "Error: Please provide a valid age between 1 and 12."
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
complexity_levels = {
|
| 32 |
+
(1, 3): "simple",
|
| 33 |
+
(4, 6): "basic",
|
| 34 |
+
(7, 9): "intermediate",
|
| 35 |
+
(10, 12): "advanced"
|
| 36 |
+
}
|
| 37 |
|
| 38 |
+
complexity = next(value for (low, high), value in complexity_levels.items() if low <= age <= high)
|
|
|
|
| 39 |
|
| 40 |
+
# Enhanced prompts specifically for Jewish Passover/Pesach themes
|
| 41 |
+
passover_pages = {
|
| 42 |
+
"simple": [
|
| 43 |
+
"Line drawing of matzah for Jewish Passover coloring page, thick black outlines, white background, child-friendly",
|
| 44 |
+
"Simple black outline of a Seder plate with spaces for the six items (karpas, charoset, maror, zeroa, beitzah, chazeret), coloring book style, thick lines",
|
| 45 |
+
"Simple outline drawing of the Afikoman (broken piece of matzah) hidden in fabric, black and white for coloring",
|
| 46 |
+
"Simple outline of a Kiddush cup for Passover seder, black and white for coloring"
|
| 47 |
+
],
|
| 48 |
+
"basic": [
|
| 49 |
+
"Black and white outline of Moses parting the Red Sea, traditional Jewish Pesach story, no Christian symbols, coloring book style",
|
| 50 |
+
"Outline drawing of the Ten Plagues (blood, frogs, lice, wild animals, cattle disease, boils, hail, locusts, darkness, death of firstborn) in separated panels, Jewish Passover theme",
|
| 51 |
+
"Haggadah Four Questions illustrations in Hebrew and English for coloring, Jewish Passover tradition",
|
| 52 |
+
"Afikoman hunt maze with matzah at the center, black and white outline for Jewish Passover coloring"
|
| 53 |
],
|
| 54 |
+
"intermediate": [
|
| 55 |
+
"Detailed black and white outline of a traditional Jewish Seder table with all symbolic foods and Haggadah, no crosses or Christian symbols",
|
| 56 |
+
"Hebrew letter decorations spelling 'Pesach' (פסח) for coloring, traditional Jewish style",
|
| 57 |
+
"Outline drawing of ancient Israelites leaving Egypt, Jewish Passover story, historically accurate depiction",
|
| 58 |
+
"Black and white outline of the Four Sons from the Haggadah, traditional Jewish Passover story characters"
|
| 59 |
],
|
| 60 |
+
"advanced": [
|
| 61 |
+
"Intricate Haggadah page illustrations in black and white, showing the order of the Seder, traditional Jewish style",
|
| 62 |
+
"Detailed scene of Miriam and women celebrating after crossing the Red Sea with tambourines, Jewish Passover story",
|
| 63 |
+
"Intricate Hebrew calligraphy spelling 'Next year in Jerusalem' (לשנה הבאה בירושלים) for coloring",
|
| 64 |
+
"Detailed symbolic Jewish Passover illustrations showing the journey from slavery to freedom, with proper Jewish symbols only"
|
| 65 |
]
|
| 66 |
}
|
| 67 |
|
| 68 |
+
selected_pages = passover_pages[complexity]
|
| 69 |
+
descriptions = [page.split(',')[0] if ',' in page else page for page in selected_pages]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
# Очищаем директорию от старых изображений
|
| 72 |
+
for file in os.listdir(IMAGES_DIR):
|
| 73 |
+
if file.endswith(".png"):
|
| 74 |
+
file_path = os.path.join(IMAGES_DIR, file)
|
| 75 |
+
try:
|
| 76 |
+
os.remove(file_path)
|
| 77 |
+
except:
|
| 78 |
+
pass
|
| 79 |
|
| 80 |
+
# Создаем заглушки для изображений на случай сбоя в генерации
|
| 81 |
+
def create_placeholder_image(description, index):
|
| 82 |
+
img = Image.new('RGB', (800, 600), color='white')
|
| 83 |
+
return img
|
| 84 |
|
| 85 |
+
# Попытка сгенерировать изображения
|
| 86 |
+
try:
|
| 87 |
+
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 88 |
|
| 89 |
+
# Используем улучшенные подсказки для раскрасок
|
| 90 |
+
enhanced_prompts = []
|
| 91 |
+
for page in selected_pages:
|
| 92 |
+
enhanced_prompts.append(f"{page}, Jewish traditional Passover symbols only, no Christian imagery, suitable for printing as a coloring page")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
+
# Сохраняем пути к изображениям
|
| 95 |
+
image_paths = []
|
| 96 |
+
|
| 97 |
+
# Генерируем и сохраняем изображения
|
| 98 |
+
for i, prompt in enumerate(enhanced_prompts):
|
| 99 |
+
try:
|
| 100 |
+
img = image_generation_tool(prompt)
|
| 101 |
+
# Сохраняем в постоянную директорию с уникальным именем
|
| 102 |
+
timestamp = int(time.time())
|
| 103 |
+
img_path = os.path.join(IMAGES_DIR, f"passover_{age}_{i}_{timestamp}.png")
|
| 104 |
+
img.save(img_path)
|
| 105 |
+
image_paths.append(img_path)
|
| 106 |
+
except Exception as e:
|
| 107 |
+
# При ошибке создаем заглушку
|
| 108 |
+
placeholder = create_placeholder_image(descriptions[i], i)
|
| 109 |
+
img_path = os.path.join(IMAGES_DIR, f"passover_{age}_{i}_placeholder.png")
|
| 110 |
+
placeholder.save(img_path)
|
| 111 |
+
image_paths.append(img_path)
|
| 112 |
+
print(f"Error generating image {i}: {str(e)}")
|
| 113 |
+
|
| 114 |
+
# Создаем форматированный ответ с описаниями
|
| 115 |
+
response = f"## Jewish Passover (Pesach) Coloring Pages for a {age}-year-old:\n\n"
|
| 116 |
+
response += "\n".join([f"- {desc}" for desc in descriptions])
|
| 117 |
+
|
| 118 |
+
# Сохраняем пути к изображениям в ответе в специальном формате
|
| 119 |
+
image_paths_str = "||".join(image_paths)
|
| 120 |
+
return f"{response}\n\nIMAGE_PATHS:{image_paths_str}"
|
| 121 |
|
| 122 |
+
except Exception as e:
|
| 123 |
+
# Если генерация изображений полностью не удалась, вернуть только текстовое описание
|
| 124 |
+
response = f"## Jewish Passover (Pesach) Coloring Pages for a {age}-year-old:\n\n"
|
| 125 |
+
response += "\n".join([f"- {desc}" for desc in descriptions])
|
| 126 |
+
|
| 127 |
+
# Создаем заглушки для каждого описания
|
| 128 |
+
image_paths = []
|
| 129 |
+
for i, desc in enumerate(descriptions):
|
| 130 |
+
placeholder = create_placeholder_image(desc, i)
|
| 131 |
+
img_path = os.path.join(IMAGES_DIR, f"passover_{age}_{i}_placeholder.png")
|
| 132 |
+
placeholder.save(img_path)
|
| 133 |
+
image_paths.append(img_path)
|
| 134 |
+
|
| 135 |
+
# Сохраняем пути к заглушкам
|
| 136 |
+
image_paths_str = "||".join(image_paths)
|
| 137 |
+
return f"{response}\n\nIMAGE_PATHS:{image_paths_str}"
|
| 138 |
|
| 139 |
+
# Custom UI wrapper to handle image display
|
| 140 |
+
class CustomGradioUI(GradioUI):
|
| 141 |
+
def __init__(self, agent):
|
| 142 |
+
super().__init__(agent)
|
| 143 |
+
|
| 144 |
+
def launch(self, **kwargs):
|
| 145 |
+
import gradio as gr
|
| 146 |
+
|
| 147 |
+
# Create a custom interface that can display images
|
| 148 |
+
with gr.Blocks() as demo:
|
| 149 |
+
with gr.Row():
|
| 150 |
+
with gr.Column(scale=1):
|
| 151 |
+
gr.Markdown("# Jewish Passover (Pesach) Coloring Pages Generator")
|
| 152 |
+
gr.Markdown("Generate traditional Jewish Passover coloring pages for children")
|
| 153 |
+
|
| 154 |
+
with gr.Row():
|
| 155 |
+
with gr.Column(scale=1):
|
| 156 |
+
input_box = gr.Textbox(label="Enter child's age (1-12)")
|
| 157 |
+
submit_btn = gr.Button("Generate Coloring Pages")
|
| 158 |
+
|
| 159 |
+
with gr.Row():
|
| 160 |
+
with gr.Column(scale=1):
|
| 161 |
+
output_text = gr.Markdown(label="Generated Pages")
|
| 162 |
+
|
| 163 |
+
with gr.Row():
|
| 164 |
+
gallery = gr.Gallery(label="Jewish Passover Coloring Pages", show_label=True)
|
| 165 |
+
|
| 166 |
+
def process_input(input_text):
|
| 167 |
+
try:
|
| 168 |
+
# Try to convert the input to an integer
|
| 169 |
+
age = int(input_text.strip())
|
| 170 |
+
if not (1 <= age <= 12):
|
| 171 |
+
return "Please enter a valid age between 1 and 12.", []
|
| 172 |
+
|
| 173 |
+
# Generate the coloring pages
|
| 174 |
+
result = generate_passover_coloring_pages(age)
|
| 175 |
+
|
| 176 |
+
# Extract image paths from the result
|
| 177 |
+
image_paths = []
|
| 178 |
+
if "IMAGE_PATHS:" in result:
|
| 179 |
+
paths_part = result.split("IMAGE_PATHS:")[1]
|
| 180 |
+
image_paths = paths_part.split("||")
|
| 181 |
+
# Удаляем маркер путей из результата
|
| 182 |
+
result = result.split("\n\nIMAGE_PATHS:")[0]
|
| 183 |
+
|
| 184 |
+
# Если нет путей к изображениям, ищем в директории
|
| 185 |
+
if not image_paths:
|
| 186 |
+
for file in os.listdir(IMAGES_DIR):
|
| 187 |
+
if file.endswith('.png') and f"passover_{age}_" in file:
|
| 188 |
+
image_paths.append(os.path.join(IMAGES_DIR, file))
|
| 189 |
+
|
| 190 |
+
# Проверяем, что пути ведут к реальным файлам
|
| 191 |
+
valid_image_paths = [path for path in image_paths if os.path.exists(path)]
|
| 192 |
+
|
| 193 |
+
# Return the result and image paths
|
| 194 |
+
return result, valid_image_paths
|
| 195 |
+
except ValueError:
|
| 196 |
+
return "Please enter a valid number for the child's age.", []
|
| 197 |
+
except Exception as e:
|
| 198 |
+
return f"Error: {str(e)}", []
|
| 199 |
+
|
| 200 |
+
submit_btn.click(process_input, inputs=input_box, outputs=[output_text, gallery])
|
| 201 |
+
|
| 202 |
+
# Launch the demo
|
| 203 |
+
demo.launch(**kwargs)
|
| 204 |
|
| 205 |
+
# Modified prompt templates to handle simple age input
|
| 206 |
+
custom_prompt_templates = {
|
| 207 |
+
"react-system": """You are a helpful agent that helps children learn about Jewish Passover/Pesach through coloring pages.
|
| 208 |
You have access to the following tools:
|
| 209 |
|
| 210 |
{tools_string}
|
| 211 |
|
| 212 |
+
When a user enters a number between 1 and 12, interpret it as the age of a child and generate Jewish Passover coloring pages suitable for that age using the generate_passover_coloring_pages tool.
|
| 213 |
+
If you're asked to generate coloring pages or if the input is just a number, assume the user wants Jewish Passover coloring pages for a child of that age.
|
|
|
|
|
|
|
| 214 |
|
| 215 |
+
Important: Only generate authentic Jewish Passover (Pesach) symbols and imagery - including matzah, seder plate, haggadah, afikoman, four cups of wine, the exodus story, etc.
|
| 216 |
+
Do NOT include any Christian symbols or imagery like crosses, Jesus, or other non-Jewish religious elements.
|
| 217 |
|
| 218 |
To use a tool, output an action in this format:
|
| 219 |
```py
|
| 220 |
action = tool_name(arg1=value1, arg2=value2, ...)
|
| 221 |
```
|
| 222 |
|
| 223 |
+
Always use Python syntax for calling tools. After using a tool, analyze the result to determine what to do next. Use final_answer to return your answer when complete.
|
| 224 |
""",
|
| 225 |
"react-human": "{input_string}",
|
| 226 |
"react-assistant": "{agent_response}",
|
| 227 |
}
|
| 228 |
|
| 229 |
+
# Setup agent
|
| 230 |
+
final_answer = FinalAnswerTool()
|
| 231 |
+
|
| 232 |
+
model = HfApiModel(
|
| 233 |
+
max_tokens=2096,
|
| 234 |
+
temperature=0.5,
|
| 235 |
+
model_id='Qwen/Qwen2.5-Coder-32B-Instruct'
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
# Check if custom prompts should be used or merged with existing ones
|
| 239 |
try:
|
| 240 |
with open("prompts.yaml", 'r') as stream:
|
| 241 |
prompt_templates = yaml.safe_load(stream)
|
| 242 |
+
# Merge the templates, giving priority to our custom ones
|
| 243 |
+
prompt_templates.update(custom_prompt_templates)
|
| 244 |
except:
|
| 245 |
+
# If file doesn't exist or has issues, use our custom templates
|
| 246 |
+
prompt_templates = custom_prompt_templates
|
| 247 |
+
|
| 248 |
agent = CodeAgent(
|
| 249 |
model=model,
|
| 250 |
+
tools=[final_answer, generate_passover_coloring_pages],
|
| 251 |
+
max_steps=6,
|
| 252 |
verbosity_level=1,
|
| 253 |
prompt_templates=prompt_templates
|
| 254 |
)
|
| 255 |
|
| 256 |
+
# Launch custom Gradio UI
|
| 257 |
+
CustomGradioUI(agent).launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|