saniaE commited on
Commit
602f302
·
2 Parent(s): c934f16cb1158f

Merge branch 'main' of https://huggingface.co/spaces/SaniaE/GeoGen-API into main

Browse files
Files changed (1) hide show
  1. app.py +23 -16
app.py CHANGED
@@ -47,9 +47,14 @@ def load_model():
47
  checkpoint = torch.load(model_path, map_location=DEVICE)
48
 
49
  gen_model = Generator(z_dim=Z_DIM).to(DEVICE)
50
- gen_model.load_state_dict(checkpoint["gen_state_dict"], strict=False)
 
 
 
 
 
51
  gen_model.eval()
52
- print("✅ SUCCESS: Petrol Pump GAN is live!")
53
  except Exception as e:
54
  print(f"Error loading model: {e}")
55
 
@@ -59,10 +64,8 @@ def postprocess_image(tensor):
59
  img_tensor = (tensor + 1) / 2
60
  img_tensor = img_tensor.clamp(0, 1)
61
 
62
- # Use make_grid to handle single or batch images
63
  grid = vutils.make_grid(img_tensor, padding=0, normalize=False)
64
 
65
- # Convert to HWC format for PIL
66
  ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy()
67
  return Image.fromarray(ndarr)
68
 
@@ -87,10 +90,14 @@ def read_root():
87
 
88
 
89
  @app.get("/generate")
90
- def generate_random():
91
- """Endpoint 1: Purely random generation for 'Discovery'."""
92
  if gen_model is None: raise HTTPException(status_code=503)
93
 
 
 
 
 
94
  with torch.inference_mode():
95
  noise = torch.randn(1, Z_DIM, device=DEVICE)
96
  fake_img = gen_model(noise)
@@ -98,26 +105,26 @@ def generate_random():
98
 
99
 
100
  @app.get("/explore")
101
- def explore_latent(
102
- seed: int,
103
- x_shift: float = Query(0.0, ge=-5.0, le=5.0),
104
- y_shift: float = Query(0.0, ge=-5.0, le=5.0)
105
- ):
106
  """Endpoint 2: Controlled generation for 'Tuning'."""
107
  if gen_model is None: raise HTTPException(status_code=503)
108
 
109
  try:
110
  with torch.inference_mode():
111
- # Use the seed to recreate the base 'personality' of the image
112
  torch.manual_seed(seed)
113
  if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)
114
-
115
  noise = torch.randn(1, Z_DIM, device=DEVICE)
116
 
117
- # Apply shifts to specific dimensions
118
- noise[0, 0] += x_shift
119
- noise[0, 1] += y_shift
 
 
 
 
120
 
 
121
  fake_img = gen_model(noise)
122
  return StreamingResponse(get_image_stream(fake_img), media_type="image/png")
123
 
 
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
 
 
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
 
 
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)
 
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