Peeble commited on
Commit
8bd3cef
·
verified ·
1 Parent(s): 06a8698

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -0
app.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ import matplotlib.pyplot as plt
4
+
5
+ from gpt3d.model import GPT3D
6
+ from gpt3d.mesh import save_obj
7
+
8
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
9
+ model = GPT3D().to(device)
10
+
11
+ MODEL_PATH = "gpt3d_local.pt"
12
+
13
+
14
+ def train_model(epochs):
15
+ opt = torch.optim.AdamW(model.parameters(), lr=1e-4)
16
+ loss_fn = torch.nn.MSELoss()
17
+
18
+ for e in range(epochs):
19
+ noise = torch.randn(8, 1024, 3).to(device)
20
+ out = model(noise)
21
+ loss = loss_fn(out, noise)
22
+
23
+ opt.zero_grad()
24
+ loss.backward()
25
+ opt.step()
26
+
27
+ torch.save(model.state_dict(), MODEL_PATH)
28
+ return "✅ Trained locally"
29
+
30
+
31
+ def generate_mesh(steps):
32
+ model.load_state_dict(torch.load(MODEL_PATH, map_location=device))
33
+ model.eval()
34
+
35
+ pts = torch.randn(1, 1024, 3).to(device)
36
+
37
+ with torch.no_grad():
38
+ for _ in range(steps):
39
+ pts = model(pts)
40
+
41
+ pts = pts.squeeze().cpu().numpy()
42
+ save_obj(pts, "mesh.obj")
43
+
44
+ return "✅ mesh.obj generated"
45
+
46
+
47
+ def view_mesh():
48
+ pts = []
49
+ with open("mesh.obj") as f:
50
+ for line in f:
51
+ if line.startswith("v "):
52
+ _, x, y, z = line.split()
53
+ pts.append([float(x), float(y), float(z)])
54
+
55
+ pts = torch.tensor(pts)
56
+
57
+ fig = plt.figure()
58
+ ax = fig.add_subplot(projection='3d')
59
+ ax.scatter(pts[:,0], pts[:,1], pts[:,2], s=1)
60
+ return fig
61
+
62
+
63
+ with gr.Blocks() as demo:
64
+ gr.Markdown("# GPT-3D Local Generator")
65
+
66
+ with gr.Tab("Train"):
67
+ epochs = gr.Slider(1, 50, value=5, step=1)
68
+ btn = gr.Button("Train")
69
+ out = gr.Textbox()
70
+ btn.click(train_model, epochs, out)
71
+
72
+ with gr.Tab("Generate OBJ"):
73
+ steps = gr.Slider(10, 200, value=50, step=10)
74
+ btn2 = gr.Button("Generate Mesh")
75
+ out2 = gr.Textbox()
76
+ btn2.click(generate_mesh, steps, out2)
77
+
78
+ with gr.Tab("View"):
79
+ btn3 = gr.Button("View Mesh")
80
+ plot = gr.Plot()
81
+ btn3.click(view_mesh, None, plot)
82
+
83
+ demo.launch()