ArrcttacsrjksX commited on
Commit
5527dff
·
verified ·
1 Parent(s): 8e73422

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -231
app.py CHANGED
@@ -1,255 +1,76 @@
1
- import os
2
- import subprocess
3
  import gradio as gr
4
- from huggingface_hub import hf_hub_download
 
5
  import logging
6
- import tempfile
7
-
8
- # Set up logging
9
- logging.basicConfig(
10
- level=logging.INFO,
11
- format='%(asctime)s - %(levelname)s - %(message)s'
12
- )
13
- logger = logging.getLogger(__name__)
14
-
15
- # Configuration
16
- CLI_FILENAME = "Texttoimage"
17
- REPO_ID = "ArrcttacsrjksX/Texttoimage"
18
- FONT_LIST = ["Arial", "Times New Roman", "Courier New", "Comic Sans MS", "Verdana"]
19
- DEFAULT_FONT = "Arial"
20
- TEMP_DIR = tempfile.gettempdir()
21
 
22
  def setup_cli_tool():
23
  """Download and set up the CLI tool with proper error handling."""
 
 
 
24
  if os.path.exists(CLI_FILENAME):
25
- logger.info(f"CLI tool already exists: {CLI_FILENAME}")
26
  return True
27
-
28
  hf_token = os.environ.get("HF_TOKEN")
29
  if not hf_token:
30
- logger.error("HF_TOKEN environment variable not set!")
31
- return False
32
-
33
- try:
34
- logger.info(f"Downloading CLI tool from {REPO_ID}...")
35
- cli_local_path = hf_hub_download(
36
- repo_id=REPO_ID,
37
- filename=CLI_FILENAME,
38
- token=hf_token
39
- )
40
-
41
- if os.path.exists(cli_local_path):
42
- if os.path.exists(CLI_FILENAME):
43
- os.remove(CLI_FILENAME)
44
- os.rename(cli_local_path, CLI_FILENAME)
45
- os.chmod(CLI_FILENAME, 0o755)
46
- logger.info(f"Successfully downloaded and set up CLI tool: {CLI_FILENAME}")
47
- return True
48
- else:
49
- logger.error(f"Downloaded file not found at {cli_local_path}")
50
- return False
51
-
52
- except Exception as e:
53
- logger.error(f"Error during CLI tool setup: {str(e)}")
54
  return False
55
 
56
- def read_text_file(file_path):
57
- """Read text from uploaded file."""
58
- try:
59
- with open(file_path, 'r', encoding='utf-8') as f:
60
- return f.read()
61
- except Exception as e:
62
- logger.error(f"Error reading file: {str(e)}")
63
- return None
64
-
65
- def text_to_image(text, font_size, width, height, bg_color, text_color, mode, font_name, align, image_format):
66
- """Convert text to image using the CLI tool."""
67
- if not text:
68
- return "Error: No text provided", "Please enter text or upload a file"
69
-
70
- if not os.path.exists(CLI_FILENAME):
71
- if not setup_cli_tool():
72
- return None, "Error: Failed to set up Texttoimage. Please check logs and HF_TOKEN."
73
-
74
- # Create unique output filename
75
- output_path = os.path.join(TEMP_DIR, f"output_image_{os.getpid()}.{image_format.lower()}")
76
 
77
- command = [
78
- f"./{CLI_FILENAME}",
79
- "--text", text,
 
 
 
80
  "--font-size", str(font_size),
81
  "--width", str(width),
82
  "--height", str(height),
83
  "--bg-color", bg_color,
84
  "--text-color", text_color,
85
- "--mode", mode.lower(),
86
- "--font", font_name,
87
- "--align", align.lower(),
88
- "--format", image_format.lower(),
89
- "--output", output_path
90
  ]
91
 
92
  try:
93
- result = subprocess.run(command, check=True, capture_output=True, text=True)
94
- if os.path.exists(output_path):
95
- return output_path, "Image generated successfully!"
96
  else:
97
- logger.error(f"Output file not created: {output_path}")
98
- logger.error(f"Command output: {result.stdout}")
99
- logger.error(f"Command error: {result.stderr}")
100
- return None, "Error: Failed to generate image. Check logs for details."
101
- except subprocess.CalledProcessError as e:
102
- logger.error(f"CLI tool execution failed: {str(e)}")
103
- logger.error(f"Command output: {e.stdout}")
104
- logger.error(f"Command error: {e.stderr}")
105
- return None, f"Error: Failed to generate image: {str(e)}"
106
 
107
- def handle_file_upload(file_path):
108
- """Handle file upload and return text content."""
109
- if file_path is None:
110
- return None, "No file uploaded"
111
- text = read_text_file(file_path)
112
- if text is None:
113
- return None, "Error reading file"
114
- return text, "File uploaded successfully!"
115
 
116
- # Create Gradio interface
117
- with gr.Blocks(title="Text to Image Converter") as demo:
118
- gr.Markdown("# 🖼️ Text to Image Converter")
119
-
120
- # Status message
121
- status_msg = gr.Markdown("Status: Ready")
122
-
123
- # Input section
124
- with gr.Row():
125
- with gr.Column():
126
- input_text = gr.Textbox(
127
- label="Enter Text",
128
- placeholder="Type or paste text here...",
129
- lines=5
130
- )
131
- file_input = gr.File(
132
- label="Or Upload a Text File",
133
- type="filepath"
134
- )
135
-
136
- # Settings section
137
- with gr.Row():
138
- with gr.Column():
139
- font_size = gr.Slider(
140
- minimum=10,
141
- maximum=100,
142
- value=30,
143
- label="Font Size"
144
- )
145
- font_name = gr.Dropdown(
146
- choices=FONT_LIST,
147
- value=DEFAULT_FONT,
148
- label="Font"
149
- )
150
- align = gr.Radio(
151
- choices=["Left", "Center", "Right"],
152
- label="Text Alignment",
153
- value="Center"
154
- )
155
-
156
- with gr.Row():
157
- with gr.Column():
158
- width = gr.Slider(
159
- minimum=200,
160
- maximum=2000,
161
- value=800,
162
- label="Image Width"
163
- )
164
- height = gr.Slider(
165
- minimum=200,
166
- maximum=2000,
167
- value=600,
168
- label="Base Height"
169
- )
170
-
171
- with gr.Row():
172
- with gr.Column():
173
- bg_color = gr.ColorPicker(
174
- label="Background Color",
175
- value="#FFFFFF"
176
- )
177
- text_color = gr.ColorPicker(
178
- label="Text Color",
179
- value="#000000"
180
- )
181
-
182
- with gr.Row():
183
- with gr.Column():
184
- mode = gr.Radio(
185
- choices=["Plain Text", "LaTeX Math"],
186
- label="Rendering Mode",
187
- value="Plain Text"
188
- )
189
- image_format = gr.Radio(
190
- choices=["PNG", "JPEG"],
191
- label="Image Format",
192
- value="PNG"
193
- )
194
-
195
- # Output section
196
- output_image = gr.Image(label="Generated Image")
197
-
198
- # Buttons
199
- with gr.Row():
200
- convert_button = gr.Button("Convert Text to Image", variant="primary")
201
- clear_button = gr.Button("Clear", variant="secondary")
202
-
203
- # Event handlers
204
- def convert_with_status(*args):
205
- status_msg.update("Converting...")
206
- result, message = text_to_image(*args)
207
- status_msg.update(message)
208
- return result
209
-
210
- def clear_inputs():
211
- return {
212
- input_text: "",
213
- output_image: None,
214
- status_msg: gr.Markdown("Status: Ready")
215
- }
216
-
217
- def handle_file_upload_event(file_path):
218
- text, message = handle_file_upload(file_path)
219
- status_msg.update(message)
220
- return text if text else ""
221
-
222
- # Set up event listeners
223
- convert_button.click(
224
- fn=convert_with_status,
225
- inputs=[
226
- input_text, font_size, width, height,
227
- bg_color, text_color, mode, font_name,
228
- align, image_format
229
- ],
230
- outputs=output_image
231
- )
232
-
233
- clear_button.click(
234
- fn=clear_inputs,
235
- inputs=[],
236
- outputs=[input_text, output_image, status_msg]
237
- )
238
-
239
- file_input.upload(
240
- fn=handle_file_upload_event,
241
- inputs=[file_input],
242
- outputs=[input_text]
243
- )
244
 
245
- # Launch the application
246
- if __name__ == "__main__":
247
- try:
248
- demo.launch(
249
- server_name="0.0.0.0",
250
- server_port=7860,
251
- share=False,
252
- show_error=True
253
- )
254
- except Exception as e:
255
- logger.error(f"Failed to launch application: {str(e)}")
 
 
 
1
  import gradio as gr
2
+ import subprocess
3
+ import os
4
  import logging
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  def setup_cli_tool():
7
  """Download and set up the CLI tool with proper error handling."""
8
+ CLI_FILENAME = "Texttoimage"
9
+ REPO_ID = "ArrcttacsrjksX/Texttoimage"
10
+
11
  if os.path.exists(CLI_FILENAME):
12
+ logging.info(f"CLI tool already exists: {CLI_FILENAME}")
13
  return True
14
+
15
  hf_token = os.environ.get("HF_TOKEN")
16
  if not hf_token:
17
+ logging.error("HF_TOKEN environment variable not set!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  return False
19
 
20
+ def run_texttoimage(text, file, font_size, width, height, bg_color, text_color, mode, font, align):
21
+ command = ["./Texttoimage"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ if text:
24
+ command += ["-t", text]
25
+ elif file:
26
+ command += ["-f", file.name]
27
+
28
+ command += [
29
  "--font-size", str(font_size),
30
  "--width", str(width),
31
  "--height", str(height),
32
  "--bg-color", bg_color,
33
  "--text-color", text_color,
34
+ "--mode", mode,
35
+ "--font", font,
36
+ "--align", align,
37
+ "--output", "output.png"
 
38
  ]
39
 
40
  try:
41
+ result = subprocess.run(command, capture_output=True, text=True)
42
+ if result.returncode == 0:
43
+ return "output.png"
44
  else:
45
+ return f"Error: {result.stderr}"
46
+ except Exception as e:
47
+ return f"Execution failed: {e}"
 
 
 
 
 
 
48
 
49
+ # Danh sách font mẫu
50
+ AVAILABLE_FONTS = [
51
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
52
+ "/usr/share/fonts/truetype/liberation/LiberationSerif-Regular.ttf",
53
+ "/usr/share/fonts/truetype/msttcorefonts/Arial.ttf"
54
+ ]
 
 
55
 
56
+ # Tạo giao diện Gradio
57
+ demo = gr.Interface(
58
+ fn=run_texttoimage,
59
+ inputs=[
60
+ gr.Textbox(label="Input Text", lines=3, placeholder="Nhập văn bản..."),
61
+ gr.File(label="Upload File"),
62
+ gr.Slider(10, 100, value=30, label="Font Size"),
63
+ gr.Number(value=800, label="Image Width"),
64
+ gr.Number(value=600, label="Image Height"),
65
+ gr.ColorPicker(value="#FFFFFF", label="Background Color", interactive=True),
66
+ gr.ColorPicker(value="#000000", label="Text Color", interactive=True),
67
+ gr.Radio(["plain", "math"], value="plain", label="Rendering Mode"),
68
+ gr.Dropdown(AVAILABLE_FONTS, value=AVAILABLE_FONTS[0], label="Font Selection"),
69
+ gr.Radio(["left", "center", "right"], value="center", label="Text Alignment")
70
+ ],
71
+ outputs=gr.Image(label="Generated Image"),
72
+ title="Text to Image Converter",
73
+ description="Ứng dụng chuyển văn bản thành ảnh sử dụng Texttoimage."
74
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
+ demo.launch()