SAVAI123 commited on
Commit
8866c4b
·
verified ·
1 Parent(s): 7519a0a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -37
app.py CHANGED
@@ -1,9 +1,8 @@
1
  import os
2
  import torch
3
- import legacy
4
  import numpy as np
5
  import PIL.Image
6
- from flask import Flask, request, render_template, send_file
7
  from werkzeug.utils import secure_filename
8
 
9
  # Set up Flask app
@@ -18,60 +17,96 @@ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
18
  os.makedirs(RESULT_FOLDER, exist_ok=True)
19
 
20
  # Load StyleGAN3 Model
21
- network_pkl = "models/stylegan3-r-ffhq-1024x1024.pkl"
22
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
23
-
24
- print(f'Loading networks from "{network_pkl}"...')
25
- with open(network_pkl, "rb") as f:
26
- G = legacy.load_network_pkl(f)["G_ema"].to(device)
 
 
 
 
 
 
 
 
 
27
 
28
  # Function to encode an image into latent space
29
  def image_to_latent(image_path):
 
 
30
  latent_vector = torch.randn(1, G.z_dim, device=device) # Generate random latent vector
31
  return latent_vector
32
 
33
  # Function to modify latent code to make the face look younger
34
  def modify_age(latent_vector, age_factor=-2.0):
35
- age_direction = torch.load("models/age_direction.pt").to(device) # Load precomputed age direction
36
- new_latent_vector = latent_vector + age_factor * age_direction
37
- return new_latent_vector
 
 
 
 
38
 
39
  # Function to generate an image from a latent code
40
  def generate_image(latent_vector):
41
- img = G.synthesis(latent_vector, noise_mode="const")
42
- img = (img + 1) * (255 / 2)
43
- img = img.permute(0, 2, 3, 1).cpu().numpy()[0].astype(np.uint8)
44
- return PIL.Image.fromarray(img)
 
 
 
 
 
45
 
46
  # Flask Routes
47
  @app.route("/", methods=["GET", "POST"])
48
  def upload_file():
 
 
 
 
 
49
  if request.method == "POST":
50
  if "file" not in request.files:
51
- return "No file uploaded", 400
52
 
53
  file = request.files["file"]
54
  if file.filename == "":
55
- return "No selected file", 400
56
-
57
- filename = secure_filename(file.filename)
58
- input_path = os.path.join(app.config["UPLOAD_FOLDER"], filename)
59
- file.save(input_path)
60
-
61
- # Convert input image to latent vector
62
- latent_code = image_to_latent(input_path)
63
-
64
- # Modify latent code for a younger appearance
65
- young_latent_code = modify_age(latent_code, age_factor=-2.0)
66
-
67
- # Generate a younger-looking face
68
- young_image = generate_image(young_latent_code)
69
- output_path = os.path.join(app.config["RESULT_FOLDER"], "young_" + filename)
70
- young_image.save(output_path)
71
-
72
- return render_template("result.html", filename="young_" + filename)
73
-
74
- return render_template("index.html")
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  @app.route("/download/<filename>")
77
  def download_file(filename):
@@ -79,4 +114,4 @@ def download_file(filename):
79
 
80
  # Run the Flask app
81
  if __name__ == "__main__":
82
- app.run(debug=True)
 
1
  import os
2
  import torch
 
3
  import numpy as np
4
  import PIL.Image
5
+ from flask import Flask, request, render_template, send_file, url_for
6
  from werkzeug.utils import secure_filename
7
 
8
  # Set up Flask app
 
17
  os.makedirs(RESULT_FOLDER, exist_ok=True)
18
 
19
  # Load StyleGAN3 Model
20
+ try:
21
+ import legacy
22
+
23
+ network_pkl = "models/stylegan3-r-ffhq-1024x1024.pkl"
24
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
25
+ print(f'Loading networks from "{network_pkl}"...')
26
+
27
+ with open(network_pkl, "rb") as f:
28
+ G = legacy.load_network_pkl(f)["G_ema"].to(device)
29
+
30
+ model_loaded = True
31
+ print("StyleGAN3 model loaded successfully!")
32
+ except Exception as e:
33
+ print(f"Error loading StyleGAN3 model: {e}")
34
+ model_loaded = False
35
 
36
  # Function to encode an image into latent space
37
  def image_to_latent(image_path):
38
+ # Note: This is a simplified version. Actual image encoding to latent space
39
+ # requires techniques like optimization or encoder networks
40
  latent_vector = torch.randn(1, G.z_dim, device=device) # Generate random latent vector
41
  return latent_vector
42
 
43
  # Function to modify latent code to make the face look younger
44
  def modify_age(latent_vector, age_factor=-2.0):
45
+ try:
46
+ age_direction = torch.load("models/age_direction.pt").to(device) # Load precomputed age direction
47
+ new_latent_vector = latent_vector + age_factor * age_direction
48
+ return new_latent_vector
49
+ except Exception as e:
50
+ print(f"Error modifying age: {e}")
51
+ return latent_vector # Return original if error
52
 
53
  # Function to generate an image from a latent code
54
  def generate_image(latent_vector):
55
+ try:
56
+ img = G.synthesis(latent_vector, noise_mode="const")
57
+ img = (img + 1) * (255 / 2)
58
+ img = img.permute(0, 2, 3, 1).cpu().numpy()[0].astype(np.uint8)
59
+ return PIL.Image.fromarray(img)
60
+ except Exception as e:
61
+ print(f"Error generating image: {e}")
62
+ # Return a blank image if there's an error
63
+ return PIL.Image.new('RGB', (1024, 1024), color = (255, 255, 255))
64
 
65
  # Flask Routes
66
  @app.route("/", methods=["GET", "POST"])
67
  def upload_file():
68
+ error_message = None
69
+
70
+ if not model_loaded:
71
+ error_message = "StyleGAN3 model could not be loaded. Please check the server logs."
72
+
73
  if request.method == "POST":
74
  if "file" not in request.files:
75
+ return render_template("index.html", error="No file uploaded")
76
 
77
  file = request.files["file"]
78
  if file.filename == "":
79
+ return render_template("index.html", error="No selected file")
80
+
81
+ if not model_loaded:
82
+ return render_template("index.html", error=error_message)
83
+
84
+ try:
85
+ filename = secure_filename(file.filename)
86
+ input_path = os.path.join(app.config["UPLOAD_FOLDER"], filename)
87
+ file.save(input_path)
88
+
89
+ # Convert input image to latent vector
90
+ latent_code = image_to_latent(input_path)
91
+
92
+ # Modify latent code for a younger appearance
93
+ young_latent_code = modify_age(latent_code, age_factor=-2.0)
94
+
95
+ # Generate a younger-looking face
96
+ young_image = generate_image(young_latent_code)
97
+ output_path = os.path.join(app.config["RESULT_FOLDER"], "young_" + filename)
98
+ young_image.save(output_path)
99
+
100
+ return render_template("result.html", filename="young_" + filename)
101
+ except Exception as e:
102
+ error_message = f"Error processing image: {str(e)}"
103
+ return render_template("index.html", error=error_message)
104
+
105
+ return render_template("index.html", error=error_message)
106
+
107
+ @app.route("/results/<filename>")
108
+ def display_image(filename):
109
+ return send_file(os.path.join(app.config["RESULT_FOLDER"], filename))
110
 
111
  @app.route("/download/<filename>")
112
  def download_file(filename):
 
114
 
115
  # Run the Flask app
116
  if __name__ == "__main__":
117
+ app.run(debug=True, host="0.0.0.0")