Spaces:
Paused
Paused
File size: 10,262 Bytes
8e5b8a6 785585e 8e5b8a6 cf57dc0 8e5b8a6 cf57dc0 8e5b8a6 cf57dc0 8e5b8a6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
import cv2
import pytesseract
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import argparse
import io
import base64
class AndroidEditor:
def __init__(self, font_path="Roboto-Regular.ttf"):
self.font_path = font_path
@staticmethod
def find_text_position(text_list, target_text, start_idx=0):
"""Mencari posisi teks target dalam list teks"""
for i in range(start_idx, len(text_list)):
if target_text in text_list[i]:
return i
return None
@staticmethod
def get_position_data(extracted_data, idx):
"""Mendapatkan data posisi dari indeks tertentu"""
if idx is None or idx >= len(extracted_data['left']):
return None
return {
"left": extracted_data['left'][idx],
"top": extracted_data['top'][idx],
"width": extracted_data['width'][idx],
"height": extracted_data['height'][idx],
}
@staticmethod
def is_dark_mode(bg_color):
"""Mendeteksi apakah background menggunakan dark mode berdasarkan kecerahan warna"""
r, g, b = float(bg_color[0]), float(bg_color[1]), float(bg_color[2])
brightness = (r * 299 + g * 587 + b * 114) / 1000
return brightness < 128
def process_image(self, image_path, anggota):
image = cv2.imread(image_path)
if image is None:
return
result = self._process_core(image, anggota, show_preview=True)
return result
def process_image_bytes(self, image_bytes, anggota):
image_stream = io.BytesIO(image_bytes)
pil_image = Image.open(image_stream).convert('RGB')
image = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
result, theme = self._process_core(image, anggota, show_preview=False, return_theme=True)
if result is not None:
pil_result = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
output_io = io.BytesIO()
pil_result.save(output_io, format='PNG')
img_b64 = base64.b64encode(output_io.getvalue()).decode('utf-8')
return img_b64, theme
return None, None
def _process_core(self, image, anggota, show_preview=False, return_theme=False):
# Ekstrak teks dari gambar
extracted_data = pytesseract.image_to_data(image, output_type=pytesseract.Output.DICT)
text_list = extracted_data['text']
# Inisialisasi variabel posisi
group_position = None
split_position = None
member_position = None
member_count_position = None
second_member_position = None
second_member_count_position = None
lang = ''
group_idx = self.find_text_position(text_list, "Grup")
if group_idx is None:
group_idx = self.find_text_position(text_list, "Group")
if group_idx is not None:
lang = 'id' if "Grup" in text_list[group_idx] else 'en'
group_position = self.get_position_data(extracted_data, group_idx)
split_idx = self.find_text_position(text_list, "路", group_idx)
if split_idx is None:
for i in range(group_idx, min(group_idx + 4, len(text_list))):
if "-" in text_list[i]:
split_idx = i
break
split_position = self.get_position_data(extracted_data, split_idx)
member_idx = self.find_text_position(text_list, "anggota", group_idx)
if member_idx is None:
member_idx = self.find_text_position(text_list, "member", group_idx)
member_position = self.get_position_data(extracted_data, member_idx)
for i in range(group_idx, min(group_idx + 5, len(text_list))):
if text_list[i].isdigit():
member_count_position = self.get_position_data(extracted_data, i)
break
second_member_idx = self.find_text_position(text_list, "Anggota", group_idx + 4)
if second_member_idx is not None:
second_member_position = self.get_position_data(extracted_data, second_member_idx)
for i in range(second_member_idx - 3, second_member_idx):
if i >= 0 and text_list[i].isdigit():
second_member_count_position = self.get_position_data(extracted_data, i)
break
else:
return None
if member_position is None:
return None
x = member_position['left'] + member_position['width'] + 100
y = member_position['top'] + member_position['height'] - 100
bg_color = image[y, x]
rgb = (int(bg_color[0]), int(bg_color[1]), int(bg_color[2]))
is_dark = self.is_dark_mode(bg_color)
theme = 'Dark Mode' if is_dark else 'Light Mode'
text_color = (147,151,154,255) if is_dark else (90, 94, 95, 255)
for position in [group_position, split_position, member_position, member_count_position,
second_member_position, second_member_count_position]:
if position:
margin_horizontal = 10
cv2.rectangle(
image,
(position['left'] - margin_horizontal, position['top']),
(position['left'] + position['width'] + margin_horizontal, position['top'] + position['height']),
rgb,
-1,
)
if member_count_position:
updated_member_count = {
'id': f"Grup 路 {anggota} anggota",
'en': f"Group 路 {anggota} members"
}.get(lang)
original_height = member_count_position['height']
original_width = member_count_position['width']
font_size = int(original_height * 2.0)
font = ImageFont.truetype(self.font_path, font_size)
image_pil = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(image_pil)
min_size = int(original_height * 1.5)
max_size = int(original_height * 2.5)
max_iterations = 10
iteration = 0
while min_size <= max_size and iteration < max_iterations:
font = ImageFont.truetype(self.font_path, font_size)
text_bbox = draw.textbbox((0, 0), updated_member_count, font=font)
text_height = text_bbox[3] - text_bbox[1]
text_width = text_bbox[2] - text_bbox[0]
if abs(text_height - original_height) <= 2 and text_width <= original_width * 1.5:
break
if text_height > original_height or text_width > original_width * 1.5:
font_size = int(font_size * 0.95)
else:
font_size = int(font_size * 1.05)
font_size = max(min_size, min(max_size, font_size))
iteration += 1
text_width = text_bbox[2] - text_bbox[0]
image_width = image.shape[1]
text_x = (image_width - text_width) // 2
text_y = member_count_position['top'] - 2
draw.text((text_x, text_y), updated_member_count, font=font, fill=text_color)
image = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
if second_member_count_position:
updated_second_member_count = {
'id': f"{anggota} Anggota",
'en': f"{anggota} Members"
}.get(lang)
original_height = second_member_count_position['height']
original_width = second_member_count_position['width']
font_size = int(original_height * 2.0)
font = ImageFont.truetype(self.font_path, font_size)
image_pil = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(image_pil)
min_size = int(original_height * 1.5)
max_size = int(original_height * 2.5)
max_iterations = 10
iteration = 0
while min_size <= max_size and iteration < max_iterations:
font = ImageFont.truetype(self.font_path, font_size)
text_bbox = draw.textbbox((0, 0), updated_second_member_count, font=font)
text_height = text_bbox[3] - text_bbox[1]
text_width = text_bbox[2] - text_bbox[0]
if abs(text_height - original_height) <= 2 and text_width <= original_width * 1.5:
break
if text_height > original_height or text_width > original_width * 1.5:
font_size = int(font_size * 0.95)
else:
font_size = int(font_size * 1.05)
font_size = max(min_size, min(max_size, font_size))
iteration += 1
text_width = text_bbox[2] - text_bbox[0]
text_x = second_member_count_position['left']
text_y = second_member_count_position['top'] - 2
draw.text((text_x, text_y), updated_second_member_count, font=font, fill=text_color)
image = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
cv2.imwrite('output.png', image)
if show_preview:
cv2.imshow('Preview (Tekan q untuk keluar)', image)
while True:
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
cv2.destroyAllWindows()
if return_theme:
return image, theme
return image
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Proses gambar grup')
parser.add_argument('image_path', help='Path ke file gambar')
parser.add_argument('anggota', help='Jumlah anggota')
args = parser.parse_args()
editor = AndroidEditor()
editor.process_image(args.image_path, args.anggota)
|