AIMaster7 commited on
Commit
17bfc41
·
verified ·
1 Parent(s): eb249f4

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +19 -30
main.py CHANGED
@@ -11,41 +11,35 @@ from dotenv import load_dotenv
11
 
12
  load_dotenv()
13
 
14
- from models import AVAILABLE_MODELS, MODEL_ALIASES
 
15
 
16
- # Require IMAGE_API_URL strictly from environment
17
  IMAGE_API_URL = os.environ["IMAGE_API_URL"]
18
- GPT_IMAGE_API_URL = "https://www.chatwithmono.xyz/api/image"
19
  SNAPZION_UPLOAD_URL = "https://upload.snapzion.com/api/public-upload"
20
  SNAPZION_API_KEY = os.environ["SNAP"]
21
 
22
  app = FastAPI()
23
 
24
-
25
  def unix_id():
26
  return str(int(time.time() * 1000))
27
 
28
-
29
- # ==== Models ====
30
-
31
  @app.get("/v1/models")
32
  async def list_models():
33
  return {"object": "list", "data": AVAILABLE_MODELS}
34
 
35
-
36
- # ==== Chat Completion ====
37
 
38
  class Message(BaseModel):
39
  role: str
40
  content: str
41
 
42
-
43
  class ChatRequest(BaseModel):
44
  messages: List[Message]
45
  model: str
46
  stream: Optional[bool] = False
47
 
48
-
49
  @app.post("/v1/chat/completions")
50
  async def chat_completion(request: ChatRequest):
51
  model_id = MODEL_ALIASES.get(request.model, request.model)
@@ -104,7 +98,6 @@ async def chat_completion(request: ChatRequest):
104
  }
105
  yield f"data: {json.dumps(done_chunk)}\n\ndata: [DONE]\n\n"
106
  return StreamingResponse(event_stream(), media_type="text/event-stream")
107
-
108
  else:
109
  assistant_response = ""
110
  usage_info = {}
@@ -145,8 +138,7 @@ async def chat_completion(request: ChatRequest):
145
  }
146
  })
147
 
148
-
149
- # ==== Image Generation ====
150
 
151
  class ImageGenerationRequest(BaseModel):
152
  prompt: str
@@ -155,14 +147,15 @@ class ImageGenerationRequest(BaseModel):
155
  user: Optional[str] = None
156
  model: Optional[str] = "default"
157
 
158
-
159
  @app.post("/v1/images/generations")
160
  async def generate_images(request: ImageGenerationRequest):
161
  results = []
162
 
163
  async with httpx.AsyncClient(timeout=60) as client:
164
  for _ in range(request.n):
165
- if request.model == "gpt-image-1":
 
 
166
  headers = {
167
  'Content-Type': 'application/json',
168
  'User-Agent': 'Mozilla/5.0',
@@ -174,26 +167,23 @@ async def generate_images(request: ImageGenerationRequest):
174
 
175
  payload = {
176
  "prompt": request.prompt,
177
- "model": "gpt-image-1"
178
  }
179
 
180
- resp = await client.post(GPT_IMAGE_API_URL, headers=headers, json=payload)
181
  if resp.status_code != 200:
182
  return JSONResponse(
183
  status_code=502,
184
- content={"error": "GPT-Image generation failed", "details": resp.text}
185
  )
186
 
187
  data = resp.json()
188
  b64_image = data.get("image")
189
-
190
  if not b64_image:
191
- return JSONResponse(status_code=502, content={"error": "No base64 image in response"})
192
 
193
- # Reconstruct full data URI
194
- full_image_data = f"data:image/png;base64,{b64_image}"
195
 
196
- # Upload to Snapzion
197
  upload_headers = {"Authorization": SNAPZION_API_KEY}
198
  upload_files = {
199
  'file': ('image.png', base64.b64decode(b64_image), 'image/png')
@@ -207,15 +197,13 @@ async def generate_images(request: ImageGenerationRequest):
207
  )
208
 
209
  upload_data = upload_resp.json()
210
- image_url = upload_data.get("url")
211
-
212
  results.append({
213
- "url": image_url,
214
  "b64_json": b64_image,
215
- "data_uri": full_image_data
 
216
  })
217
  else:
218
- # Default image generator
219
  params = {
220
  "prompt": request.prompt,
221
  "aspect_ratio": request.aspect_ratio,
@@ -233,7 +221,8 @@ async def generate_images(request: ImageGenerationRequest):
233
  results.append({
234
  "url": data.get("image_link"),
235
  "b64_json": data.get("base64_output"),
236
- "retries": data.get("attempt")
 
237
  })
238
 
239
  return {
 
11
 
12
  load_dotenv()
13
 
14
+ # Dummy imports for example
15
+ from models import AVAILABLE_MODELS, MODEL_ALIASES # Ensure these are defined properly
16
 
17
+ # Env variables
18
  IMAGE_API_URL = os.environ["IMAGE_API_URL"]
 
19
  SNAPZION_UPLOAD_URL = "https://upload.snapzion.com/api/public-upload"
20
  SNAPZION_API_KEY = os.environ["SNAP"]
21
 
22
  app = FastAPI()
23
 
 
24
  def unix_id():
25
  return str(int(time.time() * 1000))
26
 
27
+ # === Models ===
 
 
28
  @app.get("/v1/models")
29
  async def list_models():
30
  return {"object": "list", "data": AVAILABLE_MODELS}
31
 
32
+ # === Chat Completion ===
 
33
 
34
  class Message(BaseModel):
35
  role: str
36
  content: str
37
 
 
38
  class ChatRequest(BaseModel):
39
  messages: List[Message]
40
  model: str
41
  stream: Optional[bool] = False
42
 
 
43
  @app.post("/v1/chat/completions")
44
  async def chat_completion(request: ChatRequest):
45
  model_id = MODEL_ALIASES.get(request.model, request.model)
 
98
  }
99
  yield f"data: {json.dumps(done_chunk)}\n\ndata: [DONE]\n\n"
100
  return StreamingResponse(event_stream(), media_type="text/event-stream")
 
101
  else:
102
  assistant_response = ""
103
  usage_info = {}
 
138
  }
139
  })
140
 
141
+ # === Image Generation ===
 
142
 
143
  class ImageGenerationRequest(BaseModel):
144
  prompt: str
 
147
  user: Optional[str] = None
148
  model: Optional[str] = "default"
149
 
 
150
  @app.post("/v1/images/generations")
151
  async def generate_images(request: ImageGenerationRequest):
152
  results = []
153
 
154
  async with httpx.AsyncClient(timeout=60) as client:
155
  for _ in range(request.n):
156
+ model = request.model or "default"
157
+
158
+ if model in ["gpt-image-1", "dall-e-3", "dall-e-2", "nextlm-image-1"]:
159
  headers = {
160
  'Content-Type': 'application/json',
161
  'User-Agent': 'Mozilla/5.0',
 
167
 
168
  payload = {
169
  "prompt": request.prompt,
170
+ "model": model
171
  }
172
 
173
+ resp = await client.post("https://www.chatwithmono.xyz/api/image", headers=headers, json=payload)
174
  if resp.status_code != 200:
175
  return JSONResponse(
176
  status_code=502,
177
+ content={"error": f"{model} generation failed", "details": resp.text}
178
  )
179
 
180
  data = resp.json()
181
  b64_image = data.get("image")
 
182
  if not b64_image:
183
+ return JSONResponse(status_code=502, content={"error": "Missing base64 image in response"})
184
 
185
+ data_uri = f"data:image/png;base64,{b64_image}"
 
186
 
 
187
  upload_headers = {"Authorization": SNAPZION_API_KEY}
188
  upload_files = {
189
  'file': ('image.png', base64.b64decode(b64_image), 'image/png')
 
197
  )
198
 
199
  upload_data = upload_resp.json()
 
 
200
  results.append({
201
+ "url": upload_data.get("url"),
202
  "b64_json": b64_image,
203
+ "data_uri": data_uri,
204
+ "model": model
205
  })
206
  else:
 
207
  params = {
208
  "prompt": request.prompt,
209
  "aspect_ratio": request.aspect_ratio,
 
221
  results.append({
222
  "url": data.get("image_link"),
223
  "b64_json": data.get("base64_output"),
224
+ "retries": data.get("attempt"),
225
+ "model": "default"
226
  })
227
 
228
  return {