SaniaE commited on
Commit
f358dc8
·
verified ·
1 Parent(s): 602f302

updated app.py to support new model checkpoint

Browse files
Files changed (1) hide show
  1. app.py +38 -46
app.py CHANGED
@@ -1,14 +1,14 @@
1
  import os
2
  import io
 
3
  import torch
4
- from torch import nn
5
  from PIL import Image
6
  import torchvision.utils as vutils
7
  from fastapi import FastAPI, Response, HTTPException, Query
8
  from fastapi.responses import StreamingResponse
9
  from fastapi.middleware.cors import CORSMiddleware
10
  from huggingface_hub import hf_hub_download, login
11
-
12
  from models import Generator
13
 
14
  app = FastAPI()
@@ -16,7 +16,7 @@ app = FastAPI()
16
  # CORS Configuration
17
  app.add_middleware(
18
  CORSMiddleware,
19
- allow_origins=["*"],
20
  allow_methods=["*"],
21
  allow_headers=["*"],
22
  )
@@ -26,8 +26,6 @@ Z_DIM = 100
26
  DEVICE = torch.device("cpu")
27
  REPO_ID = "SaniaE/GeoGen"
28
  FILENAME = "dcgans_model_checkpoint.pth"
29
-
30
- # Global model variable
31
  gen_model = None
32
 
33
  @app.on_event("startup")
@@ -40,41 +38,30 @@ def load_model():
40
  print("Login successful.")
41
  else:
42
  print("No HF_TOKEN found - attempting public download.")
43
-
44
  model_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME, token=token)
45
  print(f"File downloaded to: {model_path}")
46
-
47
  checkpoint = torch.load(model_path, map_location=DEVICE)
48
 
49
  gen_model = Generator(z_dim=Z_DIM).to(DEVICE)
50
  missing, unexpected = gen_model.load_state_dict(
51
  checkpoint["gen_state_dict"], strict=False
52
  )
53
-
54
  print("Unexpected keys: ", unexpected)
55
  print("Missing keys: ", missing)
 
56
  gen_model.eval()
57
  print("SUCCESS: Petrol Pump GAN is live!")
58
  except Exception as e:
59
  print(f"Error loading model: {e}")
60
 
61
-
62
- def postprocess_image(tensor):
63
- # Unnormalize: tanh output [-1, 1] -> [0, 1]
64
- img_tensor = (tensor + 1) / 2
65
- img_tensor = img_tensor.clamp(0, 1)
66
-
67
- grid = vutils.make_grid(img_tensor, padding=0, normalize=False)
68
-
69
- ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy()
70
- return Image.fromarray(ndarr)
71
-
72
-
73
  def get_image_stream(tensor):
74
  """Helper to convert tensor to a streaming-ready PNG."""
75
  img_tensor = (tensor + 1) / 2
76
  img_tensor = img_tensor.clamp(0, 1)
77
  grid = vutils.make_grid(img_tensor, padding=0)
 
78
  ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy()
79
 
80
  pil_img = Image.fromarray(ndarr)
@@ -83,50 +70,55 @@ def get_image_stream(tensor):
83
  buf.seek(0)
84
  return buf
85
 
86
-
87
  @app.get("/")
88
  def read_root():
89
  return {"status": "online", "model": REPO_ID}
90
 
91
-
92
  @app.get("/generate")
93
  def generate_random(seed: int = Query(None)):
94
  """Endpoint 1: Fixed context generation for a session."""
95
- if gen_model is None: raise HTTPException(status_code=503)
96
-
97
- # Use the provided session seed or fallback to random
98
- active_seed = seed if seed is not None else torch.seed()
99
  torch.manual_seed(active_seed)
100
-
101
  with torch.inference_mode():
102
  noise = torch.randn(1, Z_DIM, device=DEVICE)
103
  fake_img = gen_model(noise)
104
  return StreamingResponse(get_image_stream(fake_img), media_type="image/png")
105
 
106
-
107
  @app.get("/explore")
108
- def explore_latent(seed: int, x_shift: float = Query(0.0, ge=-5.0, le=5.0), y_shift: float = Query(0.0, ge=-5.0, le=5.0)):
109
- """Endpoint 2: Controlled generation for 'Tuning'."""
110
- if gen_model is None: raise HTTPException(status_code=503)
111
-
 
 
 
 
 
112
  try:
113
  with torch.inference_mode():
114
  torch.manual_seed(seed)
115
- if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)
116
-
 
117
  noise = torch.randn(1, Z_DIM, device=DEVICE)
118
-
119
- # Structured control
120
- noise[:, :10] += x_shift
121
- noise[:, 10:20] += y_shift
122
-
123
- # Random direction
124
- direction = torch.randn_like(noise)
125
- noise = noise + 0.3 * direction * (abs(x_shift) + abs(y_shift))
126
-
127
- print("NOISE:", noise[0, :5])
128
- fake_img = gen_model(noise)
129
- return StreamingResponse(get_image_stream(fake_img), media_type="image/png")
130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  except Exception as e:
132
  raise HTTPException(status_code=500, detail=str(e))
 
1
  import os
2
  import io
3
+ import random
4
  import torch
5
+ from torch import nn
6
  from PIL import Image
7
  import torchvision.utils as vutils
8
  from fastapi import FastAPI, Response, HTTPException, Query
9
  from fastapi.responses import StreamingResponse
10
  from fastapi.middleware.cors import CORSMiddleware
11
  from huggingface_hub import hf_hub_download, login
 
12
  from models import Generator
13
 
14
  app = FastAPI()
 
16
  # CORS Configuration
17
  app.add_middleware(
18
  CORSMiddleware,
19
+ allow_origins=["*"],
20
  allow_methods=["*"],
21
  allow_headers=["*"],
22
  )
 
26
  DEVICE = torch.device("cpu")
27
  REPO_ID = "SaniaE/GeoGen"
28
  FILENAME = "dcgans_model_checkpoint.pth"
 
 
29
  gen_model = None
30
 
31
  @app.on_event("startup")
 
38
  print("Login successful.")
39
  else:
40
  print("No HF_TOKEN found - attempting public download.")
41
+
42
  model_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME, token=token)
43
  print(f"File downloaded to: {model_path}")
44
+
45
  checkpoint = torch.load(model_path, map_location=DEVICE)
46
 
47
  gen_model = Generator(z_dim=Z_DIM).to(DEVICE)
48
  missing, unexpected = gen_model.load_state_dict(
49
  checkpoint["gen_state_dict"], strict=False
50
  )
 
51
  print("Unexpected keys: ", unexpected)
52
  print("Missing keys: ", missing)
53
+
54
  gen_model.eval()
55
  print("SUCCESS: Petrol Pump GAN is live!")
56
  except Exception as e:
57
  print(f"Error loading model: {e}")
58
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  def get_image_stream(tensor):
60
  """Helper to convert tensor to a streaming-ready PNG."""
61
  img_tensor = (tensor + 1) / 2
62
  img_tensor = img_tensor.clamp(0, 1)
63
  grid = vutils.make_grid(img_tensor, padding=0)
64
+
65
  ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy()
66
 
67
  pil_img = Image.fromarray(ndarr)
 
70
  buf.seek(0)
71
  return buf
72
 
 
73
  @app.get("/")
74
  def read_root():
75
  return {"status": "online", "model": REPO_ID}
76
 
 
77
  @app.get("/generate")
78
  def generate_random(seed: int = Query(None)):
79
  """Endpoint 1: Fixed context generation for a session."""
80
+ if gen_model is None:
81
+ raise HTTPException(status_code=503, detail="Model not loaded")
82
+
83
+ active_seed = seed if seed is not None else random.randint(0, 2147483647)
84
  torch.manual_seed(active_seed)
85
+
86
  with torch.inference_mode():
87
  noise = torch.randn(1, Z_DIM, device=DEVICE)
88
  fake_img = gen_model(noise)
89
  return StreamingResponse(get_image_stream(fake_img), media_type="image/png")
90
 
 
91
  @app.get("/explore")
92
+ def explore_latent(
93
+ seed: int,
94
+ x_shift: float = Query(0.0, ge=-5.0, le=5.0),
95
+ y_shift: float = Query(0.0, ge=-5.0, le=5.0)
96
+ ):
97
+ """Endpoint 2: Controlled generation for 'Tuning' using stable normalized steering vectors."""
98
+ if gen_model is None:
99
+ raise HTTPException(status_code=503, detail="Model not loaded")
100
+
101
  try:
102
  with torch.inference_mode():
103
  torch.manual_seed(seed)
104
+ if torch.cuda.is_available():
105
+ torch.cuda.manual_seed_all(seed)
106
+
107
  noise = torch.randn(1, Z_DIM, device=DEVICE)
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
+ gen_x = torch.Generator(device=DEVICE).manual_seed(seed + 101)
110
+ dir_x = torch.randn(1, Z_DIM, generator=gen_x, device=DEVICE)
111
+ dir_x = dir_x / dir_x.norm()
112
+
113
+ gen_y = torch.Generator(device=DEVICE).manual_seed(seed + 202)
114
+ dir_y = torch.randn(1, Z_DIM, generator=gen_y, device=DEVICE)
115
+ dir_y = dir_y / dir_y.norm()
116
+
117
+ # Apply controlled linear shifts along the unit directions
118
+ steered_noise = noise + (x_shift * dir_x) + (y_shift * dir_y)
119
+
120
+ fake_img = gen_model(steered_noise)
121
+ return StreamingResponse(get_image_stream(fake_img), media_type="image/png")
122
+
123
  except Exception as e:
124
  raise HTTPException(status_code=500, detail=str(e))