Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -7,16 +7,17 @@ import requests
|
|
7 |
import datetime
|
8 |
import zipfile
|
9 |
import matplotlib.font_manager
|
10 |
-
import matplotlib.colors as mcolors
|
11 |
from huggingface_hub import HfApi, HfFolder
|
|
|
12 |
|
13 |
# Hugging Face repo and token
|
14 |
HF_REPO = "ArrcttacsrjksX/Texttoimage"
|
15 |
HF_ENGINE_URL = "https://huggingface.co/ArrcttacsrjksX/Texttoimage/resolve/main/engine"
|
16 |
-
HF_TOKEN = os.getenv("HF_TOKEN")
|
17 |
ENGINE_EXECUTABLE = "./engine"
|
18 |
|
19 |
def download_engine():
|
|
|
20 |
if not os.path.exists(ENGINE_EXECUTABLE):
|
21 |
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
|
22 |
response = requests.get(HF_ENGINE_URL, headers=headers, stream=True)
|
@@ -32,10 +33,6 @@ def ensure_executable(file_path):
|
|
32 |
if not os.access(file_path, os.X_OK):
|
33 |
os.chmod(file_path, os.stat(file_path).st_mode | stat.S_IXUSR)
|
34 |
|
35 |
-
def hex_to_rgb_float(hex_color):
|
36 |
-
"""Convert hex color (#RRGGBB) to (r, g, b) float values."""
|
37 |
-
return mcolors.hex2color(hex_color)
|
38 |
-
|
39 |
def extract_and_load_fonts(directory="fontfile", extract_to="extracted_fonts"):
|
40 |
if not os.path.exists(extract_to):
|
41 |
os.makedirs(extract_to)
|
@@ -64,6 +61,7 @@ def get_available_fonts():
|
|
64 |
return sorted(set(system_fonts + extracted_fonts))
|
65 |
|
66 |
def upload_to_huggingface(file_path, text_content, timestamp_folder):
|
|
|
67 |
api = HfApi()
|
68 |
HfFolder.save_token(HF_TOKEN)
|
69 |
repo_path = f"{HF_REPO}/{timestamp_folder}"
|
@@ -73,27 +71,19 @@ def upload_to_huggingface(file_path, text_content, timestamp_folder):
|
|
73 |
api.upload_file(path_or_fileobj="temp_text.txt", path_in_repo=f"{repo_path}/text.txt", repo_id=HF_REPO)
|
74 |
os.remove("temp_text.txt")
|
75 |
|
76 |
-
def read_file_content(file):
|
77 |
-
"""Read text from uploaded file."""
|
78 |
-
try:
|
79 |
-
if isinstance(file, bytes):
|
80 |
-
return file.decode("utf-8")
|
81 |
-
elif hasattr(file, "read"):
|
82 |
-
return file.read().decode("utf-8")
|
83 |
-
return str(file, "utf-8")
|
84 |
-
except Exception as e:
|
85 |
-
return f"Error reading file: {e}"
|
86 |
-
|
87 |
def call_engine(file_input, input_text, font_size, width, height, bg_color, text_color, mode, font_name, align, line_spacing, image_format):
|
88 |
download_engine()
|
89 |
ensure_executable(ENGINE_EXECUTABLE)
|
90 |
if file_input:
|
91 |
input_text = read_file_content(file_input)
|
92 |
|
93 |
-
#
|
94 |
-
|
95 |
-
|
96 |
-
|
|
|
|
|
|
|
97 |
input_data = {
|
98 |
"input_text": input_text,
|
99 |
"font_size": font_size,
|
@@ -107,16 +97,21 @@ def call_engine(file_input, input_text, font_size, width, height, bg_color, text
|
|
107 |
"line_spacing": line_spacing,
|
108 |
"image_format": image_format
|
109 |
}
|
110 |
-
|
111 |
result = subprocess.run([ENGINE_EXECUTABLE, json.dumps(input_data)], capture_output=True, text=True)
|
112 |
if result.returncode != 0:
|
113 |
raise Exception(f"Engine error: {result.stderr}")
|
114 |
-
|
115 |
output_path = result.stdout.strip()
|
116 |
timestamp_folder = datetime.datetime.now().strftime("%d-%m-%Y %H-%M-%S")
|
117 |
upload_to_huggingface(output_path, input_text, timestamp_folder)
|
118 |
return output_path
|
119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
with gr.Blocks() as demo:
|
121 |
gr.Markdown("# 🖼️ Text to Image Converter")
|
122 |
available_fonts = get_available_fonts()
|
|
|
7 |
import datetime
|
8 |
import zipfile
|
9 |
import matplotlib.font_manager
|
|
|
10 |
from huggingface_hub import HfApi, HfFolder
|
11 |
+
from matplotlib.colors import to_rgba
|
12 |
|
13 |
# Hugging Face repo and token
|
14 |
HF_REPO = "ArrcttacsrjksX/Texttoimage"
|
15 |
HF_ENGINE_URL = "https://huggingface.co/ArrcttacsrjksX/Texttoimage/resolve/main/engine"
|
16 |
+
HF_TOKEN = os.getenv("HF_TOKEN") # Lấy token từ biến môi trường
|
17 |
ENGINE_EXECUTABLE = "./engine"
|
18 |
|
19 |
def download_engine():
|
20 |
+
"""Download engine from Hugging Face if not available."""
|
21 |
if not os.path.exists(ENGINE_EXECUTABLE):
|
22 |
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
|
23 |
response = requests.get(HF_ENGINE_URL, headers=headers, stream=True)
|
|
|
33 |
if not os.access(file_path, os.X_OK):
|
34 |
os.chmod(file_path, os.stat(file_path).st_mode | stat.S_IXUSR)
|
35 |
|
|
|
|
|
|
|
|
|
36 |
def extract_and_load_fonts(directory="fontfile", extract_to="extracted_fonts"):
|
37 |
if not os.path.exists(extract_to):
|
38 |
os.makedirs(extract_to)
|
|
|
61 |
return sorted(set(system_fonts + extracted_fonts))
|
62 |
|
63 |
def upload_to_huggingface(file_path, text_content, timestamp_folder):
|
64 |
+
"""Upload image and text to Hugging Face repo."""
|
65 |
api = HfApi()
|
66 |
HfFolder.save_token(HF_TOKEN)
|
67 |
repo_path = f"{HF_REPO}/{timestamp_folder}"
|
|
|
71 |
api.upload_file(path_or_fileobj="temp_text.txt", path_in_repo=f"{repo_path}/text.txt", repo_id=HF_REPO)
|
72 |
os.remove("temp_text.txt")
|
73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
def call_engine(file_input, input_text, font_size, width, height, bg_color, text_color, mode, font_name, align, line_spacing, image_format):
|
75 |
download_engine()
|
76 |
ensure_executable(ENGINE_EXECUTABLE)
|
77 |
if file_input:
|
78 |
input_text = read_file_content(file_input)
|
79 |
|
80 |
+
# Chuyển đổi màu sắc sang dạng hợp lệ
|
81 |
+
try:
|
82 |
+
bg_color = to_rgba(bg_color)
|
83 |
+
text_color = to_rgba(text_color)
|
84 |
+
except ValueError:
|
85 |
+
raise Exception("Invalid color format. Please use a valid color code or tuple.")
|
86 |
+
|
87 |
input_data = {
|
88 |
"input_text": input_text,
|
89 |
"font_size": font_size,
|
|
|
97 |
"line_spacing": line_spacing,
|
98 |
"image_format": image_format
|
99 |
}
|
|
|
100 |
result = subprocess.run([ENGINE_EXECUTABLE, json.dumps(input_data)], capture_output=True, text=True)
|
101 |
if result.returncode != 0:
|
102 |
raise Exception(f"Engine error: {result.stderr}")
|
|
|
103 |
output_path = result.stdout.strip()
|
104 |
timestamp_folder = datetime.datetime.now().strftime("%d-%m-%Y %H-%M-%S")
|
105 |
upload_to_huggingface(output_path, input_text, timestamp_folder)
|
106 |
return output_path
|
107 |
|
108 |
+
def read_file_content(file):
|
109 |
+
"""Read text from uploaded file."""
|
110 |
+
try:
|
111 |
+
return file.decode("utf-8") if isinstance(file, bytes) else file.read().decode("utf-8")
|
112 |
+
except Exception as e:
|
113 |
+
return f"Error reading file: {e}"
|
114 |
+
|
115 |
with gr.Blocks() as demo:
|
116 |
gr.Markdown("# 🖼️ Text to Image Converter")
|
117 |
available_fonts = get_available_fonts()
|