Hydragee commited on
Commit
cc2f8db
·
verified ·
1 Parent(s): 4fc180f

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +163 -214
app.py CHANGED
@@ -1,231 +1,180 @@
1
- """
2
- UltraProTagger - HuggingFace Space Full Version
3
- Dataset'ten tam uygulamayı yükler ve çalıştırır
4
- """
5
 
6
  import os
7
  import sys
8
- import subprocess
9
-
10
- # ==================== DATASET'TEN KODU İNDİR ====================
11
-
12
- def setup_from_dataset():
13
- """Dataset'ten kaynak kodu indir ve kurulum yap"""
14
-
15
- DATASET_REPO = "Hydragee/ultrapro-tagger"
16
- LOCAL_PATH = "/home/user/app/ultrapro-tagger"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- # Zaten indirilmişse atla
19
- if os.path.exists(os.path.join(LOCAL_PATH, "main.py")):
20
- print("✅ Kod zaten mevcut")
21
- return LOCAL_PATH
22
-
23
- print("📥 Dataset'ten kod indiriliyor...")
24
-
25
- try:
26
- from huggingface_hub import snapshot_download
27
 
28
- # Dataset'i indir
29
- local_dir = snapshot_download(
30
- repo_id=DATASET_REPO,
31
- repo_type="dataset",
32
- local_dir=LOCAL_PATH,
33
- token=os.environ.get("HF_TOKEN")
34
- )
35
-
36
- print(f"✅ Kod indirildi: {local_dir}")
37
- return local_dir
38
-
39
- except Exception as e:
40
- print(f"❌ İndirme hatası: {e}")
41
- return None
42
 
43
- # Kurulum yap
44
- APP_PATH = setup_from_dataset()
45
 
46
- if APP_PATH:
47
- # Sys path'e ekle
48
- sys.path.insert(0, APP_PATH)
49
- os.chdir(APP_PATH)
50
-
51
- # ==================== ORIJINAL UYGULAMAYI YÜKLE ====================
52
-
53
- import gradio as gr
54
- from modules.shared_state import set_web_image, check_and_reset_tab_switch, shared_state
55
- from modules.config_manager import load_config
56
- from modules.ui.common import CSS_STYLES
57
- from modules.ui.tab_settings import create_settings_tab
58
- from modules.ui.tab_single import create_single_tab
59
- from modules.ui.tab_batch import create_batch_tab
60
- from modules.ui.tab_dual import create_dual_tab
61
- from modules.ui.tab_tools import create_tools_tab
62
- from modules.managers.rule_manager import (
63
- read_replacement_file_content,
64
- read_synonym_file_content,
65
- read_addition_file_content
66
- )
67
- from modules.managers.localization_manager import get_str
68
-
69
- # Tagger modülleri
70
- try:
71
- from modules.tagger import run_joint_classifier, cl_tagger_instance
72
- except Exception as e:
73
- print(f"⚠️ Tagger modülleri yüklenemedi: {e}")
74
- run_joint_classifier = None
75
- cl_tagger_instance = None
76
-
77
- # Klasör Sabitleri
78
- KATEGORILER_KLASORU = "data/rules/kategoriler"
79
- ALT_KATEGORILER_KLASORU = "data/rules/alt_kategoriler"
80
- REPLACEMENT_RULES_KLASORU = "data/rules/replacement_rules"
81
- SYNONYM_RULES_KLASORU = "data/rules/synonym_rules"
82
- ADDITION_RULES_KLASORU = "data/rules/addition_rules"
83
- CONFIGLIST_KLASORU = "data/rules/configlist"
84
-
85
- OS_ENV_HF_TOKEN = os.environ.get("HF_TOKEN")
86
-
87
- def create_ui():
88
- # Ayarları yükle
89
- app_config = load_config()
90
-
91
- # Tema Ayarını Uygula
92
- current_theme_name = app_config.get("general_settings", {}).get("theme", "Default")
93
- theme_object = None
94
-
95
- if current_theme_name == "Soft":
96
- theme_object = gr.themes.Soft()
97
- elif current_theme_name == "Glass":
98
- theme_object = gr.themes.Glass()
99
- elif current_theme_name == "Monochrome":
100
- theme_object = gr.themes.Monochrome()
101
-
102
- with gr.Blocks(title=get_str("app_title"), css=CSS_STYLES, theme=theme_object) as demo:
103
 
104
- # Uyarı mesajları
105
- if OS_ENV_HF_TOKEN is None or run_joint_classifier is None:
106
- gr.Markdown("""<div style='background-color:#fff3cd; color:#856404; padding:10px; border-radius:8px; border:1px solid #ffeeba; margin-bottom: 20px;'>⚠️ **UYARI:** Joint Tagger modeli başlatılamadı veya 'HF_TOKEN' ortam değişkeni ayarlanmamış.</div>""")
 
 
 
 
 
107
 
108
- if cl_tagger_instance is None or (hasattr(cl_tagger_instance, 'session') and cl_tagger_instance.session is None):
109
- gr.Markdown("""<div style='background-color:#f8d7da; color:#721c24; padding:10px; border-radius:8px; border:1px solid #f5c6cb; margin-bottom: 20px;'>❌ **HATA:** CL Tagger modeli başlatılamadı.</div>""")
110
-
111
- # ANA TABS
112
- with gr.Tabs() as tabs_ana_panel:
113
-
114
- # 1. AYARLAR
115
- settings_components = create_settings_tab(app_config)
116
-
117
- # 2. TEKİL ETİKETLEME
118
- single_components = create_single_tab(settings_components)
119
-
120
- # 3. DUAL ETİKETLEME
121
- dual_components = create_dual_tab(settings_components)
122
-
123
- # 4. TOPLU ETİKETLEME
124
- batch_components = create_batch_tab(settings_components)
125
-
126
- # 5. ARAÇLAR
127
- tools_components = create_tools_tab(app_config)
128
-
129
- # --- ANA SEKME KONTROL DÖNGÜSÜ ---
130
- def control_tab_switch():
131
- if check_and_reset_tab_switch():
132
- return gr.Tabs(selected="tab_single")
133
- return gr.update()
134
-
135
- main_loop_btn = gr.Button("Main Loop", visible=False, elem_id="main_loop_btn")
136
- main_loop_btn.click(
137
- fn=control_tab_switch,
138
- inputs=[],
139
- outputs=[tabs_ana_panel],
140
- show_progress="hidden"
141
  )
142
 
143
- # --- BUTON BAĞLANTILARI ---
144
- def transfer_ve_gecis(text):
145
- return text, gr.Tabs(selected="tab_kategori_araclari")
146
-
147
- if "btn_send_tekil" in single_components and "toplu_filtered_output" in single_components:
148
- single_components["btn_send_tekil"].click(
149
- fn=transfer_ve_gecis,
150
- inputs=[single_components["toplu_filtered_output"]],
151
- outputs=[tools_components["etiket_input_common"], tabs_ana_panel]
152
- )
153
-
154
- if "btn_send_toplu" in batch_components and "toplu_batch_combined_original_tags" in batch_components:
155
- batch_components["btn_send_toplu"].click(
156
- fn=transfer_ve_gecis,
157
- inputs=[batch_components["toplu_batch_combined_original_tags"]],
158
- outputs=[tools_components["etiket_input_common"], tabs_ana_panel]
159
- )
160
-
161
- if "btn_send_dual" in dual_components and "dual_combined_all_tags" in dual_components:
162
- dual_components["btn_send_dual"].click(
163
- fn=transfer_ve_gecis,
164
- inputs=[dual_components["dual_combined_all_tags"]],
165
- outputs=[tools_components["etiket_input_common"], tabs_ana_panel]
166
- )
167
-
168
- gr.Markdown(
169
- f"<h1 style='text-align: center; color: #4a00e0; margin-bottom: 5px; font-size: 1.5em; font-weight: 700; text-shadow: 1px 1px 2px rgba(0,0,0,0.1);'>🚀 {get_str('app_title')}</h1>"
170
- f"<div style='text-align: center; color: #555; font-size: 0.9em;'>{get_str('app_subtitle')}</div>"
171
  )
172
 
173
- # Default dosya yüklemeleri
174
- default_replacement_path = os.path.join(REPLACEMENT_RULES_KLASORU, "varsayilan_degisiklikler.txt")
175
- default_synonym_path = os.path.join(SYNONYM_RULES_KLASORU, "varsayilan_birlesimler.txt")
176
- default_addition_path = os.path.join(ADDITION_RULES_KLASORU, "varsayilan_eklemeler.txt")
177
-
178
- demo.load(fn=lambda: read_replacement_file_content(default_replacement_path) if os.path.exists(default_replacement_path) else "", outputs=tools_components["replacement_file_content"])
179
- demo.load(fn=lambda: read_synonym_file_content(default_synonym_path) if os.path.exists(default_synonym_path) else "", outputs=tools_components["synonym_file_content"])
180
- demo.load(fn=lambda: read_addition_file_content(default_addition_path) if os.path.exists(default_addition_path) else "", outputs=tools_components["addition_file_content"])
181
-
182
- demo.load(None, None, None, js="""
183
- () => {
184
- console.log("UltraProTagger: Smart Polling Başlatıldı");
185
- setInterval(async () => {
186
- try {
187
- const response = await fetch('/api/check_status');
188
- const data = await response.json();
189
-
190
- if (data.switch_tab) {
191
- const btnMain = document.getElementById('main_loop_btn');
192
- if (btnMain) btnMain.click();
193
- }
194
-
195
- if (data.new_image) {
196
- const btnTimer = document.getElementById('timer_btn');
197
- if (btnTimer) btnTimer.click();
198
- }
199
- } catch (e) {
200
- console.error("Polling hatası:", e);
201
- }
202
- }, 1000);
203
- }
204
- """)
205
-
206
- demo.queue()
207
- return demo
208
-
209
- # Klasörleri oluştur
210
- folders_to_create = [
211
- KATEGORILER_KLASORU, ALT_KATEGORILER_KLASORU,
212
- REPLACEMENT_RULES_KLASORU, SYNONYM_RULES_KLASORU, ADDITION_RULES_KLASORU,
213
- CONFIGLIST_KLASORU, "data/configs"
214
- ]
215
- for folder in folders_to_create:
216
- os.makedirs(folder, exist_ok=True)
217
-
218
- # Demo oluştur ve başlat
219
- demo = create_ui()
220
-
221
- else:
222
- # Fallback: Basit hata mesajı
223
- import gradio as gr
224
-
225
- with gr.Blocks() as demo:
226
- gr.Markdown("# ❌ Hata\nDataset'ten kod yüklenemedi. Lütfen daha sonra tekrar deneyin.")
227
 
228
- # ==================== UYGULAMA BAŞLAT ====================
 
 
 
229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  if __name__ == "__main__":
231
  demo.launch()
 
1
+ # app.py - HuggingFace Space Version
2
+ # UltraProTagger - Tam Uygulama
 
 
3
 
4
  import os
5
  import sys
6
+ import gradio as gr
7
+
8
+ # Modül importları
9
+ from modules.shared_state import set_web_image, check_and_reset_tab_switch, shared_state
10
+ from modules.config_manager import load_config
11
+ from modules.ui.common import CSS_STYLES
12
+ from modules.ui.tab_settings import create_settings_tab
13
+ from modules.ui.tab_single import create_single_tab
14
+ from modules.ui.tab_batch import create_batch_tab
15
+ from modules.ui.tab_dual import create_dual_tab
16
+ from modules.ui.tab_tools import create_tools_tab
17
+ from modules.managers.rule_manager import (
18
+ read_replacement_file_content,
19
+ read_synonym_file_content,
20
+ read_addition_file_content
21
+ )
22
+ from modules.managers.localization_manager import get_str
23
+
24
+ # --- Global Kontroller ---
25
+ try:
26
+ from modules.tagger import run_joint_classifier, cl_tagger_instance
27
+ except Exception as e:
28
+ print(f"⚠️ Tagger yüklenirken hata: {e}")
29
+ run_joint_classifier = None
30
+ cl_tagger_instance = None
31
+
32
+ # Klasör Sabitleri
33
+ KATEGORILER_KLASORU = "data/rules/kategoriler"
34
+ ALT_KATEGORILER_KLASORU = "data/rules/alt_kategoriler"
35
+ REPLACEMENT_RULES_KLASORU = "data/rules/replacement_rules"
36
+ SYNONYM_RULES_KLASORU = "data/rules/synonym_rules"
37
+ ADDITION_RULES_KLASORU = "data/rules/addition_rules"
38
+ CONFIGLIST_KLASORU = "data/rules/configlist"
39
+
40
+ OS_ENV_HF_TOKEN = os.environ.get("HF_TOKEN")
41
+
42
+
43
+ def create_ui():
44
+ # Ayarları yükle
45
+ app_config = load_config()
46
+
47
+ # Tema Ayarını Uygula
48
+ current_theme_name = app_config.get("general_settings", {}).get("theme", "Default")
49
+ theme_object = None
50
 
51
+ if current_theme_name == "Soft":
52
+ theme_object = gr.themes.Soft()
53
+ elif current_theme_name == "Glass":
54
+ theme_object = gr.themes.Glass()
55
+ elif current_theme_name == "Monochrome":
56
+ theme_object = gr.themes.Monochrome()
57
+
58
+ with gr.Blocks(title=get_str("app_title"), css=CSS_STYLES, theme=theme_object) as demo:
 
59
 
60
+ # Uyarı mesajları
61
+ if OS_ENV_HF_TOKEN is None or run_joint_classifier is None:
62
+ gr.Markdown("""<div style='background-color:#fff3cd; color:#856404; padding:10px; border-radius:8px; border:1px solid #ffeeba; margin-bottom: 20px;'>⚠️ **UYARI:** Joint Tagger modeli başlatılamadı veya 'HF_TOKEN' ortam değişkeni ayarlanmamış.</div>""")
63
+ if cl_tagger_instance is None or (hasattr(cl_tagger_instance, 'session') and cl_tagger_instance.session is None):
64
+ gr.Markdown("""<div style='background-color:#f8d7da; color:#721c24; padding:10px; border-radius:8px; border:1px solid #f5c6cb; margin-bottom: 20px;'>❌ **HATA:** CL Tagger modeli başlatılamadı.</div>""")
65
+
66
+ # ANA TABS
67
+ with gr.Tabs() as tabs_ana_panel:
68
+
69
+ # 1. AYARLAR
70
+ settings_components = create_settings_tab(app_config)
71
+
72
+ # 2. TEKİL ETİKETLEME
73
+ single_components = create_single_tab(settings_components)
74
 
75
+ # 3. DUAL ETİKETLEME
76
+ dual_components = create_dual_tab(settings_components)
77
 
78
+ # 4. TOPLU ETİKETLEME
79
+ batch_components = create_batch_tab(settings_components)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
+ # 5. ARAÇLAR
82
+ tools_components = create_tools_tab(app_config)
83
+
84
+ # --- ANA SEKME KONTROL DÖNGÜSÜ ---
85
+ def control_tab_switch():
86
+ if check_and_reset_tab_switch():
87
+ return gr.Tabs(selected="tab_single")
88
+ return gr.update()
89
 
90
+ main_loop_btn = gr.Button("Main Loop", visible=False, elem_id="main_loop_btn")
91
+ main_loop_btn.click(
92
+ fn=control_tab_switch,
93
+ inputs=[],
94
+ outputs=[tabs_ana_panel],
95
+ show_progress="hidden"
96
+ )
97
+
98
+ # --- BUTON BAĞLANTILARI ---
99
+ def transfer_ve_gecis(text):
100
+ return text, gr.Tabs(selected="tab_kategori_araclari")
101
+
102
+ if "btn_send_tekil" in single_components and "toplu_filtered_output" in single_components:
103
+ single_components["btn_send_tekil"].click(
104
+ fn=transfer_ve_gecis,
105
+ inputs=[single_components["toplu_filtered_output"]],
106
+ outputs=[tools_components["etiket_input_common"], tabs_ana_panel]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  )
108
 
109
+ if "btn_send_toplu" in batch_components and "toplu_batch_combined_original_tags" in batch_components:
110
+ batch_components["btn_send_toplu"].click(
111
+ fn=transfer_ve_gecis,
112
+ inputs=[batch_components["toplu_batch_combined_original_tags"]],
113
+ outputs=[tools_components["etiket_input_common"], tabs_ana_panel]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  )
115
 
116
+ if "btn_send_dual" in dual_components and "dual_combined_all_tags" in dual_components:
117
+ dual_components["btn_send_dual"].click(
118
+ fn=transfer_ve_gecis,
119
+ inputs=[dual_components["dual_combined_all_tags"]],
120
+ outputs=[tools_components["etiket_input_common"], tabs_ana_panel]
121
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
+ gr.Markdown(
124
+ f"<h1 style='text-align: center; color: #4a00e0; margin-bottom: 5px; font-size: 1.5em; font-weight: 700; text-shadow: 1px 1px 2px rgba(0,0,0,0.1);'>🚀 {get_str('app_title')}</h1>"
125
+ f"<div style='text-align: center; color: #555; font-size: 0.9em;'>{get_str('app_subtitle')}</div>"
126
+ )
127
 
128
+ # Default dosya yüklemeleri
129
+ default_replacement_path = os.path.join(REPLACEMENT_RULES_KLASORU, "varsayilan_degisiklikler.txt")
130
+ default_synonym_path = os.path.join(SYNONYM_RULES_KLASORU, "varsayilan_birlesimler.txt")
131
+ default_addition_path = os.path.join(ADDITION_RULES_KLASORU, "varsayilan_eklemeler.txt")
132
+
133
+ demo.load(fn=lambda: read_replacement_file_content(default_replacement_path) if os.path.exists(default_replacement_path) else "", outputs=tools_components["replacement_file_content"])
134
+ demo.load(fn=lambda: read_synonym_file_content(default_synonym_path) if os.path.exists(default_synonym_path) else "", outputs=tools_components["synonym_file_content"])
135
+ demo.load(fn=lambda: read_addition_file_content(default_addition_path) if os.path.exists(default_addition_path) else "", outputs=tools_components["addition_file_content"])
136
+
137
+ demo.queue()
138
+ return demo
139
+
140
+
141
+ # ==================== BAŞLANGIÇ ====================
142
+
143
+ # Klasörleri oluştur
144
+ folders_to_create = [
145
+ KATEGORILER_KLASORU, ALT_KATEGORILER_KLASORU,
146
+ REPLACEMENT_RULES_KLASORU, SYNONYM_RULES_KLASORU, ADDITION_RULES_KLASORU,
147
+ CONFIGLIST_KLASORU, "data/configs"
148
+ ]
149
+ for folder in folders_to_create:
150
+ os.makedirs(folder, exist_ok=True)
151
+
152
+ # Varsayılan dosyaları oluştur
153
+ default_replacement_file_path = os.path.join(REPLACEMENT_RULES_KLASORU, "varsayilan_degisiklikler.txt")
154
+ if not os.path.exists(default_replacement_file_path):
155
+ with open(default_replacement_file_path, "w", encoding="utf-8") as f:
156
+ f.write("# Her satıra bir kural: eski_etiket_regex -> yeni_etiket\n")
157
+ f.write("# Örnek: blue_hair -> cyan hair\n")
158
+
159
+ default_synonym_file_path = os.path.join(SYNONYM_RULES_KLASORU, "varsayilan_birlesimler.txt")
160
+ if not os.path.exists(default_synonym_file_path):
161
+ with open(default_synonym_file_path, "w", encoding="utf-8") as f:
162
+ f.write("# Her satıra bir kural: ana_etiket: silinecek_es_anlamli_etiket1, silinecek_es_anlamli_etiket2\n")
163
+ f.write("# Örnek: panties: underwear\n")
164
+
165
+ default_addition_file_path = os.path.join(ADDITION_RULES_KLASORU, "varsayilan_eklemeler.txt")
166
+ if not os.path.exists(default_addition_file_path):
167
+ with open(default_addition_file_path, "w", encoding="utf-8") as f:
168
+ f.write("best quality, masterpiece\n")
169
+
170
+ default_configlist_file_path = os.path.join(CONFIGLIST_KLASORU, "varsayilan_isimler.txt")
171
+ if not os.path.exists(default_configlist_file_path):
172
+ with open(default_configlist_file_path, "w", encoding="utf-8") as f:
173
+ f.write("Güzel_Çiçek\nHarika_Manzara\nGizemli_Sanat\n")
174
+
175
+ # Demo oluştur
176
+ demo = create_ui()
177
+
178
+ # Başlat
179
  if __name__ == "__main__":
180
  demo.launch()