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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +155 -197
app.py CHANGED
@@ -1,44 +1,16 @@
1
- import gradio as gr
2
  from PIL import Image, ImageDraw
3
  import tempfile
4
  import os
5
  import requests
6
- import json
 
7
 
8
- # Use Mistral-7B-Instruct model from Hugging Face
9
- def generate_mistral_response(prompt):
10
- """
11
- Uses the Mistral-7B-Instruct-v0.1 model to generate a response.
12
- This model should be accessible without a subscription on Hugging Face.
13
- """
14
- API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.1"
15
-
16
- # Format the prompt according to Mistral's expected format
17
- formatted_prompt = f"""<s>[INST] {prompt} [/INST]"""
18
-
19
- payload = {
20
- "inputs": formatted_prompt,
21
- "parameters": {
22
- "max_new_tokens": 500,
23
- "temperature": 0.7,
24
- "top_p": 0.95,
25
- "do_sample": True
26
- }
27
- }
28
-
29
- # Make the API call
30
- try:
31
- response = requests.post(API_URL, json=payload)
32
- if response.status_code == 200:
33
- return response.json()[0]["generated_text"].split("[/INST]")[1].strip()
34
- else:
35
- return f"Error: {response.status_code}, {response.text}"
36
- except Exception as e:
37
- return f"Error connecting to Mistral API: {str(e)}"
38
 
39
  def generate_passover_coloring_page(age):
40
  """
41
- Generates a Passover-themed coloring page based on age using Mistral model.
42
  """
43
  try:
44
  age = int(float(age))
@@ -47,64 +19,23 @@ def generate_passover_coloring_page(age):
47
  except (ValueError, TypeError):
48
  return "Please enter a valid number for age.", None
49
 
50
- # Get coloring page ideas from Mistral
51
- prompt = f"""I need to create a Passover-themed coloring page for a {age}-year-old child.
52
-
53
- Based on this age, provide:
54
- 1. A suitable Passover theme for the coloring page
55
- 2. A brief description (1-2 sentences) of what elements should be included
56
- 3. The appropriate complexity level (simple, basic, intermediate, or advanced)
57
-
58
- Keep your response concise and structured. Here's an example format:
59
- Theme: [theme name]
60
- Description: [brief description]
61
- Complexity: [complexity level]"""
62
-
63
- try:
64
- # Get response from Mistral
65
- model_response = generate_mistral_response(prompt)
66
-
67
- # Parse the response to extract information
68
- theme = "Passover"
69
- description = "Passover symbols and elements"
70
  complexity = "simple"
71
-
72
- # Try to extract the theme, description, and complexity from the response
73
- if "Theme:" in model_response:
74
- theme = model_response.split("Theme:")[1].split("\n")[0].strip()
75
- if "Description:" in model_response:
76
- description = model_response.split("Description:")[1].split("\n")[0].strip()
77
- if "Complexity:" in model_response:
78
- complexity = model_response.split("Complexity:")[1].split("\n")[0].strip().lower()
79
-
80
- # Ensure complexity is valid
81
- if complexity not in ["simple", "basic", "intermediate", "advanced"]:
82
- if age <= 3:
83
- complexity = "simple"
84
- elif age <= 6:
85
- complexity = "basic"
86
- elif age <= 9:
87
- complexity = "intermediate"
88
- else:
89
- complexity = "advanced"
90
- except Exception as e:
91
- # Fallback if parsing fails
92
- if age <= 3:
93
- theme = "Matzah"
94
- description = "Simple outline of matzah bread for coloring"
95
- complexity = "simple"
96
- elif age <= 6:
97
- theme = "Seder Plate"
98
- description = "Basic outline of a Seder plate with clear sections"
99
- complexity = "basic"
100
- elif age <= 9:
101
- theme = "Exodus Story"
102
- description = "Intermediate level scene from the Exodus story"
103
- complexity = "intermediate"
104
- else:
105
- theme = "Passover Symbols"
106
- description = "Advanced design with various Passover symbols"
107
- complexity = "advanced"
108
 
109
  # Create a coloring page based on the theme and complexity
110
  img = Image.new('RGB', (600, 500), color='white')
@@ -120,14 +51,14 @@ Complexity: [complexity level]"""
120
  d.text((50, 130), f"{description}", fill='black')
121
 
122
  # Draw content based on the theme
123
- if "Matzah" in theme:
124
  # Matzah pattern
125
  d.rectangle([(150, 180), (450, 380)], outline='black', width=2)
126
  for i in range(160, 440, 25):
127
  for j in range(190, 370, 25):
128
  d.ellipse([(i, j), (i+5, j+5)], fill='black')
129
 
130
- elif "Seder" in theme or "Plate" in theme:
131
  # Seder plate
132
  d.ellipse([(150, 180), (450, 380)], outline='black', width=2)
133
  # Divide into sections
@@ -135,30 +66,15 @@ Complexity: [complexity level]"""
135
  d.line([(150, 280), (450, 280)], fill='black', width=2)
136
  d.ellipse([(275, 255), (325, 305)], outline='black', width=2)
137
 
138
- elif "Moses" in theme or "Exodus" in theme:
139
  # Simple boat/basket shape for baby Moses
140
  d.arc([(150, 250), (450, 400)], 0, 180, fill='black', width=2)
141
  d.line([(150, 325), (450, 325)], fill='black', width=2)
142
  # Water waves
143
  for i in range(170, 430, 50):
144
  d.arc([(i, 350), (i+30, 370)], 0, 180, fill='black', width=2)
145
-
146
- elif "Plague" in theme or "Frog" in theme:
147
- # Frog outline (representing the plagues)
148
- # Body
149
- d.ellipse([(250, 230), (350, 300)], outline='black', width=2)
150
- # Head
151
- d.ellipse([(275, 180), (325, 230)], outline='black', width=2)
152
- # Eyes
153
- d.ellipse([(280, 190), (290, 200)], outline='black', width=2)
154
- d.ellipse([(310, 190), (320, 200)], outline='black', width=2)
155
- # Legs
156
- d.line([(250, 265), (200, 290)], fill='black', width=2)
157
- d.line([(350, 265), (400, 290)], fill='black', width=2)
158
- d.line([(270, 300), (240, 350)], fill='black', width=2)
159
- d.line([(330, 300), (360, 350)], fill='black', width=2)
160
 
161
- elif "Symbol" in theme or "Hebrew" in theme:
162
  # Draw Star of David
163
  center_x, center_y = 300, 280
164
  radius = 80
@@ -181,101 +97,143 @@ Complexity: [complexity level]"""
181
 
182
  d.line(points1, fill='black', width=2)
183
  d.line(points2, fill='black', width=2)
184
-
185
- else:
186
- # Default: Simple Passover scene with pyramids and figures
187
- # Pyramids
188
- d.polygon([(150, 380), (250, 200), (350, 380)], outline='black', width=2)
189
- d.polygon([(300, 380), (400, 220), (500, 380)], outline='black', width=2)
190
-
191
- # Figures (simple stick figures)
192
- for i in range(180, 500, 80):
193
- # Body
194
- d.line([(i, 350), (i, 320)], fill='black', width=2)
195
- # Head
196
- d.ellipse([(i-5, 310), (i+5, 320)], outline='black', width=2)
197
- # Arms
198
- d.line([(i-10, 335), (i+10, 335)], fill='black', width=2)
199
- # Legs
200
- d.line([(i, 350), (i-7, 370)], fill='black', width=2)
201
- d.line([(i, 350), (i+7, 370)], fill='black', width=2)
202
 
203
- # Save to a temporary file
204
- with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as temp_file:
205
- temp_path = temp_file.name
206
- img.save(temp_path)
 
 
 
 
 
 
 
 
 
207
 
208
- # Create the response text with the model's insights
209
- response = f"## Passover Coloring Page for a {age}-year-old\n\n"
210
- response += f"**Theme**: {theme}\n\n"
211
- response += f"**Description**: {description}\n\n"
212
- response += f"**Complexity**: {complexity.capitalize()}\n\n"
 
213
 
214
- # Add Mistral's full response as additional context
215
- response += "---\n\n"
216
- response += "### Mistral AI's Suggestion:\n\n"
217
- response += f"{model_response}"
 
 
 
218
 
219
- return response, temp_path
220
 
221
- # Create a simple UI that avoids the API issue
222
- with gr.Blocks() as demo:
223
- gr.Markdown("# Passover Coloring Pages Generator")
224
- gr.Markdown("### Powered by Mistral-7B-Instruct")
225
-
226
- with gr.Row():
227
- with gr.Column():
228
- age_input = gr.Slider(
229
- minimum=1,
230
- maximum=12,
231
- step=1,
232
- value=6,
233
- label="Child's Age"
234
- )
235
- generate_btn = gr.Button("Generate Coloring Page")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
- with gr.Row():
238
- with gr.Column():
239
- output_text = gr.Markdown()
 
 
 
 
240
 
241
- with gr.Row():
242
- output_image = gr.Image(label="Coloring Page")
243
-
244
- generate_btn.click(
245
- generate_passover_coloring_page,
246
- inputs=age_input,
247
- outputs=[output_text, output_image]
248
- )
249
-
250
- # Launch with the patched method to avoid API issues
251
- if __name__ == "__main__":
252
- # Override the app.get_blocks().get_api_info() method that's causing the error
253
- original_launch = demo.launch
254
-
255
- def patched_launch(*args, **kwargs):
256
- # Skip the problematic API processing in routes.py
257
- try:
258
- import types
259
- from gradio import routes
260
-
261
- # Create a dummy method that returns an empty dict to avoid the error
262
- def dummy_api_info(self):
263
- return {"endpoints": {}, "components": [], "dependencies": []}
264
 
265
- # Try to patch FastAPI.api_info
266
- try:
267
- if hasattr(routes, 'FastAPI'):
268
- original_api_info = routes.FastAPI.api_info
269
- routes.FastAPI.api_info = types.MethodType(dummy_api_info, routes.FastAPI)
270
- except:
271
- pass
272
-
273
- except:
274
- pass
275
 
276
- # Call the original launch method
277
- return original_launch(*args, **kwargs)
 
 
 
 
278
 
279
- # Replace the launch method with our patched version
280
- demo.launch = patched_launch
281
- demo.launch(share=False)
 
 
 
 
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))
 
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')
 
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
 
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
 
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)