Spaces:
Running
Running
| import os | |
| from fastapi import FastAPI, Response, Request | |
| from fastapi.responses import RedirectResponse | |
| from g4f.image import images_dir | |
| import g4f.api | |
| import g4f.Provider | |
| import demo | |
| from demo.BackendApi import BackendApi | |
| g4f.Provider.__map__["Feature"] = BackendApi | |
| g4f.models.demo_models | |
| from g4f.image import copy_images | |
| def create_app(): | |
| g4f.debug.logging = True | |
| g4f.api.AppConfig.gui = True | |
| g4f.api.AppConfig.demo = True | |
| app = FastAPI() | |
| # Add CORS middleware | |
| app.add_middleware( | |
| g4f.api.CORSMiddleware, | |
| allow_origin_regex=".*", | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| api = g4f.api.Api(app) | |
| api.register_routes() | |
| api.register_authorization() | |
| api.register_validation_exception_handler() | |
| async def download(filename, request: Request): | |
| filename = os.path.basename(filename) | |
| if "." not in filename: | |
| target = os.path.join(images_dir, filename) | |
| filename = f"{filename}.jpg" | |
| target = os.path.join(images_dir, filename) | |
| if not os.path.exists(target): | |
| url = str(request.query_params).split("url=", 1)[1] | |
| if url: | |
| source_url = url.replace("%2F", "/").replace("%3A", ":").replace("%3F", "?") | |
| await copy_images( | |
| [source_url], | |
| target=target, | |
| ssl=False, | |
| headers=demo.headers if source_url.startswith(BackendApi.url) else None) | |
| if not os.path.exists(target): | |
| return Response(status_code=404) | |
| return RedirectResponse(f"/images/{filename}") | |
| gui_app = g4f.api.WSGIMiddleware(g4f.api.get_gui_app(g4f.api.AppConfig.demo)) | |
| app.mount("/", gui_app) | |
| return app | |
| app = create_app() |