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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
def health_check():
|
35 |
return {"status": "✅ FastAPI running on Hugging Face Spaces!"}
|
36 |
|
37 |
+
REPO_ID = "rahul7star/ohamlab"
|
38 |
+
FOLDER = "demo"
|
39 |
+
BASE_URL = f"https://huggingface.co/{REPO_ID}/resolve/main/"
|
40 |
|
41 |
+
#show all images in a DIR at UI FE
|
42 |
+
@app.get("/images")
|
43 |
+
def list_images():
|
44 |
+
try:
|
45 |
+
all_files = list_repo_files(REPO_ID)
|
46 |
+
|
47 |
+
folder_prefix = FOLDER.rstrip("/") + "/"
|
48 |
+
|
49 |
+
files_in_folder = [
|
50 |
+
f for f in all_files
|
51 |
+
if f.startswith(folder_prefix)
|
52 |
+
and "/" not in f[len(folder_prefix):] # no subfolder files
|
53 |
+
and f.lower().endswith((".png", ".jpg", ".jpeg", ".webp"))
|
54 |
+
]
|
55 |
+
|
56 |
+
urls = [BASE_URL + f for f in files_in_folder]
|
57 |
+
|
58 |
+
return {"images": urls}
|
59 |
+
|
60 |
+
except Exception as e:
|
61 |
+
return {"error": str(e)}
|
62 |
+
|
63 |
+
from datetime import datetime
|
64 |
+
import tempfile
|
65 |
+
import uuid
|
66 |
+
|
67 |
+
# upload zip from UI
|
68 |
+
@app.post("/upload-zip")
|
69 |
+
async def upload_zip(file: UploadFile = File(...)):
|
70 |
+
if not file.filename.endswith(".zip"):
|
71 |
+
return {"error": "Please upload a .zip file"}
|
72 |
+
|
73 |
+
# Save the ZIP to /tmp
|
74 |
+
temp_zip_path = f"/tmp/{file.filename}"
|
75 |
+
with open(temp_zip_path, "wb") as f:
|
76 |
+
f.write(await file.read())
|
77 |
+
|
78 |
+
# Create a unique subfolder name inside 'demo/'
|
79 |
+
timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
|
80 |
+
unique_id = uuid.uuid4().hex[:6]
|
81 |
+
folder_name = f"upload_{timestamp}_{unique_id}"
|
82 |
+
hf_folder_prefix = f"demo/{folder_name}"
|
83 |
+
|
84 |
+
try:
|
85 |
+
with tempfile.TemporaryDirectory() as extract_dir:
|
86 |
+
# Extract zip
|
87 |
+
with zipfile.ZipFile(temp_zip_path, 'r') as zip_ref:
|
88 |
+
zip_ref.extractall(extract_dir)
|
89 |
+
|
90 |
+
uploaded_files = []
|
91 |
+
|
92 |
+
# Upload all extracted files
|
93 |
+
for root_dir, _, files in os.walk(extract_dir):
|
94 |
+
for name in files:
|
95 |
+
file_path = os.path.join(root_dir, name)
|
96 |
+
relative_path = os.path.relpath(file_path, extract_dir)
|
97 |
+
repo_path = f"{hf_folder_prefix}/{relative_path}".replace("\\", "/")
|
98 |
+
|
99 |
+
upload_file(
|
100 |
+
path_or_fileobj=file_path,
|
101 |
+
path_in_repo=repo_path,
|
102 |
+
repo_id="rahul7star/ohamlab",
|
103 |
+
repo_type="model",
|
104 |
+
commit_message=f"Upload {relative_path} to {folder_name}",
|
105 |
+
token=True,
|
106 |
+
)
|
107 |
+
uploaded_files.append(repo_path)
|
108 |
+
|
109 |
+
return {
|
110 |
+
"message": f"✅ Uploaded {len(uploaded_files)} files",
|
111 |
+
"folder": folder_name,
|
112 |
+
"files": uploaded_files,
|
113 |
+
}
|
114 |
+
|
115 |
+
except Exception as e:
|
116 |
+
return {"error": f"❌ Failed to process zip: {str(e)}"}
|
117 |
+
|
118 |
+
|
119 |
+
# upload a single file from UI
|
120 |
+
from typing import List
|
121 |
+
from fastapi import UploadFile, File, APIRouter
|
122 |
+
import os
|
123 |
+
from fastapi import UploadFile, File, APIRouter
|
124 |
+
from typing import List
|
125 |
+
from datetime import datetime
|
126 |
+
import uuid, os
|
127 |
+
|
128 |
+
|
129 |
+
@app.post("/upload")
|
130 |
+
async def upload_images(
|
131 |
+
background_tasks: BackgroundTasks,
|
132 |
+
files: List[UploadFile] = File(...)
|
133 |
+
):
|
134 |
+
# Step 1: Generate dynamic folder name
|
135 |
+
timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
|
136 |
+
unique_id = uuid.uuid4().hex[:6]
|
137 |
+
folder_name = f"upload_{timestamp}_{unique_id}"
|
138 |
+
hf_folder_prefix = f"demo/{folder_name}"
|
139 |
+
|
140 |
+
responses = []
|
141 |
+
|
142 |
+
# Step 2: Save and upload each image
|
143 |
+
for file in files:
|
144 |
+
filename = file.filename
|
145 |
+
contents = await file.read()
|
146 |
+
temp_path = f"/tmp/{filename}"
|
147 |
+
with open(temp_path, "wb") as f:
|
148 |
+
f.write(contents)
|
149 |
+
|
150 |
+
try:
|
151 |
+
upload_file(
|
152 |
+
path_or_fileobj=temp_path,
|
153 |
+
path_in_repo=f"{hf_folder_prefix}/{filename}",
|
154 |
+
repo_id=T_REPO_ID,
|
155 |
+
repo_type="model",
|
156 |
+
commit_message=f"Upload {filename} to {hf_folder_prefix}",
|
157 |
+
token=True,
|
158 |
+
)
|
159 |
+
responses.append({
|
160 |
+
"filename": filename,
|
161 |
+
"status": "✅ uploaded",
|
162 |
+
"path": f"{hf_folder_prefix}/{filename}"
|
163 |
+
})
|
164 |
+
except Exception as e:
|
165 |
+
responses.append({
|
166 |
+
"filename": filename,
|
167 |
+
"status": f"❌ failed: {str(e)}"
|
168 |
+
})
|
169 |
+
|
170 |
+
os.remove(temp_path)
|
171 |
+
|
172 |
+
# Step 3: Add filter job to background
|
173 |
+
def run_filter():
|
174 |
+
try:
|
175 |
+
result = filter_and_rename_images(folder=hf_folder_prefix)
|
176 |
+
print(f"🧼 Filter result: {result}")
|
177 |
+
except Exception as e:
|
178 |
+
print(f"❌ Filter failed: {str(e)}")
|
179 |
+
|
180 |
+
background_tasks.add_task(run_filter)
|
181 |
+
|
182 |
+
return {
|
183 |
+
"message": f"{len(files)} file(s) uploaded",
|
184 |
+
"upload_folder": hf_folder_prefix,
|
185 |
+
"results": responses,
|
186 |
+
"note": "Filtering started in background"
|
187 |
+
}
|
188 |
+
|
189 |
+
|
190 |
+
|
191 |
+
|
192 |
+
|
193 |
+
|
194 |
+
#Tranining Data set start fitering data for traninig
|
195 |
+
|
196 |
+
|
197 |
+
T_REPO_ID = "rahul7star/ohamlab"
|
198 |
+
DESCRIPTION_TEXT = (
|
199 |
+
"Ra3hul is wearing a black jacket over a striped white t-shirt with blue jeans. "
|
200 |
+
"He is standing near a lake with his arms spread wide open, with mountains and cloudy skies in the background."
|
201 |
+
)
|
202 |
+
|
203 |
+
def is_image_file(filename: str) -> bool:
|
204 |
+
return filename.lower().endswith((".png", ".jpg", ".jpeg", ".webp"))
|
205 |
+
|
206 |
+
@app.post("/filter-images")
|
207 |
+
def filter_and_rename_images(folder: str = Query("demo", description="Folder path in repo to scan")):
|
208 |
+
try:
|
209 |
+
all_files = list_repo_files(T_REPO_ID)
|
210 |
+
folder_prefix = folder.rstrip("/") + "/"
|
211 |
+
filter_folder = f"filter-{folder.rstrip('/')}"
|
212 |
+
filter_prefix = filter_folder + "/"
|
213 |
+
|
214 |
+
# Filter images only directly in the folder (no subfolders)
|
215 |
+
image_files = [
|
216 |
+
f for f in all_files
|
217 |
+
if f.startswith(folder_prefix)
|
218 |
+
and "/" not in f[len(folder_prefix):] # no deeper path
|
219 |
+
and is_image_file(f)
|
220 |
+
]
|
221 |
+
|
222 |
+
if not image_files:
|
223 |
+
return {"error": f"No images found in folder '{folder}'"}
|
224 |
+
|
225 |
+
uploaded_files = []
|
226 |
+
|
227 |
+
for idx, orig_path in enumerate(image_files, start=1):
|
228 |
+
# Download image content bytes (uses local cache)
|
229 |
+
local_path = hf_hub_download(repo_id=T_REPO_ID, filename=orig_path)
|
230 |
+
with open(local_path, "rb") as f:
|
231 |
+
file_bytes = f.read()
|
232 |
+
|
233 |
+
# Rename images as image1.jpeg, image2.jpeg, ...
|
234 |
+
new_image_name = f"image{idx}.jpeg"
|
235 |
+
|
236 |
+
# Upload renamed image from memory
|
237 |
+
upload_file(
|
238 |
+
path_or_fileobj=io.BytesIO(file_bytes),
|
239 |
+
path_in_repo=filter_prefix + new_image_name,
|
240 |
+
repo_id=T_REPO_ID,
|
241 |
+
repo_type="model",
|
242 |
+
commit_message=f"Upload renamed image {new_image_name} to {filter_folder}",
|
243 |
+
token=True,
|
244 |
+
)
|
245 |
+
uploaded_files.append(filter_prefix + new_image_name)
|
246 |
+
|
247 |
+
# Create and upload text file for each image
|
248 |
+
txt_filename = f"image{idx}.txt"
|
249 |
+
upload_file(
|
250 |
+
path_or_fileobj=io.BytesIO(DESCRIPTION_TEXT.encode("utf-8")),
|
251 |
+
path_in_repo=filter_prefix + txt_filename,
|
252 |
+
repo_id=T_REPO_ID,
|
253 |
+
repo_type="model",
|
254 |
+
commit_message=f"Upload text file {txt_filename} to {filter_folder}",
|
255 |
+
token=True,
|
256 |
+
)
|
257 |
+
uploaded_files.append(filter_prefix + txt_filename)
|
258 |
+
|
259 |
+
return {
|
260 |
+
"message": f"Processed and uploaded {len(image_files)} images and text files.",
|
261 |
+
"files": uploaded_files,
|
262 |
+
}
|
263 |
+
|
264 |
+
except Exception as e:
|
265 |
+
return {"error": str(e)}
|
266 |
+
|
267 |
+
|
268 |
+
|
269 |
+
|
270 |
+
# Test call another space and send the payload
|
271 |
+
@app.post("/webhook-trigger")
|
272 |
+
def call_other_space():
|
273 |
+
try:
|
274 |
+
payload = {"input": "Start training from external trigger"}
|
275 |
+
|
276 |
+
res = requests.post(
|
277 |
+
"https://rahul7star-ohamlab-ai-toolkit.hf.space/trigger",
|
278 |
+
json=payload,
|
279 |
+
timeout=30,
|
280 |
+
)
|
281 |
+
|
282 |
+
# ✅ check if response has content and is JSON
|
283 |
+
try:
|
284 |
+
data = res.json()
|
285 |
+
except ValueError:
|
286 |
+
return {
|
287 |
+
"error": f"Invalid JSON response. Status: {res.status_code}",
|
288 |
+
"text": res.text
|
289 |
+
}
|
290 |
+
|
291 |
+
return data
|
292 |
+
|
293 |
+
except Exception as e:
|
294 |
+
return {"error": str(e)}
|