vericudebuget commited on
Commit
ff71fa8
·
verified ·
1 Parent(s): 5926fe1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +191 -0
app.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import py7zr
4
+ import requests
5
+ from huggingface_hub import HfApi
6
+ import torch
7
+ from torch.utils.data import DataLoader
8
+ import shutil
9
+ from pathlib import Path
10
+ from typing import Optional
11
+ import sys
12
+ import io
13
+
14
+ # Import the denoising code (assuming it's in a file called denoising_model.py)
15
+ from denoising_model import DenoisingModel, DenoiseDataset, get_optimal_threads
16
+
17
+ class StreamCapture:
18
+ def __init__(self):
19
+ self.logs = []
20
+
21
+ def write(self, text):
22
+ self.logs.append(text)
23
+ st.warning(text)
24
+
25
+ def flush(self):
26
+ pass
27
+
28
+ def download_and_extract_7z(url: str, extract_to: str = '.') -> Optional[str]:
29
+ """Downloads a 7z file and extracts it"""
30
+ try:
31
+ st.warning(f"Downloading file from {url}...")
32
+ response = requests.get(url, stream=True)
33
+ response.raise_for_status()
34
+
35
+ archive_path = os.path.join(extract_to, 'dataset.7z')
36
+ with open(archive_path, 'wb') as f:
37
+ for chunk in response.iter_content(chunk_size=8192):
38
+ f.write(chunk)
39
+
40
+ st.warning("Extracting 7z archive...")
41
+ with py7zr.SevenZipFile(archive_path, mode='r') as z:
42
+ z.extractall(extract_to)
43
+
44
+ # Handle directory renaming
45
+ output_images_path = os.path.join(extract_to, 'output_images')
46
+ if os.path.exists(output_images_path):
47
+ # Move and rename directories
48
+ source_noisy = os.path.join(output_images_path, 'images_noisy')
49
+ source_target = os.path.join(output_images_path, 'images_target')
50
+
51
+ if os.path.exists('noisy_images'):
52
+ shutil.rmtree('noisy_images')
53
+ if os.path.exists('target_images'):
54
+ shutil.rmtree('target_images')
55
+
56
+ shutil.move(source_noisy, 'noisy_images')
57
+ shutil.move(source_target, 'target_images')
58
+
59
+ # Clean up
60
+ if os.path.exists(output_images_path):
61
+ shutil.rmtree(output_images_path)
62
+
63
+ os.remove(archive_path)
64
+ st.warning("Download and extraction completed successfully.")
65
+ return None
66
+
67
+ except Exception as e:
68
+ return f"Error: {str(e)}"
69
+
70
+ def upload_to_huggingface(file_path: str, repo_id: str, path_in_repo: str):
71
+ """Uploads a file to Hugging Face"""
72
+ try:
73
+ api = HfApi()
74
+ api.upload_file(
75
+ path_or_fileobj=file_path,
76
+ path_in_repo=path_in_repo,
77
+ repo_id=repo_id,
78
+ repo_type="space"
79
+ )
80
+ st.warning(f"Successfully uploaded {file_path} to {repo_id}")
81
+ except Exception as e:
82
+ st.error(f"Error uploading to Hugging Face: {str(e)}")
83
+
84
+ def train_model_with_upload(epochs, batch_size, learning_rate, save_interval, num_workers, repo_id):
85
+ """Modified training function that uploads checkpoints to Hugging Face"""
86
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
87
+ st.warning(f"Using device: {device}")
88
+
89
+ # Create temporary directory for checkpoints
90
+ checkpoint_dir = "temp_checkpoints"
91
+ os.makedirs(checkpoint_dir, exist_ok=True)
92
+
93
+ try:
94
+ dataset = DenoiseDataset('noisy_images', 'target_images')
95
+ dataloader = DataLoader(
96
+ dataset,
97
+ batch_size=batch_size,
98
+ shuffle=True,
99
+ num_workers=num_workers,
100
+ pin_memory=True if torch.cuda.is_available() else False
101
+ )
102
+
103
+ model = DenoisingModel().to(device)
104
+ criterion = torch.nn.MSELoss()
105
+ optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
106
+
107
+ for epoch in range(epochs):
108
+ st.warning(f"Starting epoch {epoch+1}/{epochs}")
109
+ for batch_idx, (noisy_patches, target_patches) in enumerate(dataloader):
110
+ noisy_patches = noisy_patches.to(device)
111
+ target_patches = target_patches.to(device)
112
+
113
+ outputs = model(noisy_patches)
114
+ loss = criterion(outputs, target_patches)
115
+
116
+ optimizer.zero_grad()
117
+ loss.backward()
118
+ optimizer.step()
119
+
120
+ if (batch_idx + 1) % 10 == 0:
121
+ st.warning(f"Epoch [{epoch+1}/{epochs}], Batch [{batch_idx+1}], Loss: {loss.item():.6f}")
122
+
123
+ if (batch_idx + 1) % save_interval == 0:
124
+ checkpoint_path = os.path.join(checkpoint_dir, f"checkpoint_epoch{epoch+1}_batch{batch_idx+1}.pth")
125
+ torch.save(model.state_dict(), checkpoint_path)
126
+
127
+ # Upload checkpoint to Hugging Face
128
+ upload_to_huggingface(
129
+ checkpoint_path,
130
+ repo_id,
131
+ f"checkpoints/checkpoint_epoch{epoch+1}_batch{batch_idx+1}.pth"
132
+ )
133
+
134
+ # Save and upload final model
135
+ final_model_path = os.path.join(checkpoint_dir, "final_model.pth")
136
+ torch.save(model.state_dict(), final_model_path)
137
+ upload_to_huggingface(final_model_path, repo_id, "model/final_model.pth")
138
+
139
+ finally:
140
+ # Clean up temporary directory
141
+ if os.path.exists(checkpoint_dir):
142
+ shutil.rmtree(checkpoint_dir)
143
+
144
+ def main():
145
+ st.title("Image Denoising Model Training")
146
+
147
+ # Redirect stdout to capture print statements
148
+ sys.stdout = StreamCapture()
149
+
150
+ # Input for Hugging Face token
151
+ hf_token = st.text_input("Enter your Hugging Face token:", type="password")
152
+ if hf_token:
153
+ os.environ["HF_TOKEN"] = hf_token
154
+
155
+ # Input for repository ID
156
+ repo_id = st.text_input("Enter your Hugging Face repository ID (username/repo):")
157
+
158
+ # Download and extract dataset button
159
+ if st.button("Download and Extract Dataset"):
160
+ url = "https://huggingface.co/spaces/vericudebuget/ok4231/resolve/main/output_images.7z"
161
+ error = download_and_extract_7z(url)
162
+ if error:
163
+ st.error(error)
164
+
165
+ # Training parameters
166
+ col1, col2 = st.columns(2)
167
+ with col1:
168
+ epochs = st.number_input("Number of epochs", min_value=1, value=10)
169
+ batch_size = st.number_input("Batch size", min_value=1, value=4)
170
+ learning_rate = st.number_input("Learning rate", min_value=0.0001, value=0.001, format="%.4f")
171
+
172
+ with col2:
173
+ save_interval = st.number_input("Save interval (batches)", min_value=1, value=1000)
174
+ num_workers = st.number_input("Number of workers", min_value=1, value=get_optimal_threads())
175
+
176
+ # Start training button
177
+ if st.button("Start Training"):
178
+ if not hf_token:
179
+ st.error("Please enter your Hugging Face token")
180
+ return
181
+ if not repo_id:
182
+ st.error("Please enter your repository ID")
183
+ return
184
+ if not os.path.exists("noisy_images") or not os.path.exists("target_images"):
185
+ st.error("Dataset not found. Please download and extract it first.")
186
+ return
187
+
188
+ train_model_with_upload(epochs, batch_size, learning_rate, save_interval, num_workers, repo_id)
189
+
190
+ if __name__ == "__main__":
191
+ main()