ArrcttacsrjksX commited on
Commit
0fde3b3
·
verified ·
1 Parent(s): f2d48fb

Upload app (6).py

Browse files
Files changed (1) hide show
  1. app (6).py +156 -0
app (6).py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import subprocess
3
+ import json
4
+ import os
5
+ import stat
6
+ import zipfile
7
+ from PIL import ImageFont
8
+ import matplotlib.font_manager
9
+
10
+ # Path to the compiled engine executable
11
+ ENGINE_EXECUTABLE = "./engine"
12
+
13
+ def ensure_executable(file_path):
14
+ """
15
+ Đảm bảo rằng file có quyền thực thi.
16
+ Nếu không, cấp quyền thực thi.
17
+ """
18
+ if not os.access(file_path, os.X_OK): # Kiểm tra quyền thực thi
19
+ try:
20
+ # Cấp quyền thực thi
21
+ current_permissions = os.stat(file_path).st_mode
22
+ os.chmod(file_path, current_permissions | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
23
+ print(f"Granted execute permission to {file_path}")
24
+ except Exception as e:
25
+ raise PermissionError(f"Failed to grant execute permission to {file_path}: {e}")
26
+
27
+ def extract_and_load_fonts_from_directory(directory="fontfile", extract_to="extracted_fonts"):
28
+ if not os.path.exists(extract_to):
29
+ os.makedirs(extract_to)
30
+
31
+ fonts = []
32
+
33
+ # Extract fonts from zip files
34
+ for root, dirs, files in os.walk(directory):
35
+ for file in files:
36
+ if file.endswith(".zip"):
37
+ zip_path = os.path.join(root, file)
38
+ try:
39
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
40
+ zip_ref.extractall(extract_to)
41
+ print(f"Extracted: {zip_path}")
42
+ except Exception as e:
43
+ print(f"Failed to extract {zip_path}: {e}")
44
+
45
+ # Collect all .ttf and .shx fonts
46
+ for root, dirs, files in os.walk(extract_to):
47
+ for file in files:
48
+ if file.endswith(".ttf") or file.endswith(".shx"):
49
+ fonts.append(os.path.join(root, file))
50
+
51
+ return fonts
52
+
53
+ def get_system_fonts():
54
+ fonts = []
55
+ for font in matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf'):
56
+ fonts.append(font)
57
+ return fonts
58
+
59
+ def get_available_fonts():
60
+ # Get system fonts
61
+ system_fonts = get_system_fonts()
62
+
63
+ # Extract and load custom fonts
64
+ extracted_fonts = extract_and_load_fonts_from_directory()
65
+
66
+ # Combine and deduplicate fonts
67
+ all_fonts = list(set(system_fonts + extracted_fonts))
68
+ return sorted(all_fonts)
69
+
70
+ def call_engine(input_text, font_size, width, height, bg_color, text_color, mode, font_name, align, line_spacing, image_format):
71
+ # Ensure the engine file is executable
72
+ ensure_executable(ENGINE_EXECUTABLE)
73
+
74
+ # Prepare input data as a dictionary
75
+ input_data = {
76
+ "input_text": input_text,
77
+ "font_size": font_size,
78
+ "width": width,
79
+ "height": height,
80
+ "bg_color": bg_color,
81
+ "text_color": text_color,
82
+ "mode": mode,
83
+ "font_path": font_name, # Pass the selected font path
84
+ "align": align,
85
+ "line_spacing": line_spacing,
86
+ "image_format": image_format
87
+ }
88
+
89
+ # Call the engine executable with input data
90
+ result = subprocess.run(
91
+ [ENGINE_EXECUTABLE, json.dumps(input_data)],
92
+ capture_output=True,
93
+ text=True
94
+ )
95
+
96
+ # Handle errors
97
+ if result.returncode != 0:
98
+ raise Exception(f"Engine failed with error: {result.stderr}")
99
+
100
+ # Get the output image path from stdout
101
+ output_path = result.stdout.strip()
102
+
103
+ # Load the generated image
104
+ if os.path.exists(output_path):
105
+ return output_path
106
+ else:
107
+ raise Exception("Failed to generate image!")
108
+
109
+ with gr.Blocks() as demo:
110
+ gr.Markdown("# 🖼️ Text to Image Converter")
111
+
112
+ with gr.Row():
113
+ input_text = gr.Textbox(label="Enter Text", placeholder="Type or paste text here...", lines=5)
114
+ file_input = gr.File(label="Upload a Text File", type="filepath")
115
+
116
+ with gr.Row():
117
+ font_size = gr.Slider(10, 100, value=30, label="Font Size")
118
+
119
+ # Lấy danh sách font và đặt font mặc định là font đầu tiên
120
+ available_fonts = get_available_fonts()
121
+ default_font = available_fonts[0] if available_fonts else ""
122
+
123
+ font_name = gr.Dropdown(choices=available_fonts, value=default_font, label="Font")
124
+ align = gr.Radio(["Left", "Center", "Right"], label="Text Alignment", value="Center")
125
+
126
+ with gr.Row():
127
+ width = gr.Slider(200, 2000, value=800, label="Image Width")
128
+ height = gr.Slider(200, 2000, value=600, label="Base Height")
129
+
130
+ with gr.Row():
131
+ bg_color = gr.ColorPicker(label="Background Color", value="#FFFFFF")
132
+ text_color = gr.ColorPicker(label="Text Color", value="#000000")
133
+
134
+ with gr.Row():
135
+ mode = gr.Radio(["Plain Text", "LaTeX Math"], label="Rendering Mode", value="Plain Text")
136
+ image_format = gr.Radio(["PNG", "JPEG"], label="Image Format", value="PNG")
137
+
138
+ # Add line spacing slider
139
+ line_spacing = gr.Slider(1.0, 3.0, value=1.2, step=0.1, label="Line Spacing")
140
+
141
+ output_image = gr.Image(label="Generated Image")
142
+
143
+ with gr.Row():
144
+ convert_button = gr.Button("Convert Text to Image")
145
+ file_convert_button = gr.Button("Convert File to Image")
146
+
147
+ convert_button.click(
148
+ call_engine,
149
+ inputs=[
150
+ input_text, font_size, width, height, bg_color, text_color,
151
+ mode, font_name, align, line_spacing, image_format
152
+ ],
153
+ outputs=output_image
154
+ )
155
+
156
+ demo.launch()