yukee1992 commited on
Commit
63c8dab
Β·
verified Β·
1 Parent(s): 4dc6845

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -79
app.py CHANGED
@@ -32,10 +32,17 @@ def ensure_package(package_name, import_name=None):
32
  ensure_package("gradio")
33
  ensure_package("supabase")
34
  ensure_package("python-dotenv")
 
 
35
 
36
  # Now import after ensuring they're installed
37
  import gradio as gr
38
  from supabase import create_client
 
 
 
 
 
39
 
40
  print("\n" + "=" * 60)
41
 
@@ -76,8 +83,6 @@ else:
76
  def create_project(title, content, tags, image_prompt, channel):
77
  """Create a new project and save to Supabase"""
78
  print(f"\nπŸ“ Creating project: {title}")
79
- print(f" Content length: {len(content)}")
80
- print(f" Tags: {tags}")
81
 
82
  try:
83
  # Generate proper UUID
@@ -99,27 +104,17 @@ def create_project(title, content, tags, image_prompt, channel):
99
  print(f"πŸ’Ύ Saving project with UUID: {project_id}")
100
 
101
  if supabase:
102
- try:
103
- result = supabase.table("projects").insert(project_data).execute()
104
- print(f"βœ… Saved to database! Record ID: {result.data[0]['id'] if result.data else 'unknown'}")
105
-
106
- return {
107
- "status": "success",
108
- "project_id": project_id,
109
- "folder": folder_name,
110
- "title": title,
111
- "message": "Project created successfully in database!"
112
- }
113
- except Exception as e:
114
- print(f"❌ Database error: {e}")
115
- return {
116
- "status": "error",
117
- "message": f"Database error: {str(e)}",
118
- "project_id": project_id,
119
- "folder": folder_name
120
- }
121
  else:
122
- print("⚠️ No database connection - memory only")
123
  return {
124
  "status": "memory_only",
125
  "project_id": project_id,
@@ -130,8 +125,6 @@ def create_project(title, content, tags, image_prompt, channel):
130
 
131
  except Exception as e:
132
  print(f"❌ Error: {e}")
133
- import traceback
134
- traceback.print_exc()
135
  return {"status": "error", "message": str(e)}
136
 
137
  def search_projects(term):
@@ -141,7 +134,6 @@ def search_projects(term):
141
  if not supabase:
142
  return [
143
  ["Demo Project 1", "memory", datetime.now().strftime("%Y-%m-%d"), "demo_1"],
144
- ["How to Make Videos", "demo", datetime.now().strftime("%Y-%m-%d"), "tutorial"],
145
  ]
146
 
147
  try:
@@ -185,23 +177,16 @@ def health_check():
185
  }
186
 
187
  # =============================================
188
- # FASTAPI ROUTES (Direct API endpoints)
189
  # =============================================
190
 
191
- from fastapi import FastAPI, Request
192
- from fastapi.responses import JSONResponse
193
- import uvicorn
194
- import threading
195
-
196
- # Create FastAPI app
197
- fastapi_app = FastAPI()
198
 
199
- @fastapi_app.post("/api/create")
200
  async def api_create(request: Request):
201
  """Direct API endpoint for creating projects"""
202
  try:
203
  data = await request.json()
204
- # Extract data from the request
205
  if "data" in data and len(data["data"]) >= 5:
206
  result = create_project(
207
  data["data"][0],
@@ -210,11 +195,11 @@ async def api_create(request: Request):
210
  data["data"][3],
211
  data["data"][4]
212
  )
213
- return JSONResponse(content={"data": [result]})
214
  else:
215
  return JSONResponse(
216
  status_code=400,
217
- content={"error": "Invalid data format"}
218
  )
219
  except Exception as e:
220
  return JSONResponse(
@@ -222,27 +207,32 @@ async def api_create(request: Request):
222
  content={"error": str(e)}
223
  )
224
 
225
- @fastapi_app.post("/api/health")
226
  async def api_health():
227
  """Health check endpoint"""
228
  return JSONResponse(content=health_check())
229
 
230
- @fastapi_app.post("/api/search")
231
  async def api_search(request: Request):
232
  """Search endpoint"""
233
  try:
234
  data = await request.json()
235
  term = data.get("data", [""])[0] if data.get("data") else ""
236
  result = search_projects(term)
237
- return JSONResponse(content={"data": [result]})
238
  except Exception as e:
239
  return JSONResponse(
240
  status_code=500,
241
  content={"error": str(e)}
242
  )
243
 
 
 
 
 
 
244
  # =============================================
245
- # GRADIO INTERFACE
246
  # =============================================
247
 
248
  print("\nπŸ“ Creating Gradio interface...")
@@ -250,14 +240,12 @@ print("\nπŸ“ Creating Gradio interface...")
250
  with gr.Blocks(title="Video Project Manager") as demo:
251
  gr.Markdown("# 🎬 Video Project Manager")
252
 
253
- # Status indicator
254
  if supabase:
255
  gr.Markdown("### βœ… Connected to Supabase")
256
  else:
257
  gr.Markdown("### ⚠️ Running in Memory Mode (No Database)")
258
 
259
  with gr.Tabs():
260
- # Create Project Tab
261
  with gr.TabItem("πŸ“ Create Project"):
262
  with gr.Row():
263
  with gr.Column():
@@ -272,7 +260,6 @@ with gr.Blocks(title="Video Project Manager") as demo:
272
  with gr.Column():
273
  output = gr.JSON(label="Result")
274
 
275
- # Search Tab
276
  with gr.TabItem("πŸ” Search"):
277
  search_input = gr.Textbox(label="Search Term", placeholder="Enter search term")
278
  search_btn = gr.Button("πŸ” Search", variant="secondary")
@@ -281,7 +268,6 @@ with gr.Blocks(title="Video Project Manager") as demo:
281
  label="Search Results"
282
  )
283
 
284
- # API Info Tab
285
  with gr.TabItem("πŸ“š API Info"):
286
  gr.Markdown("""
287
  ## API Endpoints
@@ -299,13 +285,6 @@ with gr.Blocks(title="Video Project Manager") as demo:
299
  -H "Content-Type: application/json" \\
300
  -d '{}'
301
  ```
302
-
303
- ### Search
304
- ```bash
305
- curl -X POST "https://yukee1992-video-project-manager.hf.space/api/search" \\
306
- -H "Content-Type: application/json" \\
307
- -d '{"data": ["search term"]}'
308
- ```
309
  """)
310
 
311
  # Gradio event handlers
@@ -320,37 +299,21 @@ with gr.Blocks(title="Video Project Manager") as demo:
320
  inputs=[search_input],
321
  outputs=[results]
322
  )
323
-
324
- print("βœ… Gradio interface created")
325
 
326
- # =============================================
327
- # RUN BOTH FASTAPI AND GRADIO
328
- # =============================================
329
-
330
- def run_fastapi():
331
- """Run FastAPI server in a separate thread"""
332
- uvicorn.run(fastapi_app, host="0.0.0.0", port=8000)
333
 
334
- def run_gradio():
335
- """Run Gradio interface"""
336
- demo.launch(
337
- server_name="0.0.0.0",
338
- server_port=7860,
339
- share=False,
340
- debug=True
341
- )
342
 
 
 
 
343
  if __name__ == "__main__":
344
  print("\n" + "=" * 60)
345
- print("🌐 Launching servers...")
346
- print(" - Gradio UI: http://0.0.0.0:7860")
347
- print(" - FastAPI: http://0.0.0.0:8000")
348
- print(" - API endpoints: /api/create, /api/health, /api/search")
349
  print("=" * 60)
350
 
351
- # Start FastAPI in a thread
352
- fastapi_thread = threading.Thread(target=run_fastapi, daemon=True)
353
- fastapi_thread.start()
354
-
355
- # Start Gradio in main thread
356
- run_gradio()
 
32
  ensure_package("gradio")
33
  ensure_package("supabase")
34
  ensure_package("python-dotenv")
35
+ ensure_package("fastapi")
36
+ ensure_package("uvicorn")
37
 
38
  # Now import after ensuring they're installed
39
  import gradio as gr
40
  from supabase import create_client
41
+ from fastapi import FastAPI, Request
42
+ from fastapi.responses import JSONResponse
43
+ import uvicorn
44
+ from threading import Thread
45
+ import time
46
 
47
  print("\n" + "=" * 60)
48
 
 
83
  def create_project(title, content, tags, image_prompt, channel):
84
  """Create a new project and save to Supabase"""
85
  print(f"\nπŸ“ Creating project: {title}")
 
 
86
 
87
  try:
88
  # Generate proper UUID
 
104
  print(f"πŸ’Ύ Saving project with UUID: {project_id}")
105
 
106
  if supabase:
107
+ result = supabase.table("projects").insert(project_data).execute()
108
+ print(f"βœ… Saved to database!")
109
+
110
+ return {
111
+ "status": "success",
112
+ "project_id": project_id,
113
+ "folder": folder_name,
114
+ "title": title,
115
+ "message": "Project created successfully in database!"
116
+ }
 
 
 
 
 
 
 
 
 
117
  else:
 
118
  return {
119
  "status": "memory_only",
120
  "project_id": project_id,
 
125
 
126
  except Exception as e:
127
  print(f"❌ Error: {e}")
 
 
128
  return {"status": "error", "message": str(e)}
129
 
130
  def search_projects(term):
 
134
  if not supabase:
135
  return [
136
  ["Demo Project 1", "memory", datetime.now().strftime("%Y-%m-%d"), "demo_1"],
 
137
  ]
138
 
139
  try:
 
177
  }
178
 
179
  # =============================================
180
+ # CREATE FASTAPI APP
181
  # =============================================
182
 
183
+ app = FastAPI()
 
 
 
 
 
 
184
 
185
+ @app.post("/api/create")
186
  async def api_create(request: Request):
187
  """Direct API endpoint for creating projects"""
188
  try:
189
  data = await request.json()
 
190
  if "data" in data and len(data["data"]) >= 5:
191
  result = create_project(
192
  data["data"][0],
 
195
  data["data"][3],
196
  data["data"][4]
197
  )
198
+ return JSONResponse(content=result)
199
  else:
200
  return JSONResponse(
201
  status_code=400,
202
+ content={"error": "Invalid data format. Expected: {\"data\": [title, content, tags, prompt, channel]}"}
203
  )
204
  except Exception as e:
205
  return JSONResponse(
 
207
  content={"error": str(e)}
208
  )
209
 
210
+ @app.post("/api/health")
211
  async def api_health():
212
  """Health check endpoint"""
213
  return JSONResponse(content=health_check())
214
 
215
+ @app.post("/api/search")
216
  async def api_search(request: Request):
217
  """Search endpoint"""
218
  try:
219
  data = await request.json()
220
  term = data.get("data", [""])[0] if data.get("data") else ""
221
  result = search_projects(term)
222
+ return JSONResponse(content={"results": result})
223
  except Exception as e:
224
  return JSONResponse(
225
  status_code=500,
226
  content={"error": str(e)}
227
  )
228
 
229
+ @app.get("/")
230
+ async def root():
231
+ """Root endpoint redirects to Gradio"""
232
+ return {"message": "Video Project Manager API. Use /api/ endpoints. Access UI at /gradio"}
233
+
234
  # =============================================
235
+ # MOUNT GRADIO APP TO FASTAPI
236
  # =============================================
237
 
238
  print("\nπŸ“ Creating Gradio interface...")
 
240
  with gr.Blocks(title="Video Project Manager") as demo:
241
  gr.Markdown("# 🎬 Video Project Manager")
242
 
 
243
  if supabase:
244
  gr.Markdown("### βœ… Connected to Supabase")
245
  else:
246
  gr.Markdown("### ⚠️ Running in Memory Mode (No Database)")
247
 
248
  with gr.Tabs():
 
249
  with gr.TabItem("πŸ“ Create Project"):
250
  with gr.Row():
251
  with gr.Column():
 
260
  with gr.Column():
261
  output = gr.JSON(label="Result")
262
 
 
263
  with gr.TabItem("πŸ” Search"):
264
  search_input = gr.Textbox(label="Search Term", placeholder="Enter search term")
265
  search_btn = gr.Button("πŸ” Search", variant="secondary")
 
268
  label="Search Results"
269
  )
270
 
 
271
  with gr.TabItem("πŸ“š API Info"):
272
  gr.Markdown("""
273
  ## API Endpoints
 
285
  -H "Content-Type: application/json" \\
286
  -d '{}'
287
  ```
 
 
 
 
 
 
 
288
  """)
289
 
290
  # Gradio event handlers
 
299
  inputs=[search_input],
300
  outputs=[results]
301
  )
 
 
302
 
303
+ print("βœ… Gradio interface created")
 
 
 
 
 
 
304
 
305
+ # Mount Gradio app to FastAPI
306
+ app = gr.mount_gradio_app(app, demo, path="/")
 
 
 
 
 
 
307
 
308
+ # =============================================
309
+ # RUN
310
+ # =============================================
311
  if __name__ == "__main__":
312
  print("\n" + "=" * 60)
313
+ print("🌐 Starting server on port 7860...")
314
+ print(" - UI: https://yukee1992-video-project-manager.hf.space")
315
+ print(" - API: https://yukee1992-video-project-manager.hf.space/api/")
316
+ print(" - Endpoints: /api/create, /api/health, /api/search")
317
  print("=" * 60)
318
 
319
+ uvicorn.run(app, host="0.0.0.0", port=7860)