sandhyasinha655 commited on
Commit
bd22fbe
·
verified ·
1 Parent(s): 04053a0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -79
app.py CHANGED
@@ -1,106 +1,85 @@
1
  import gradio as gr
2
  import os
3
  import sys
4
- import base64
5
- import uuid
6
- from fastapi import FastAPI
7
 
8
- # -------------------------------------------------------------------
9
- # PART 1: CORE LOGIC (Yeh bilkul perfect hai, ismein koi change nahi)
10
- # -------------------------------------------------------------------
11
  sys.path.append('roop')
12
  from roop.core import run as roop_run
13
 
14
- def face_swap_logic(source_path, target_path):
 
 
 
 
 
 
 
15
  output_filename = os.path.basename(target_path)
16
  os.makedirs("output", exist_ok=True)
17
- output_path = os.path.join("output", f"api_result_{output_filename}")
18
 
19
  args = [
20
- "run.py", "--source", source_path, "--target", target_path,
21
- "--output", output_path, "--execution-provider", "cpu",
 
 
 
22
  ]
23
  sys.argv = args
24
 
 
 
25
  try:
26
  roop_run()
27
- except SystemExit: pass
 
28
  except Exception as e:
29
- print(f"Face swap fail hua. Error: {str(e)}")
30
- return None
31
 
32
  if not os.path.exists(output_path):
33
- return None
34
-
 
35
  return output_path
36
 
37
- # -------------------------------------------------------------------
38
- # PART 2: GRADIO UI DEFINITION (Aapka Web Interface)
39
- # -------------------------------------------------------------------
40
- with gr.Blocks(theme=gr.themes.Soft()) as gradio_ui:
41
  gr.Markdown("# 🎭 Roop Face Swap AI")
 
 
 
 
 
 
42
  with gr.Tabs():
 
43
  with gr.TabItem("🖼️ Swap on Image"):
44
- # ... (UI ka baaki code bilkul same)
45
- with gr.Row():
46
- source_face_img = gr.Image(label="Source Face", type="filepath")
47
- target_image = gr.Image(label="Target Image", type="filepath")
48
- submit_btn_image = gr.Button("Swap Face on Image")
49
- result_image = gr.Image(label="Result Image")
50
 
 
51
  with gr.TabItem("🎬 Swap on Video"):
52
- with gr.Row():
53
- source_face_vid = gr.Image(label="Source Face", type="filepath")
54
- target_video = gr.Video(label="Target Video")
55
- submit_btn_video = gr.Button("Swap Face on Video")
56
- result_video = gr.Video(label="Result Video")
57
-
58
- # UI ke buttons ko logic se jodna
59
- submit_btn_image.click(fn=face_swap_logic, inputs=[source_face_img, target_image], outputs=result_image)
60
- submit_btn_video.click(fn=face_swap_logic, inputs=[source_face_vid, target_video], outputs=result_video)
61
-
62
- # -------------------------------------------------------------------
63
- # PART 3: FASTAPI APP DEFINITION (Aapke Android App ke liye)
64
- # -------------------------------------------------------------------
65
- # Yahan hum main app banayenge jo Hugging Face chalaayega
66
- app = FastAPI()
67
-
68
- def save_base64_to_file(b64_string, extension):
69
- filename = f"/tmp/{uuid.uuid4().hex}.{extension}"
70
- with open(filename, "wb") as f:
71
- f.write(base64.b64decode(b64_string))
72
- return filename
73
-
74
- # API ka darwaza
75
- @app.post("/api/swap-face")
76
- async def api_face_swap(payload: dict):
77
- source_b64 = payload.get("source_face_b64")
78
- target_b64 = payload.get("target_media_b64")
79
- target_ext = payload.get("target_ext", "jpg")
80
-
81
- if not source_b64 or not target_b64:
82
- return {"error": "Source ya Target file nahi mili."}
83
-
84
- source_file_path = save_base64_to_file(source_b64, "jpg")
85
- target_file_path = save_base64_to_file(target_b64, target_ext)
86
-
87
- result_path = face_swap_logic(source_file_path, target_file_path)
88
-
89
- if result_path:
90
- with open(result_path, "rb") as f:
91
- result_b64 = base64.b64encode(f.read()).decode("utf-8")
92
-
93
- os.remove(source_file_path)
94
- os.remove(target_file_path)
95
- os.remove(result_path)
96
- return {"result_b64": result_b64}
97
- else:
98
- return {"error": "Face swap fail hua."}
99
-
100
- # -------------------------------------------------------------------
101
- # PART 4: MOUNTING (Dono ko Jodna)
102
- # -------------------------------------------------------------------
103
- # Yeh aakhri line Gradio UI (gradio_ui) ko FastAPI app (app) ke upar mount karti hai
104
- app = gr.mount_gradio_app(app, gradio_ui, path="/")
105
 
106
- # Ismein app.launch() ki zaroorat nahi hoti. Hugging Face khud 'app' object ko chala leta hai.
 
1
  import gradio as gr
2
  import os
3
  import sys
 
 
 
4
 
 
 
 
5
  sys.path.append('roop')
6
  from roop.core import run as roop_run
7
 
8
+ # CORE LOGIC - ISMEIN KOI BHI CHANGE NAHI HUA HAI. YEH PERFECT HAI.
9
+ def face_swap(source_img, target_media, progress=gr.Progress(track_tqdm=True)):
10
+ if source_img is None or target_media is None:
11
+ raise gr.Error("Dono file upload karein.")
12
+
13
+ source_path = source_img
14
+ target_path = target_media
15
+
16
  output_filename = os.path.basename(target_path)
17
  os.makedirs("output", exist_ok=True)
18
+ output_path = os.path.join("output", f"result_{output_filename}")
19
 
20
  args = [
21
+ "run.py",
22
+ "--source", source_path,
23
+ "--target", target_path,
24
+ "--output", output_path,
25
+ "--execution-provider", "cpu",
26
  ]
27
  sys.argv = args
28
 
29
+ print(f"Running roop with args: {sys.argv}")
30
+
31
  try:
32
  roop_run()
33
+ except SystemExit:
34
+ pass
35
  except Exception as e:
36
+ raise gr.Error(f"Face swap fail hua. Error: {str(e)}")
 
37
 
38
  if not os.path.exists(output_path):
39
+ raise gr.Error("Processing fail hua. Model download nahi ho paaya ya koi aur error aayi. Logs check karein.")
40
+
41
+ print(f"Process poora hua. Result yahan hai: {output_path}")
42
  return output_path
43
 
44
+ # --- Gradio UI (AAPKE IDEA KE SAATH) ---
45
+ with gr.Blocks(theme=gr.themes.Soft()) as app:
 
 
46
  gr.Markdown("# 🎭 Roop Face Swap AI")
47
+
48
+ # Step 1: Source Face (Yeh dono tabs ke liye common rahega)
49
+ gr.Markdown("### Step 1: Upload Source Face")
50
+ source_face = gr.Image(label="Source Face (Jiska Chehra Lagana Hai)", type="filepath")
51
+
52
+ # Step 2: Alag-alag Tabs banana (Image aur Video ke liye)
53
  with gr.Tabs():
54
+ # TAB 1: IMAGE KE LIYE
55
  with gr.TabItem("🖼️ Swap on Image"):
56
+ gr.Markdown("### Step 2: Upload Target Image")
57
+ target_image = gr.Image(label="Target Image (Jispar Chehra Lagana Hai)", type="filepath")
58
+ submit_btn_image = gr.Button("Swap Face on Image", variant="primary")
59
+ gr.Markdown("### Step 3: Result")
60
+ result_image = gr.Image(label="Result Image", interactive=False)
 
61
 
62
+ # TAB 2: VIDEO KE LIYE
63
  with gr.TabItem("🎬 Swap on Video"):
64
+ gr.Markdown("### Step 2: Upload Target Video")
65
+ target_video = gr.Video(label="Target Video (Jispar Chehra Lagana Hai)")
66
+ submit_btn_video = gr.Button("Swap Face on Video", variant="primary")
67
+ gr.Markdown("### Step 3: Result")
68
+ result_video = gr.Video(label="Result Video", interactive=False)
69
+
70
+ # Dono buttons ke liye alag-alag click event
71
+ # Yeh dono event ek hi 'face_swap' function ko call karte hain
72
+
73
+ submit_btn_image.click(
74
+ fn=face_swap,
75
+ inputs=[source_face, target_image],
76
+ outputs=result_image
77
+ )
78
+
79
+ submit_btn_video.click(
80
+ fn=face_swap,
81
+ inputs=[source_face, target_video],
82
+ outputs=result_video
83
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
+ app.launch()