Princeaka commited on
Commit
f5337df
·
verified ·
1 Parent(s): e003942

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -194
app.py DELETED
@@ -1,194 +0,0 @@
1
- import os
2
- import shutil
3
- import asyncio
4
- import inspect
5
- import socket
6
- from typing import Optional
7
- from fastapi import FastAPI, UploadFile, File, Form
8
- from fastapi.responses import JSONResponse
9
- from fastapi.middleware.cors import CORSMiddleware
10
- import gradio as gr
11
-
12
- from multimodal_module import MultiModalChatModule
13
- AI = MultiModalChatModule()
14
-
15
- TMP_DIR = "/tmp"
16
- os.makedirs(TMP_DIR, exist_ok=True)
17
-
18
- # --- Helpers ---
19
- class FileWrapper:
20
- def __init__(self, path: str):
21
- self._path = path
22
- async def download_to_drive(self, dst_path: str) -> None:
23
- loop = asyncio.get_event_loop()
24
- await loop.run_in_executor(None, shutil.copyfile, self._path, dst_path)
25
-
26
- async def save_upload_to_tmp(up: UploadFile) -> str:
27
- if not up or not up.filename:
28
- raise ValueError("No file uploaded")
29
- dest = os.path.join(TMP_DIR, up.filename)
30
- data = await up.read()
31
- with open(dest, "wb") as f:
32
- f.write(data)
33
- return dest
34
-
35
- async def call_ai(fn, *args, **kwargs):
36
- if fn is None:
37
- raise AttributeError("Requested AI method not implemented")
38
- if inspect.iscoroutinefunction(fn):
39
- return await fn(*args, **kwargs)
40
- return await asyncio.to_thread(lambda: fn(*args, **kwargs))
41
-
42
- def get_free_port():
43
- s = socket.socket()
44
- s.bind(("", 0))
45
- port = s.getsockname()[1]
46
- s.close()
47
- return port
48
-
49
- # --- FastAPI app ---
50
- app = FastAPI(title="Multimodal Module API")
51
-
52
- app.add_middleware(
53
- CORSMiddleware,
54
- allow_origins=["*"], # Change in production!
55
- allow_credentials=True,
56
- allow_methods=["*"],
57
- allow_headers=["*"],
58
- )
59
-
60
- # --- API Endpoints ---
61
- @app.post("/api/text")
62
- async def api_text(text: str = Form(...), user_id: Optional[int] = Form(0), lang: str = Form("en")):
63
- try:
64
- fn = getattr(AI, "generate_response", getattr(AI, "process_text", None))
65
- reply = await call_ai(fn, text, int(user_id), lang)
66
- return {"status": "ok", "reply": reply}
67
- except Exception as e:
68
- return JSONResponse({"error": str(e)}, status_code=500)
69
-
70
- @app.post("/api/voice")
71
- async def api_voice(user_id: Optional[int] = Form(0), audio_file: UploadFile = File(...)):
72
- try:
73
- path = await save_upload_to_tmp(audio_file)
74
- fn = getattr(AI, "process_voice_message", None)
75
- result = await call_ai(fn, FileWrapper(path), int(user_id))
76
- return JSONResponse(result)
77
- except Exception as e:
78
- return JSONResponse({"error": str(e)}, status_code=500)
79
-
80
- @app.post("/api/voice_reply")
81
- async def api_voice_reply(user_id: Optional[int] = Form(0), reply_text: str = Form(...), fmt: str = Form("ogg")):
82
- try:
83
- fn = getattr(AI, "generate_voice_reply", None)
84
- result = await call_ai(fn, reply_text, int(user_id), fmt)
85
- return {"status": "ok", "file": result}
86
- except Exception as e:
87
- return JSONResponse({"error": str(e)}, status_code=500)
88
-
89
- @app.post("/api/image_caption")
90
- async def api_image_caption(user_id: Optional[int] = Form(0), image_file: UploadFile = File(...)):
91
- try:
92
- path = await save_upload_to_tmp(image_file)
93
- fn = getattr(AI, "process_image_message", None)
94
- caption = await call_ai(fn, FileWrapper(path), int(user_id))
95
- return {"status": "ok", "caption": caption}
96
- except Exception as e:
97
- return JSONResponse({"error": str(e)}, status_code=500)
98
-
99
- @app.post("/api/generate_image")
100
- async def api_generate_image(
101
- user_id: Optional[int] = Form(0),
102
- prompt: str = Form(...),
103
- width: int = Form(512),
104
- height: int = Form(512),
105
- steps: int = Form(30)
106
- ):
107
- try:
108
- fn = getattr(AI, "generate_image_from_text", None)
109
- out_path = await call_ai(fn, prompt, int(user_id), width, height, steps)
110
- return {"status": "ok", "file": out_path}
111
- except Exception as e:
112
- return JSONResponse({"error": str(e)}, status_code=500)
113
-
114
- @app.post("/api/edit_image")
115
- async def api_edit_image(
116
- user_id: Optional[int] = Form(0),
117
- image_file: UploadFile = File(...),
118
- mask_file: Optional[UploadFile] = File(None),
119
- prompt: str = Form("")
120
- ):
121
- try:
122
- img_path = await save_upload_to_tmp(image_file)
123
- mask_path = None
124
- if mask_file:
125
- mask_path = await save_upload_to_tmp(mask_file)
126
- fn = getattr(AI, "edit_image_inpaint", None)
127
- out_path = await call_ai(
128
- fn,
129
- FileWrapper(img_path),
130
- FileWrapper(mask_path) if mask_path else None,
131
- prompt,
132
- int(user_id)
133
- )
134
- return {"status": "ok", "file": out_path}
135
- except Exception as e:
136
- return JSONResponse({"error": str(e)}, status_code=500)
137
-
138
- @app.post("/api/video")
139
- async def api_video(user_id: Optional[int] = Form(0), video_file: UploadFile = File(...)):
140
- try:
141
- path = await save_upload_to_tmp(video_file)
142
- fn = getattr(AI, "process_video", None)
143
- result = await call_ai(fn, FileWrapper(path), int(user_id))
144
- return JSONResponse(result)
145
- except Exception as e:
146
- return JSONResponse({"error": str(e)}, status_code=500)
147
-
148
- @app.post("/api/file")
149
- async def api_file(user_id: Optional[int] = Form(0), file_obj: UploadFile = File(...)):
150
- try:
151
- path = await save_upload_to_tmp(file_obj)
152
- fn = getattr(AI, "process_file", None)
153
- result = await call_ai(fn, FileWrapper(path), int(user_id))
154
- return JSONResponse(result)
155
- except Exception as e:
156
- return JSONResponse({"error": str(e)}, status_code=500)
157
-
158
- @app.post("/api/code")
159
- async def api_code(user_id: Optional[int] = Form(0), prompt: str = Form(...), max_tokens: int = Form(512)):
160
- try:
161
- fn = getattr(AI, "code_complete", None)
162
- try:
163
- result = await call_ai(fn, int(user_id), prompt, max_tokens)
164
- except TypeError:
165
- result = await call_ai(fn, prompt, max_tokens=max_tokens)
166
- return {"status": "ok", "code": result}
167
- except Exception as e:
168
- return JSONResponse({"error": str(e)}, status_code=500)
169
-
170
- # --- Gradio UI ---
171
- def gradio_text_fn(text, user_id, lang):
172
- fn = getattr(AI, "generate_response", getattr(AI, "process_text", None))
173
- if fn is None:
174
- return "Error: text handler not implemented"
175
- loop = asyncio.get_event_loop()
176
- return loop.run_until_complete(call_ai(fn, text, int(user_id or 0), lang))
177
-
178
- with gr.Blocks(title="Multimodal Bot (UI)") as demo:
179
- gr.Markdown("# 🧠 Multimodal Bot — UI")
180
- with gr.Row():
181
- uid = gr.Textbox(label="User ID", value="0")
182
- lang = gr.Dropdown(["en", "zh", "ja", "ko", "es", "fr", "de", "it"], value="en", label="Language")
183
- inp = gr.Textbox(lines=3, label="Message")
184
- out = gr.Textbox(lines=6, label="Reply")
185
- gr.Button("Send").click(gradio_text_fn, [inp, uid, lang], out)
186
-
187
- # Mount Gradio to FastAPI
188
- app = gr.mount_gradio_app(app, demo, path="/")
189
-
190
- # --- Local Run Only ---
191
- if __name__ == "__main__":
192
- import uvicorn
193
- port = int(os.environ.get("PORT", get_free_port()))
194
- uvicorn.run("app:app", host="0.0.0.0", port=port, reload=True)