RozzaCreat commited on
Commit
e7ea66b
·
verified ·
1 Parent(s): 17ccd2e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +215 -222
app.py CHANGED
@@ -1,239 +1,232 @@
1
- from flask import Flask, render_template, request, send_file, redirect, url_for
2
- from PIL import Image, ImageDraw
3
- import tempfile
4
- import os
5
  import requests
6
- import base64
7
- from io import BytesIO
 
 
 
8
 
9
- app = Flask(__name__)
10
-
11
- def generate_passover_coloring_page(age):
12
- """
13
- Generates a Passover-themed coloring page based on age.
 
 
 
14
  """
15
  try:
16
- age = int(float(age))
17
- if not (1 <= age <= 12):
18
- return "Please enter a valid age between 1 and 12.", None
19
- except (ValueError, TypeError):
20
- return "Please enter a valid number for age.", None
21
-
22
- # Define complexity based on age
23
- if 1 <= age <= 3:
24
- complexity = "simple"
25
- theme = "Matzah"
26
- description = "Simple outline of matzah bread for coloring"
27
- elif 4 <= age <= 6:
28
- complexity = "basic"
29
- theme = "Seder Plate"
30
- description = "Basic outline of a Seder plate with clear sections"
31
- elif 7 <= age <= 9:
32
- complexity = "intermediate"
33
- theme = "Exodus Story"
34
- description = "Intermediate level scene from the Exodus story"
35
- else:
36
- complexity = "advanced"
37
- theme = "Passover Symbols"
38
- description = "Advanced design with various Passover symbols"
39
-
40
- # Create a coloring page based on the theme and complexity
41
- img = Image.new('RGB', (600, 500), color='white')
42
- d = ImageDraw.Draw(img)
43
-
44
- # Draw a border
45
- d.rectangle([(20, 20), (580, 480)], outline='black', width=3)
46
-
47
- # Add title and information
48
- d.text((50, 40), f"Passover Coloring Page", fill='black')
49
- d.text((50, 70), f"Theme: {theme}", fill='black')
50
- d.text((50, 100), f"For age: {age} (Complexity: {complexity})", fill='black')
51
- d.text((50, 130), f"{description}", fill='black')
52
-
53
- # Draw content based on the theme
54
- if theme == "Matzah":
55
- # Matzah pattern
56
- d.rectangle([(150, 180), (450, 380)], outline='black', width=2)
57
- for i in range(160, 440, 25):
58
- for j in range(190, 370, 25):
59
- d.ellipse([(i, j), (i+5, j+5)], fill='black')
60
-
61
- elif theme == "Seder Plate":
62
- # Seder plate
63
- d.ellipse([(150, 180), (450, 380)], outline='black', width=2)
64
- # Divide into sections
65
- d.line([(300, 180), (300, 380)], fill='black', width=2)
66
- d.line([(150, 280), (450, 280)], fill='black', width=2)
67
- d.ellipse([(275, 255), (325, 305)], outline='black', width=2)
68
 
69
- elif theme == "Exodus Story":
70
- # Simple boat/basket shape for baby Moses
71
- d.arc([(150, 250), (450, 400)], 0, 180, fill='black', width=2)
72
- d.line([(150, 325), (450, 325)], fill='black', width=2)
73
- # Water waves
74
- for i in range(170, 430, 50):
75
- d.arc([(i, 350), (i+30, 370)], 0, 180, fill='black', width=2)
 
 
 
 
76
 
77
- else: # Passover Symbols
78
- # Draw Star of David
79
- center_x, center_y = 300, 280
80
- radius = 80
81
 
82
- # First triangle
83
- points1 = [
84
- (center_x, center_y - radius),
85
- (center_x + radius * 0.866, center_y + radius * 0.5),
86
- (center_x - radius * 0.866, center_y + radius * 0.5),
87
- (center_x, center_y - radius)
88
- ]
89
 
90
- # Second triangle
91
- points2 = [
92
- (center_x, center_y + radius),
93
- (center_x + radius * 0.866, center_y - radius * 0.5),
94
- (center_x - radius * 0.866, center_y - radius * 0.5),
95
- (center_x, center_y + radius)
96
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
- d.line(points1, fill='black', width=2)
99
- d.line(points2, fill='black', width=2)
100
-
101
- # Convert image to base64 for HTML display
102
- buffered = BytesIO()
103
- img.save(buffered, format="PNG")
104
- img_str = base64.b64encode(buffered.getvalue()).decode()
105
-
106
- # Create the response text
107
- response = {
108
- "age": age,
109
- "theme": theme,
110
- "description": description,
111
- "complexity": complexity,
112
- "image": img_str
113
- }
114
-
115
- return response
116
-
117
- # Home page
118
- @app.route('/', methods=['GET', 'POST'])
119
- def home():
120
- result = None
121
-
122
- if request.method == 'POST':
123
- try:
124
- age = request.form.get('age')
125
- if age:
126
- result = generate_passover_coloring_page(age)
127
- except Exception as e:
128
- return render_template('index.html', error=str(e))
129
-
130
- return render_template('index.html', result=result)
131
-
132
- # Create temporary templates directory and files if they don't exist
133
- def create_templates():
134
- templates_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
135
- if not os.path.exists(templates_dir):
136
- os.makedirs(templates_dir)
137
 
138
- # Create index.html template
139
- index_html = """
140
- <!DOCTYPE html>
141
- <html>
142
- <head>
143
- <title>Passover Coloring Pages Generator</title>
144
- <style>
145
- body {
146
- font-family: Arial, sans-serif;
147
- max-width: 800px;
148
- margin: 0 auto;
149
- padding: 20px;
150
- }
151
- h1 {
152
- color: #2c3e50;
153
- }
154
- .form-container {
155
- margin: 20px 0;
156
- padding: 15px;
157
- border: 1px solid #ddd;
158
- border-radius: 5px;
159
- }
160
- label {
161
- display: block;
162
- margin-bottom: 5px;
163
- font-weight: bold;
164
- }
165
- input, button {
166
- padding: 8px;
167
- margin-bottom: 15px;
168
- }
169
- button {
170
- background-color: #3498db;
171
- color: white;
172
- border: none;
173
- cursor: pointer;
174
- border-radius: 4px;
175
- }
176
- button:hover {
177
- background-color: #2980b9;
178
- }
179
- .result-container {
180
- margin-top: 20px;
181
- padding: 15px;
182
- border: 1px solid #ddd;
183
- border-radius: 5px;
184
- }
185
- .image-container {
186
- margin-top: 20px;
187
- text-align: center;
188
- }
189
- .image-container img {
190
- max-width: 100%;
191
- border: 1px solid #ddd;
192
- }
193
- .error {
194
- color: red;
195
- font-weight: bold;
196
- }
197
- </style>
198
- </head>
199
- <body>
200
- <h1>Passover Coloring Pages Generator</h1>
201
 
202
- <div class="form-container">
203
- <form method="POST">
204
- <label for="age">Child's Age (1-12):</label>
205
- <input type="number" id="age" name="age" min="1" max="12" value="6" required>
206
- <button type="submit">Generate Coloring Page</button>
207
- </form>
208
- </div>
209
 
210
- {% if error %}
211
- <div class="error">
212
- {{ error }}
213
- </div>
214
- {% endif %}
215
 
216
- {% if result %}
217
- <div class="result-container">
218
- <h2>Passover Coloring Page for a {{ result.age }}-year-old</h2>
219
- <p><strong>Theme:</strong> {{ result.theme }}</p>
220
- <p><strong>Description:</strong> {{ result.description }}</p>
221
- <p><strong>Complexity:</strong> {{ result.complexity|capitalize }}</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
 
223
- <div class="image-container">
224
- <img src="data:image/png;base64,{{ result.image }}" alt="Passover Coloring Page">
 
 
 
 
225
  </div>
226
 
227
- <p><em>Print this page for coloring!</em></p>
228
- </div>
229
- {% endif %}
230
- </body>
231
- </html>
232
- """
233
-
234
- with open(os.path.join(templates_dir, 'index.html'), 'w') as f:
235
- f.write(index_html)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
- if __name__ == '__main__':
238
- create_templates()
239
- app.run(debug=True, host='0.0.0.0', port=8080)
 
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
+ from tools.final_answer import FinalAnswerTool
8
+ from Gradio_UI import GradioUI
9
 
10
+ # Below is an example of a tool that does nothing. Amaze us with your creativity!
11
+ @tool
12
+ def create_new_vday_card_tool(theme: str) -> str:
13
+ # it's import to specify the return type
14
+ # Keep this format for the description / args / args description but feel free to modify the tool
15
+ """A tool that generates a custom Valentine's Day card based on a given theme.
16
+ Args:
17
+ theme: A string representing the theme for the Valentine's Day card.
18
  """
19
  try:
20
+ # Import tool from Hub
21
+ '''
22
+ image_generation_tool = Tool.from_space(
23
+ space_id="black-forest-labs/FLUX.1-schnell",
24
+ name="generate-image",
25
+ description="Generate image from prompt"
26
+ )
27
+ '''
28
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
29
+ image = image_generation_tool(theme)
30
+ return final_answer(image)
31
+ except Exception as e:
32
+ return f"Error creating card for theme '{theme}': {str(e)}"
33
+
34
+ # image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
35
+ final_answer = FinalAnswerTool()
36
+
37
+ # Using Mistral-7B-Instruct-v0.1 instead of Qwen2.5-Coder-32B-Instruct
38
+ model = HfApiModel(
39
+ max_tokens=2096,
40
+ temperature=0.7, # Slightly higher temperature for Mistral as it's smaller
41
+ model_id='mistralai/Mistral-7B-Instruct-v0.1', # Changed to Mistral model
42
+ # custom_role_conversions can be adjusted for Mistral
43
+ custom_role_conversions={
44
+ "system": "<s>[INST] <<SYS>>\n{message}\n<</SYS>>\n\n",
45
+ "human": "{message} [/INST]",
46
+ "assistant": "{message} </s><s>[INST] "
47
+ },
48
+ )
49
+
50
+ # Let's add a fix for the Gradio issue by patching the launch method
51
+ def modified_launch():
52
+ try:
53
+ # Original code
54
+ with open("prompts.yaml", 'r') as stream:
55
+ prompt_templates = yaml.safe_load(stream)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ agent = CodeAgent(
58
+ model=model,
59
+ tools=[final_answer, create_new_vday_card_tool], # add your tools here (don't remove final answer)
60
+ max_steps=6,
61
+ verbosity_level=1,
62
+ grammar=None,
63
+ planning_interval=None,
64
+ name=None,
65
+ description=None,
66
+ prompt_templates=prompt_templates
67
+ )
68
 
69
+ # Get the Gradio UI instance but don't launch yet
70
+ ui = GradioUI(agent)
 
 
71
 
72
+ # Patch the launch method to avoid API issues
73
+ original_launch = ui.launch
 
 
 
 
 
74
 
75
+ def patched_launch(*args, **kwargs):
76
+ # Try to patch the problematic API processing in routes.py
77
+ try:
78
+ import types
79
+ from gradio import routes
80
+
81
+ # Create a dummy method that returns an empty dict to avoid the error
82
+ def dummy_api_info(self):
83
+ return {"endpoints": {}, "components": [], "dependencies": []}
84
+
85
+ # Try to patch FastAPI.api_info
86
+ try:
87
+ if hasattr(routes, 'FastAPI'):
88
+ routes.FastAPI.api_info = types.MethodType(dummy_api_info, routes.FastAPI)
89
+ except:
90
+ pass
91
+
92
+ except:
93
+ pass
94
+
95
+ # Call the original launch method
96
+ return original_launch(*args, **kwargs)
97
 
98
+ # Replace the launch method with our patched version
99
+ ui.launch = patched_launch
100
+
101
+ # Now launch the UI with our patched method
102
+ return ui.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
+ except Exception as e:
105
+ # If there's an error with Gradio, fall back to a Flask interface
106
+ print(f"Error with Gradio: {str(e)}")
107
+ print("Falling back to Flask interface...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
+ # Import Flask and create a simple interface
110
+ from flask import Flask, request, render_template_string, jsonify
111
+ import base64
112
+ from PIL import Image
113
+ from io import BytesIO
 
 
114
 
115
+ app = Flask(__name__)
 
 
 
 
116
 
117
+ # Simple HTML template
118
+ html_template = """
119
+ <!DOCTYPE html>
120
+ <html>
121
+ <head>
122
+ <title>Valentine's Day Card Generator</title>
123
+ <style>
124
+ body {
125
+ font-family: Arial, sans-serif;
126
+ max-width: 800px;
127
+ margin: 0 auto;
128
+ padding: 20px;
129
+ }
130
+ h1 {
131
+ color: #e91e63;
132
+ }
133
+ .form-container {
134
+ margin: 20px 0;
135
+ padding: 15px;
136
+ border: 1px solid #ffcccc;
137
+ border-radius: 5px;
138
+ background-color: #fff0f5;
139
+ }
140
+ label {
141
+ display: block;
142
+ margin-bottom: 5px;
143
+ font-weight: bold;
144
+ }
145
+ input {
146
+ width: 100%;
147
+ padding: 8px;
148
+ margin-bottom: 15px;
149
+ border: 1px solid #ccc;
150
+ border-radius: 4px;
151
+ }
152
+ button {
153
+ background-color: #e91e63;
154
+ color: white;
155
+ border: none;
156
+ padding: 10px 15px;
157
+ cursor: pointer;
158
+ border-radius: 4px;
159
+ }
160
+ button:hover {
161
+ background-color: #c2185b;
162
+ }
163
+ .result-container {
164
+ margin-top: 20px;
165
+ text-align: center;
166
+ }
167
+ .card-image {
168
+ max-width: 100%;
169
+ border: 10px solid #fff;
170
+ box-shadow: 0 0 10px rgba(0,0,0,0.2);
171
+ }
172
+ </style>
173
+ </head>
174
+ <body>
175
+ <h1>Valentine's Day Card Generator</h1>
176
+ <p>Enter a theme to generate a custom Valentine's Day card.</p>
177
 
178
+ <div class="form-container">
179
+ <form method="POST">
180
+ <label for="theme">Card Theme:</label>
181
+ <input type="text" id="theme" name="theme" placeholder="e.g., romantic sunset, cute animals, etc." required>
182
+ <button type="submit">Generate Card</button>
183
+ </form>
184
  </div>
185
 
186
+ {% if error %}
187
+ <div style="color: red; margin-top: 20px;">
188
+ <p>{{ error }}</p>
189
+ </div>
190
+ {% endif %}
191
+
192
+ {% if image_data %}
193
+ <div class="result-container">
194
+ <h2>Your Valentine's Day Card</h2>
195
+ <p>Theme: {{ theme }}</p>
196
+ <img src="data:image/png;base64,{{ image_data }}" alt="Valentine's Day Card" class="card-image">
197
+ </div>
198
+ {% endif %}
199
+ </body>
200
+ </html>
201
+ """
202
+
203
+ @app.route('/', methods=['GET', 'POST'])
204
+ def home():
205
+ if request.method == 'POST':
206
+ theme = request.form.get('theme', '')
207
+ if theme:
208
+ try:
209
+ # Add Valentine's context to the theme
210
+ valentine_theme = f"Valentine's Day card with theme: {theme}, romantic, love, hearts"
211
+
212
+ # Use the agent to generate the card
213
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
214
+ image = image_generation_tool(valentine_theme)
215
+
216
+ # Convert PIL Image to base64 string
217
+ buffered = BytesIO()
218
+ image.save(buffered, format="PNG")
219
+ img_str = base64.b64encode(buffered.getvalue()).decode()
220
+
221
+ return render_template_string(html_template, image_data=img_str, theme=theme)
222
+ except Exception as e:
223
+ return render_template_string(html_template, error=f"Error: {str(e)}")
224
+
225
+ return render_template_string(html_template)
226
+
227
+ # Run the Flask app
228
+ return app.run(debug=True, host='0.0.0.0', port=8080)
229
 
230
+ # Run the modified launch function
231
+ if __name__ == "__main__":
232
+ modified_launch()