Vnmrsharma commited on
Commit
b834f10
·
1 Parent(s): f3fa14d

Updated Simplified API Calls

Browse files
Files changed (4) hide show
  1. __pycache__/main.cpython-313.pyc +0 -0
  2. frontend.html +130 -0
  3. main.py +178 -0
  4. requirements.txt +7 -0
__pycache__/main.cpython-313.pyc ADDED
Binary file (9.35 kB). View file
 
frontend.html ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Meshy Image-to-3D Proxy Test</title>
7
+ <style>
8
+ body { font-family: Arial, sans-serif; margin: 2rem; }
9
+ section { margin-bottom: 2rem; }
10
+ pre { background: #f4f4f4; padding: 1rem; overflow: auto; }
11
+ input, button { margin-top: 0.5rem; }
12
+ </style>
13
+ </head>
14
+ <body>
15
+ <h1>Meshy Image-to-3D Proxy Test UI</h1>
16
+
17
+ <section>
18
+ <h2>1) Create Image-to-3D Task</h2>
19
+ <input type="file" id="imageInput" accept="image/png, image/jpeg" /><br />
20
+ <button id="submitImage">Submit Image</button>
21
+ <pre id="imageResult">✔ No result yet</pre>
22
+ </section>
23
+
24
+ <section>
25
+ <h2>2) Retrieve Task Result</h2>
26
+ <input type="text" id="taskIdInput" placeholder="Enter task ID" size="50" /><br />
27
+ <button id="getResult">Fetch Result</button>
28
+ <pre id="resultOutput">✔ No result yet</pre>
29
+ </section>
30
+
31
+ <section>
32
+ <h2>3) List All Tasks</h2>
33
+ <button id="listTasks">List Tasks</button>
34
+ <pre id="listOutput">✔ No result yet</pre>
35
+ </section>
36
+
37
+ <section>
38
+ <h2>4) Create Text-to-3D Task</h2>
39
+ <textarea id="textInput" rows="4" cols="50" placeholder="Enter description..."></textarea><br />
40
+ <button id="submitText">Submit Text</button>
41
+ <pre id="textResult">✔ No result yet</pre>
42
+ </section>
43
+
44
+ <section>
45
+ <h2>5) Retrieve Text-to-3D Result</h2>
46
+ <input type="text" id="textTaskIdInput" placeholder="Enter text task ID" size="50" /><br />
47
+ <button id="getTextResult">Fetch Text Result</button>
48
+ <pre id="textResultOutput">✔ No result yet</pre>
49
+ </section>
50
+
51
+ <section>
52
+ <h2>6) List Text-to-3D Tasks</h2>
53
+ <button id="listTextTasks">List Text Tasks</button>
54
+ <pre id="listTextOutput">✔ No result yet</pre>
55
+ </section>
56
+
57
+ <script>
58
+ // Base URL of your FastAPI service
59
+ const API_BASE = 'http://localhost:8000';
60
+
61
+ // 1) Create Image-to-3D Task
62
+ document.getElementById('submitImage').addEventListener('click', async () => {
63
+ const fileInput = document.getElementById('imageInput');
64
+ if (!fileInput.files.length) return alert('Please select an image first.');
65
+
66
+ const form = new FormData();
67
+ form.append('image', fileInput.files[0]);
68
+
69
+ const res = await fetch(`${API_BASE}/req-img-to-3d`, {
70
+ method: 'POST',
71
+ body: form,
72
+ });
73
+ const data = await res.json();
74
+ document.getElementById('imageResult').textContent = JSON.stringify(data, null, 2);
75
+ });
76
+
77
+ // 2) Retrieve Task Result
78
+ document.getElementById('getResult').addEventListener('click', async () => {
79
+ const taskId = document.getElementById('taskIdInput').value.trim();
80
+ if (!taskId) return alert('Enter a task ID');
81
+
82
+ const res = await fetch(`${API_BASE}/req-result-img-to-3d/${taskId}`);
83
+ const data = await res.json();
84
+ document.getElementById('resultOutput').textContent = JSON.stringify(data, null, 2);
85
+ });
86
+
87
+ // 3) List All Tasks
88
+ document.getElementById('listTasks').addEventListener('click', async () => {
89
+ const res = await fetch(`${API_BASE}/list-img-to-3d-req`);
90
+ const data = await res.json();
91
+ document.getElementById('listOutput').textContent = JSON.stringify(data, null, 2);
92
+ });
93
+
94
+ // 4) Create Text-to-3D Task
95
+ document.getElementById('submitText').addEventListener('click', async () => {
96
+ const textInput = document.getElementById('textInput');
97
+ if (!textInput.value.trim()) return alert('Please enter text');
98
+
99
+ const res = await fetch(`${API_BASE}/req-text-to-3d`, {
100
+ method: 'POST',
101
+ headers: {
102
+ 'Content-Type': 'application/json',
103
+ },
104
+ body: JSON.stringify({
105
+ text: textInput.value.trim(),
106
+ }),
107
+ });
108
+ const data = await res.json();
109
+ document.getElementById('textResult').textContent = JSON.stringify(data, null, 2);
110
+ });
111
+
112
+ // 5) Retrieve Text-to-3D Result
113
+ document.getElementById('getTextResult').addEventListener('click', async () => {
114
+ const textTaskId = document.getElementById('textTaskIdInput').value.trim();
115
+ if (!textTaskId) return alert('Enter a text task ID');
116
+
117
+ const res = await fetch(`${API_BASE}/req-result-text-to-3d/${textTaskId}`);
118
+ const data = await res.json();
119
+ document.getElementById('textResultOutput').textContent = JSON.stringify(data, null, 2);
120
+ });
121
+
122
+ // 6) List Text-to-3D Tasks
123
+ document.getElementById('listTextTasks').addEventListener('click', async () => {
124
+ const res = await fetch(`${API_BASE}/list-text-to-3d-req`);
125
+ const data = await res.json();
126
+ document.getElementById('listTextOutput').textContent = JSON.stringify(data, null, 2);
127
+ });
128
+ </script>
129
+ </body>
130
+ </html>
main.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import base64
3
+ from fastapi import FastAPI, UploadFile, File, HTTPException, Depends
4
+ import httpx
5
+ from contextlib import asynccontextmanager
6
+ from dotenv import load_dotenv
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+ from pydantic import BaseModel
9
+
10
+ load_dotenv()
11
+
12
+ class Settings:
13
+ def __init__(self):
14
+ self.mesh_api_key = os.getenv("MESHY_API_KEY")
15
+ if not self.mesh_api_key:
16
+ raise RuntimeError("MESHY_API_KEY environment variable not set")
17
+ self.openai_api_key = os.getenv("OPENAI_API_KEY")
18
+ if not self.openai_api_key:
19
+ raise RuntimeError("OPENAI_API_KEY environment variable not set")
20
+
21
+ settings = Settings()
22
+
23
+ def get_settings():
24
+ return settings
25
+
26
+ @asynccontextmanager
27
+ async def lifespan(app: FastAPI):
28
+ app.state.client = httpx.AsyncClient(timeout=10.0)
29
+ yield
30
+ await app.state.client.aclose()
31
+
32
+ app = FastAPI(
33
+ title="3DAI API Module",
34
+ version="1.0.0",
35
+ description="Proxy endpoints for the APIs",
36
+ lifespan=lifespan
37
+ )
38
+
39
+ # Add CORS for all origins (for testing)
40
+ app.add_middleware(
41
+ CORSMiddleware,
42
+ allow_origins=["*"],
43
+ allow_credentials=True,
44
+ allow_methods=["*"],
45
+ allow_headers=["*"],
46
+ )
47
+
48
+ # Pydantic model for incoming text prompt
49
+ class TextPrompt(BaseModel):
50
+ text: str
51
+
52
+ @app.post("/req-img-to-3d", tags=["Image-to-3D"])
53
+ async def req_img_to_3d(
54
+ image: UploadFile = File(...),
55
+ settings: Settings = Depends(get_settings)
56
+ ):
57
+ """
58
+ Create a new Image-to-3D task by uploading an image.
59
+ """
60
+ content = await image.read()
61
+ if not content:
62
+ raise HTTPException(status_code=400, detail="Empty file upload")
63
+ data_uri = (f"data:{image.content_type};base64," +
64
+ base64.b64encode(content).decode())
65
+ payload = {"image_url": data_uri}
66
+ headers = {"Authorization": f"Bearer {settings.mesh_api_key}"}
67
+ resp = await app.state.client.post(
68
+ "https://api.meshy.ai/openapi/v1/image-to-3d",
69
+ json=payload,
70
+ headers=headers,
71
+ )
72
+ if resp.status_code not in (200, 201):
73
+ raise HTTPException(status_code=resp.status_code, detail=resp.text)
74
+ return resp.json()
75
+
76
+ @app.get("/req-result-img-to-3d/{task_id}", tags=["Image-to-3D"])
77
+ async def req_result_img_to_3d(
78
+ task_id: str,
79
+ settings: Settings = Depends(get_settings)
80
+ ):
81
+ """
82
+ Retrieve the status and result of a Meshy Image-to-3D task by ID.
83
+ """
84
+ headers = {"Authorization": f"Bearer {settings.mesh_api_key}"}
85
+ url = f"https://api.meshy.ai/openapi/v1/image-to-3d/{task_id}"
86
+ resp = await app.state.client.get(url, headers=headers)
87
+ if resp.status_code != 200:
88
+ raise HTTPException(status_code=resp.status_code, detail=resp.text)
89
+ return resp.json()
90
+
91
+ @app.get("/list-img-to-3d-req", tags=["Image-to-3D"])
92
+ async def list_img_to_3d_req(
93
+ settings: Settings = Depends(get_settings)
94
+ ):
95
+ """
96
+ List all Image-to-3D tasks.
97
+ """
98
+ headers = {"Authorization": f"Bearer {settings.mesh_api_key}"}
99
+ resp = await app.state.client.get(
100
+ "https://api.meshy.ai/openapi/v1/image-to-3d",
101
+ headers=headers
102
+ )
103
+ if resp.status_code != 200:
104
+ raise HTTPException(status_code=resp.status_code, detail=resp.text)
105
+ return resp.json()
106
+
107
+ @app.post("/req-text-to-3d", tags=["Text-to-3D"] )
108
+ async def req_text_to_3d(
109
+ prompt: TextPrompt,
110
+ settings: Settings = Depends(get_settings)
111
+ ):
112
+ """
113
+ Reframe user text via OpenAI, then create a Text-to-3D preview task.
114
+ """
115
+ # Reframe prompt
116
+ openai_resp = await app.state.client.post(
117
+ "https://api.openai.com/v1/chat/completions",
118
+ headers={"Authorization": f"Bearer {settings.openai_api_key}"},
119
+ json={
120
+ "model": "gpt-3.5-turbo",
121
+ "messages": [
122
+ {"role": "system", "content": "Rephrase the user description to be an ideal prompt for 3D model generation."},
123
+ {"role": "user", "content": prompt.text}
124
+ ]
125
+ }
126
+ )
127
+ if openai_resp.status_code != 200:
128
+ raise HTTPException(status_code=openai_resp.status_code, detail=openai_resp.text)
129
+ reframed = openai_resp.json()["choices"][0]["message"]["content"]
130
+ # Create Meshy Text-to-3D task
131
+ meshy_resp = await app.state.client.post(
132
+ "https://api.meshy.ai/openapi/v2/text-to-3d",
133
+ headers={"Authorization": f"Bearer {settings.mesh_api_key}"},
134
+ json={"mode": "preview", "prompt": reframed}
135
+ )
136
+ if meshy_resp.status_code not in (200, 201):
137
+ raise HTTPException(status_code=meshy_resp.status_code, detail=meshy_resp.text)
138
+ return meshy_resp.json()
139
+
140
+ @app.get("/req-result-text-to-3d/{task_id}", tags=["Text-to-3D"])
141
+ async def req_result_text_to_3d(
142
+ task_id: str,
143
+ settings: Settings = Depends(get_settings)
144
+ ):
145
+ """
146
+ Retrieve the status/result of a Text-to-3D task by ID.
147
+ """
148
+ resp = await app.state.client.get(
149
+ f"https://api.meshy.ai/openapi/v2/text-to-3d/{task_id}",
150
+ headers={"Authorization": f"Bearer {settings.mesh_api_key}"}
151
+ )
152
+ if resp.status_code != 200:
153
+ raise HTTPException(status_code=resp.status_code, detail=resp.text)
154
+ return resp.json()
155
+
156
+ @app.get("/list-text-to-3d-req", tags=["Text-to-3D"])
157
+ async def list_text_to_3d_req(
158
+ settings: Settings = Depends(get_settings)
159
+ ):
160
+ """
161
+ List all Text-to-3D tasks.
162
+ """
163
+ resp = await app.state.client.get(
164
+ "https://api.meshy.ai/openapi/v2/text-to-3d",
165
+ headers={"Authorization": f"Bearer {settings.mesh_api_key}"}
166
+ )
167
+ if resp.status_code != 200:
168
+ raise HTTPException(status_code=resp.status_code, detail=resp.text)
169
+ return resp.json()
170
+
171
+ @app.get("/", tags=["Health"])
172
+ async def health_check():
173
+ """Basic health-check endpoint returning service status."""
174
+ return {"status": "ok"}
175
+
176
+ if __name__ == "__main__":
177
+ import uvicorn
178
+ uvicorn.run("main:app", host="0.0.0.0", port=8000, log_level="info")
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ fastapi[standard]>=0.70.0
2
+ httpx>=0.23.0
3
+ uvicorn[standard]>=0.18.0
4
+ pydantic>=2.0.0
5
+ pydantic-settings>=2.0.0
6
+ python-dotenv>=0.21.0
7
+ openai