kerenmasku commited on
Commit
cbcf658
·
verified ·
1 Parent(s): 9ecd1a7

Delete all.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. all.py +0 -233
all.py DELETED
@@ -1,233 +0,0 @@
1
- import cv2
2
- from PIL import Image
3
- import numpy as np
4
- import argparse
5
- import io
6
- import base64
7
- import time
8
- import logging
9
- from android import AndroidEditor
10
- from iphone import IPhoneEditor
11
- from bottom import IPhoneBottom, AndroidBottom
12
- # Setup logging
13
- logging.basicConfig(level=logging.INFO)
14
- logger = logging.getLogger(__name__)
15
-
16
- class UnifiedEditor:
17
- def __init__(self, iphone_font_path="SFUIText-Regular.otf", android_font_path="Roboto-Regular.ttf"):
18
- self.iphone_editor = IPhoneEditor(iphone_font_path)
19
- self.android_editor = AndroidEditor(android_font_path)
20
- self.iphone_bottom = IPhoneBottom(iphone_font_path)
21
- self.android_bottom = AndroidBottom(android_font_path)
22
-
23
- @staticmethod
24
- def parse_anggota(anggota_str, ocr_count=None):
25
- """Parse anggota parameter and handle + prefix for addition or return string as is"""
26
- if anggota_str.startswith('+'):
27
- # If starts with +, add to existing OCR count
28
- if ocr_count is None:
29
- logger.error("OCR count is None, cannot perform addition")
30
- return None
31
- try:
32
- addition = int(anggota_str[1:])
33
- result = ocr_count + addition
34
- logger.info(f"Adding {addition} to OCR count {ocr_count} = {result}")
35
- return result
36
- except ValueError:
37
- logger.error(f"Invalid number format in anggota: {anggota_str}")
38
- return None
39
- else:
40
- # Try to convert to number first
41
- try:
42
- result = int(anggota_str)
43
- logger.info(f"Using direct anggota value: {result}")
44
- return result
45
- except ValueError:
46
- # If not a number, treat as string
47
- logger.info(f"Using string anggota value: {anggota_str}")
48
- return anggota_str
49
-
50
- def detect_platform(self, text_list):
51
- # """Deteksi platform berdasarkan pola teks"""
52
- for i, text in enumerate(text_list):
53
- if text.lower() in {"anggota", "members"} and i > 0 and text_list[i-1].isdigit():
54
- print(text_list[i-1])
55
- if not any(text_list[j] in {"-", "Grup"} for j in range(i-2, max(-1, i-5), -1)):
56
- return "Bottom iPhone" if any(t.lower() == "edit" for t in text_list) else "Bottom Android"
57
-
58
- window_size = 5
59
- for i in range(len(text_list) - window_size + 1):
60
- window = " ".join(text_list[i:i+window_size]).lower()
61
- if ("info" in window and "grup" in window) or ("info" in window and "group" in window):
62
- return "iPhone"
63
- return "Android"
64
-
65
- def process_image(self, image_path, anggota):
66
- start_time = time.time()
67
- image = cv2.imread(image_path)
68
- if image is None:
69
- logger.error("Failed to read image")
70
- return None, None, None
71
-
72
- # Convert image to bytes for platform detection and OCR
73
- _, img_encoded = cv2.imencode('.png', image)
74
- img_bytes = img_encoded.tobytes()
75
-
76
- # Perform OCR once and reuse results
77
- extracted_data = self.iphone_editor._perform_ocr(img_bytes)
78
- if extracted_data is None:
79
- logger.error("OCR failed")
80
- return None, None, None
81
-
82
- text_list = extracted_data['text']
83
-
84
- # Detect platform using OCR results
85
- platform = self.detect_platform(text_list)
86
- logger.info(f"Detected platform: {platform}")
87
-
88
- # Get OCR count for potential addition
89
- if platform == "Bottom iPhone":
90
- ocr_count = self.iphone_bottom.replace_anggota(image, 0, skip_ocr=True, extracted_data=extracted_data, get_ocr_count_only=True)
91
- elif platform == "Bottom Android":
92
- ocr_count = self.android_bottom.replace_anggota(image, 0, skip_ocr=True, extracted_data=extracted_data, get_ocr_count_only=True)
93
- else:
94
- ocr_count = self._get_ocr_count_from_text_list(text_list)
95
-
96
- # Parse anggota parameter
97
- parsed_anggota = self.parse_anggota(anggota, ocr_count)
98
- if parsed_anggota is None:
99
- logger.error("Invalid anggota parameter")
100
- return None, None, None
101
-
102
- # Process with appropriate editor
103
- if platform == "iPhone":
104
- result, theme = self.iphone_editor._process_core(image, str(parsed_anggota), show_preview=True, return_theme=True, skip_ocr=True, extracted_data=extracted_data)
105
- elif platform == "Bottom iPhone":
106
- result, theme = self.iphone_bottom.replace_anggota(image, str(parsed_anggota), show_preview=True, return_theme=True, skip_ocr=True, extracted_data=extracted_data)
107
- elif platform == "Bottom Android":
108
- result, theme = self.android_bottom.replace_anggota(image, str(parsed_anggota), show_preview=True, return_theme=True, skip_ocr=True, extracted_data=extracted_data)
109
- else:
110
- result, theme = self.android_editor._process_core(image, str(parsed_anggota), show_preview=True, return_theme=True, skip_ocr=True, extracted_data=extracted_data)
111
-
112
- if result is None:
113
- return None, None, None
114
-
115
- end_time = time.time()
116
- logger.info(f"Total processing time: {end_time - start_time:.2f} seconds")
117
- return result, theme, platform
118
-
119
- def _get_ocr_count_from_text_list(self, text_list):
120
- """Get OCR count from text list for addition operations"""
121
- try:
122
- # Try to find group index first
123
- group_idx = None
124
- for i, text in enumerate(text_list):
125
- if "Grup" in text or "Group" in text:
126
- group_idx = i
127
- break
128
-
129
- if group_idx is not None:
130
- # Find the original member count from OCR
131
- for i in range(group_idx, min(group_idx + 5, len(text_list))):
132
- if text_list[i].isdigit():
133
- try:
134
- ocr_count = int(text_list[i])
135
- logger.info(f"Found OCR count: {ocr_count}")
136
- return ocr_count
137
- except ValueError:
138
- continue
139
-
140
- logger.warning("No valid OCR count found, using 0 as default")
141
- return 0
142
-
143
- except Exception as e:
144
- logger.error(f"Error getting OCR count: {str(e)}")
145
- return 0
146
-
147
- def process_image_bytes(self, image_bytes, anggota):
148
- start_time = time.time()
149
- try:
150
- # Convert image_bytes to numpy array first
151
- image_stream = io.BytesIO(image_bytes)
152
- pil_image = Image.open(image_stream).convert('RGB')
153
- image = np.array(pil_image)
154
-
155
- # Perform OCR once and reuse results
156
- extracted_data = self.iphone_editor._perform_ocr(image_bytes)
157
- if extracted_data is None:
158
- logger.error("OCR failed")
159
- return None, None, None
160
-
161
- text_list = extracted_data['text']
162
-
163
- # Detect platform using OCR results
164
- platform = self.detect_platform(text_list)
165
- logger.info(f"Detected platform: {platform}")
166
-
167
- # Get OCR count for potential addition - use 'image' (numpy array) instead of 'image_bytes'
168
- if platform == "Bottom iPhone":
169
- ocr_count = self.iphone_bottom.replace_anggota(image, 0, skip_ocr=True, extracted_data=extracted_data, get_ocr_count_only=True)
170
- elif platform == "Bottom Android":
171
- ocr_count = self.android_bottom.replace_anggota(image, 0, skip_ocr=True, extracted_data=extracted_data, get_ocr_count_only=True)
172
- else:
173
- ocr_count = self._get_ocr_count_from_text_list(text_list)
174
-
175
- # Parse anggota parameter
176
- parsed_anggota = self.parse_anggota(anggota, ocr_count)
177
- if parsed_anggota is None:
178
- logger.error("Invalid anggota parameter")
179
- return None, None, None
180
-
181
- # Process with appropriate editor
182
- if platform == "iPhone":
183
- result, theme = self.iphone_editor.process_image_bytes(image_bytes, str(parsed_anggota), extracted_data)
184
- elif platform == "Bottom iPhone":
185
- result, theme = self.iphone_bottom.replace_anggota(image, str(parsed_anggota), show_preview=True, return_theme=True, skip_ocr=True, extracted_data=extracted_data)
186
- # Convert numpy array to base64 string for bottom platforms
187
- if result is not None:
188
- pil_result = Image.fromarray(result)
189
- output_io = io.BytesIO()
190
- pil_result.save(output_io, format='PNG')
191
- result = base64.b64encode(output_io.getvalue()).decode('utf-8')
192
- elif platform == "Bottom Android":
193
- result, theme = self.android_bottom.replace_anggota(image, str(parsed_anggota), show_preview=True, return_theme=True, skip_ocr=True, extracted_data=extracted_data)
194
- # Convert numpy array to base64 string for bottom platforms
195
- if result is not None:
196
- pil_result = Image.fromarray(result)
197
- output_io = io.BytesIO()
198
- pil_result.save(output_io, format='PNG')
199
- result = base64.b64encode(output_io.getvalue()).decode('utf-8')
200
- else:
201
- result, theme = self.android_editor.process_image_bytes(image_bytes, str(parsed_anggota), extracted_data)
202
-
203
- if result is not None:
204
- end_time = time.time()
205
- logger.info(f"Total processing time: {end_time - start_time:.2f} seconds")
206
- return result, theme, platform
207
- else:
208
- logger.error("Result image is None")
209
- return None, None, None
210
- except Exception as e:
211
- logger.error(f"Error in process_image_bytes: {str(e)}")
212
- return None, None, None
213
-
214
- if __name__ == '__main__':
215
- parser = argparse.ArgumentParser(description='Proses gambar grup unified')
216
- parser.add_argument('image_path', help='Path ke file gambar')
217
- parser.add_argument('anggota', help='Jumlah anggota (bisa menggunakan + untuk menambah ke jumlah yang ada, contoh: +5 untuk menambah 5)')
218
- args = parser.parse_args()
219
- editor = UnifiedEditor()
220
- result, theme, platform = editor.process_image(args.image_path, args.anggota)
221
- if result is not None:
222
- print(f"Processing completed successfully!")
223
- print(f"Detected platform: {platform}")
224
- print(f"Detected theme: {theme}")
225
- else:
226
- print("Processing failed!")
227
-
228
- # Contoh penggunaan:
229
- # python all.py image.png 10 # Set jumlah anggota menjadi 10
230
- # python all.py image.png +5 # Tambah 5 ke jumlah anggota yang ada di OCR
231
- # python all.py image.png +10 # Tambah 10 ke jumlah anggota yang ada di OCR
232
- # python all.py image.png "Banyak" # Gunakan string "Banyak" sebagai anggota
233
- # python all.py image.png "100+" # Gunakan string "100+" sebagai anggota