hallelu commited on
Commit
071f38f
Β·
verified Β·
1 Parent(s): 4bb0e84

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -0
app.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import subprocess
3
+ import os
4
+ import time
5
+ import threading
6
+ from datetime import datetime
7
+
8
+ # Global variable to track training status
9
+ training_status = {"running": False, "output": "", "progress": 0}
10
+
11
+ def install_dependencies():
12
+ """Install required packages"""
13
+ try:
14
+ subprocess.run(["pip", "install", "-r", "hf_requirements.txt"],
15
+ capture_output=True, text=True, check=True)
16
+ return "βœ… Dependencies installed successfully!"
17
+ except Exception as e:
18
+ return f"❌ Error installing dependencies: {str(e)}"
19
+
20
+ def extract_data():
21
+ """Extract training data"""
22
+ try:
23
+ if os.path.exists("processed_data.zip"):
24
+ subprocess.run(["unzip", "-o", "processed_data.zip"],
25
+ capture_output=True, text=True, check=True)
26
+ return "βœ… Data extracted successfully!"
27
+ else:
28
+ return "❌ processed_data.zip not found! Please upload it first."
29
+ except Exception as e:
30
+ return f"❌ Error extracting data: {str(e)}"
31
+
32
+ def run_training():
33
+ """Run the training process"""
34
+ global training_status
35
+
36
+ if training_status["running"]:
37
+ return "⚠️ Training is already running!"
38
+
39
+ training_status["running"] = True
40
+ training_status["output"] = ""
41
+ training_status["progress"] = 0
42
+
43
+ try:
44
+ # Install dependencies
45
+ training_status["output"] += "πŸ“¦ Installing dependencies...\n"
46
+ install_result = install_dependencies()
47
+ training_status["output"] += install_result + "\n"
48
+
49
+ # Extract data
50
+ training_status["output"] += "πŸ“ Extracting data...\n"
51
+ extract_result = extract_data()
52
+ training_status["output"] += extract_result + "\n"
53
+
54
+ # Start training
55
+ training_status["output"] += "πŸš€ Starting training...\n"
56
+ training_status["output"] += f"⏰ Started at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
57
+
58
+ # Run training script
59
+ process = subprocess.Popen(
60
+ ["python", "hf_train.py"],
61
+ stdout=subprocess.PIPE,
62
+ stderr=subprocess.STDOUT,
63
+ text=True,
64
+ bufsize=1,
65
+ universal_newlines=True
66
+ )
67
+
68
+ # Monitor training progress
69
+ for line in process.stdout:
70
+ training_status["output"] += line
71
+ # Update progress based on epoch completion
72
+ if "Epoch" in line and "/50" in line:
73
+ try:
74
+ epoch_info = line.split("Epoch ")[1].split("/")[0]
75
+ current_epoch = int(epoch_info)
76
+ training_status["progress"] = (current_epoch / 50) * 100
77
+ except:
78
+ pass
79
+
80
+ process.wait()
81
+
82
+ if process.returncode == 0:
83
+ training_status["output"] += "\nπŸŽ‰ Training completed successfully!"
84
+ else:
85
+ training_status["output"] += "\n❌ Training failed!"
86
+
87
+ except Exception as e:
88
+ training_status["output"] += f"\n❌ Error during training: {str(e)}"
89
+
90
+ finally:
91
+ training_status["running"] = False
92
+ training_status["progress"] = 100
93
+
94
+ def start_training():
95
+ """Start training in a separate thread"""
96
+ thread = threading.Thread(target=run_training)
97
+ thread.start()
98
+ return "πŸš€ Training started! Check the output below for progress."
99
+
100
+ def get_training_output():
101
+ """Get current training output"""
102
+ return training_status["output"]
103
+
104
+ def get_progress():
105
+ """Get training progress"""
106
+ return training_status["progress"]
107
+
108
+ def check_files():
109
+ """Check if required files are present"""
110
+ files_status = []
111
+
112
+ # Check training script
113
+ if os.path.exists("hf_train.py"):
114
+ files_status.append("βœ… hf_train.py")
115
+ else:
116
+ files_status.append("❌ hf_train.py (missing)")
117
+
118
+ # Check requirements
119
+ if os.path.exists("hf_requirements.txt"):
120
+ files_status.append("βœ… hf_requirements.txt")
121
+ else:
122
+ files_status.append("❌ hf_requirements.txt (missing)")
123
+
124
+ # Check data
125
+ if os.path.exists("processed_data.zip"):
126
+ size = os.path.getsize("processed_data.zip") / (1024 * 1024) # MB
127
+ files_status.append(f"βœ… processed_data.zip ({size:.1f} MB)")
128
+ else:
129
+ files_status.append("❌ processed_data.zip (missing)")
130
+
131
+ # Check if data is extracted
132
+ if os.path.exists("processed_data"):
133
+ files_status.append("βœ… processed_data directory")
134
+ else:
135
+ files_status.append("⚠️ processed_data directory (will be created)")
136
+
137
+ return "\n".join(files_status)
138
+
139
+ def download_model():
140
+ """Provide download link for trained model"""
141
+ if os.path.exists("best_model.pth"):
142
+ size = os.path.getsize("best_model.pth") / (1024 * 1024) # MB
143
+ return f"βœ… Model ready for download!\nπŸ“ File: best_model.pth\nπŸ“ Size: {size:.1f} MB\nπŸ’‘ Download from the Files tab on the right."
144
+ else:
145
+ return "❌ No trained model found. Please run training first."
146
+
147
+ # Create Gradio interface
148
+ with gr.Blocks(title="🏠 Floorplan Segmentation Training", theme=gr.themes.Soft()) as demo:
149
+ gr.Markdown("# 🏠 Floorplan Segmentation Model Training")
150
+ gr.Markdown("Train a deep learning model to segment floorplan images into walls, doors, windows, rooms, and background.")
151
+
152
+ with gr.Row():
153
+ with gr.Column(scale=1):
154
+ gr.Markdown("## πŸ“‹ File Status")
155
+ file_status = gr.Textbox(label="Required Files", value=check_files, lines=6, interactive=False)
156
+
157
+ gr.Markdown("## πŸš€ Training Controls")
158
+ start_btn = gr.Button("Start Training", variant="primary", size="lg")
159
+ status_text = gr.Textbox(label="Status", value="Ready to train", interactive=False)
160
+
161
+ gr.Markdown("## πŸ“Š Progress")
162
+ progress_bar = gr.Slider(minimum=0, maximum=100, value=0, label="Training Progress (%)", interactive=False)
163
+
164
+ gr.Markdown("## πŸ’Ύ Download Model")
165
+ download_btn = gr.Button("Check Model Status")
166
+ download_status = gr.Textbox(label="Model Status", value="No model trained yet", interactive=False)
167
+
168
+ with gr.Column(scale=2):
169
+ gr.Markdown("## πŸ“ Training Output")
170
+ output_text = gr.Textbox(label="Training Log", value="Training output will appear here...", lines=20, interactive=False)
171
+
172
+ # Event handlers
173
+ start_btn.click(
174
+ fn=start_training,
175
+ outputs=status_text
176
+ )
177
+
178
+ download_btn.click(
179
+ fn=download_model,
180
+ outputs=download_status
181
+ )
182
+
183
+ # Auto-refresh output and progress
184
+ demo.load(lambda: None, None, None, every=5) # Refresh every 5 seconds
185
+
186
+ # Update output and progress
187
+ def update_output():
188
+ return get_training_output(), get_progress()
189
+
190
+ demo.load(update_output, outputs=[output_text, progress_bar], every=2)
191
+
192
+ # Launch the app
193
+ if __name__ == "__main__":
194
+ demo.launch()