File size: 9,258 Bytes
609d54c c8ef5ef 05ba985 609d54c c8ef5ef 609d54c 05ba985 609d54c 05ba985 609d54c 05ba985 609d54c 05ba985 609d54c 05ba985 609d54c c8ef5ef 609d54c 05ba985 609d54c c8ef5ef 05ba985 609d54c 05ba985 609d54c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 |
from fastapi import FastAPI, Request, File, UploadFile, HTTPException, Form, Query
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from jinja2 import Environment, FileSystemLoader, select_autoescape
from custom_logger import logger_config
from image.image_base import ImageBase
from pydantic import BaseModel
from image.converter import Converter
from image.remove_metadata import RemoveMetadata
from image.remove_background import RemoveBackground
import mimetypes
app = FastAPI(title="Tools Collection", description="Collection of utility tools")
# Mount static/image at /image
app.mount("/image/javascript", StaticFiles(directory="image/javascript"), name="image")
# Templates
template_dirs = [".", "./image"]
env = Environment(
loader=FileSystemLoader(template_dirs),
autoescape=select_autoescape(['html', 'xml'])
)
# Available features
FEATURES = {
"image": {
"name": "Image Tools",
"description": "HEIC to PNG/JPG conversion and metadata removal",
"icon": "πΌοΈ",
"features": ["convert", "remove_metadata", "remove_background"],
"folder": "image",
"tags": ["image", "heic", "png", "jpg", "convert", "metadata"]
},
"pdf": {
"name": "PDF Tools",
"description": "Convert images to PDF, merge PDFs, and more",
"icon": "π",
"features": ["images_to_pdf"],
"folder": "pdf",
"tags": ["pdf", "merge", "convert", "images", "document"],
"coming_soon": True
},
"audio": {
"name": "Audio Tools",
"description": "Convert audio formats and compress audio files",
"icon": "π΅",
"features": ["convert_audio", "compress_audio"],
"folder": "audio",
"tags": ["audio", "music", "convert", "compress", "mp3", "wav"],
"coming_soon": True
},
"video": {
"name": "Video Tools",
"description": "Basic video editing and format conversion",
"icon": "π¬",
"features": ["convert_video", "compress_video"],
"folder": "video",
"tags": ["video", "convert", "compress", "mp4", "avi", "editing"],
"coming_soon": True
}
}
# Routes
@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
template = env.get_template("index.html") # From tool/
html_content = template.render(request=request)
return HTMLResponse(content=html_content)
@app.get("/image/convert", response_class=HTMLResponse)
async def image_tools(request: Request):
template = env.get_template("image/convert.html") # From tool/image/
html_content = template.render(request=request)
return HTMLResponse(content=html_content)
@app.get("/image/remove_metadata", response_class=HTMLResponse)
async def image_tools(request: Request):
template = env.get_template("image/remove_metadata.html") # From tool/image/
html_content = template.render(request=request)
return HTMLResponse(content=html_content)
@app.get("/image/remove_background", response_class=HTMLResponse)
async def image_tools(request: Request):
template = env.get_template("image/remove_background.html") # From tool/image/
html_content = template.render(request=request)
return HTMLResponse(content=html_content)
@app.post("/image/upload")
async def upload_image(
id: str = Form(...),
image: UploadFile = File(...)
):
try:
image_base = ImageBase()
image_base.upload(id, image)
# Return success response
return JSONResponse({
"success": True,
"message": "Image uploaded successfully"
})
except ValueError as ve:
logger_config.error(f"Validation error: {str(ve)}")
raise HTTPException(
status_code=400,
detail=str(ve)
)
except Exception as e:
logger_config.error(f"Unexpected error during upload: {str(e)}")
raise HTTPException(
status_code=500,
detail=f"Internal server error: {str(e)}"
)
@app.post("/image/convert")
async def convert_image(
id: str = Form(...),
to_format: str = Form(...)
):
try:
converter = Converter()
output_path = converter.convert_image(id, to_format)
# Return success response
return JSONResponse({
"success": True,
"message": "Image uploaded successfully",
"new_filename": output_path.split("/")[-1]
})
except ValueError as ve:
logger_config.error(f"Validation error: {str(ve)}")
raise HTTPException(
status_code=400,
detail=str(ve)
)
except Exception as e:
logger_config.error(f"Unexpected error during upload: {str(e)}")
raise HTTPException(
status_code=500,
detail=f"Internal server error: {str(e)}"
)
@app.post("/image/remove_metadata")
async def remove_metadata(
id: str = Form(...)
):
try:
removeMetadata = RemoveMetadata()
output_path, metadata = removeMetadata.process(id)
# Return success response
return JSONResponse({
"success": True,
"message": "Image uploaded successfully",
"new_filename": output_path.split("/")[-1],
"other_info": metadata
})
except ValueError as ve:
logger_config.error(f"Validation error: {str(ve)}")
raise HTTPException(
status_code=400,
detail=str(ve)
)
except Exception as e:
logger_config.error(f"Unexpected error during remove_metadata: {str(e)}")
raise HTTPException(
status_code=500,
detail=f"Internal server error: {str(e)}"
)
@app.post("/image/remove_background")
async def remove_background(
id: str = Form(...)
):
try:
removeBackground = RemoveBackground()
output_path = removeBackground.process(id)
# Return success response
return JSONResponse({
"success": True,
"message": "Image uploaded successfully",
"new_filename": output_path.split("/")[-1]
})
except ValueError as ve:
logger_config.error(f"Validation error: {str(ve)}")
raise HTTPException(
status_code=400,
detail=str(ve)
)
except Exception as e:
logger_config.error(f"Unexpected error during remove_background: {str(e)}")
raise HTTPException(
status_code=500,
detail=f"Internal server error: {str(e)}"
)
@app.get("/image/download")
async def download_converted_image(
id: str = Query(...)
):
try:
image_base = ImageBase()
file_path = image_base.download_url(id)
mime_type, _ = mimetypes.guess_type(file_path)
return FileResponse(file_path, media_type=mime_type, filename=id)
except ValueError as ve:
logger_config.error(f"Validation error: {str(ve)}")
raise HTTPException(
status_code=400,
detail=str(ve)
)
except Exception as e:
logger_config.error(f"Unexpected error during upload: {str(e)}")
raise HTTPException(
status_code=500,
detail=f"Internal server error: {str(e)}"
)
class DeleteRequest(BaseModel):
ids: list[str]
@app.post("/image/delete")
async def delete_images(request: DeleteRequest):
try:
image_base = ImageBase()
image_base.delete(request.ids)
# Return success response
return JSONResponse({
"success": True,
"message": "Image deleted successfully"
})
except ValueError as ve:
logger_config.error(f"Validation error: {str(ve)}")
raise HTTPException(
status_code=400,
detail=str(ve)
)
except Exception as e:
logger_config.error(f"Unexpected error during upload: {str(e)}")
raise HTTPException(
status_code=500,
detail=f"Internal server error: {str(e)}"
)
@app.get("/api/features")
async def get_features():
"""Get available features"""
return {"features": FEATURES}
@app.get("/api/search")
async def search_features(q: str = ""):
"""Search features by name, description, or tags"""
if not q:
return {"features": FEATURES}
q = q.lower()
filtered_features = {}
for key, feature in FEATURES.items():
# Search in name, description, and tags
search_text = f"{feature['name']} {feature['description']} {' '.join(feature.get('tags', []))}".lower()
if q in search_text:
filtered_features[key] = feature
return {"features": filtered_features}
@app.get("/api/status")
async def get_feature_status():
"""Get feature status"""
features_status = {}
for key in FEATURES.keys():
features_status[key] = {
"feature_name": None,
"is_busy": False,
"process_id": None
}
return features_status
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) |