diff --git a/.env b/.env
new file mode 100644
index 0000000000000000000000000000000000000000..6e40e63bb83217a21ef7ca71398ae12db0eb713c
--- /dev/null
+++ b/.env
@@ -0,0 +1,14 @@
+SECRET_KEY=12345
+DATABASE_URL=postgresql+psycopg2://gpr3:gpr3.admin@localhost:5432/gpr3db
+BASE_URL=https://www.cloudaipdf.com
+
+ADMIN_SECRET=superadmin123
+# .env file
+
+# REPLACE 1234567 with your actual GAM Network Code
+GAM_NETWORK_CODE=1234567
+# A default site URL for GAM compliance (use your main website)
+DEFAULT_SITE_URL=http://www.yourapp.com
+ADMIN_USER=admin
+ADMIN_PASS=1234
+
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..ba79b678c80d308fee533574fc15081ecbdbf712
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,41 @@
+# Python
+__pycache__/
+*.pyc
+*.pyo
+*.pyd
+.env
+venv/
+
+# Node
+node_modules/
+
+# Logs & temp
+logs/
+temp/
+output/
+outputs/
+compressed_files/
+uploads/
+
+# ML / AI models
+*.onnx
+*.pt
+*.pth
+*.bin
+
+# Test & junk files
+test.*
+*.pdf
+*.png
+*.jpg
+
+# OS / editor
+.DS_Store
+.idea/
+.vscode/
+
+# Accidental files
+\
+udo apt install -y ffmpeg
+
+node_modules/
diff --git a/.main.py.swo b/.main.py.swo
new file mode 100644
index 0000000000000000000000000000000000000000..3c95e2adfd4172c55b6a0d5aed81f4224134aaeb
Binary files /dev/null and b/.main.py.swo differ
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..c496f74eff5f21d479ad4c154997b2d3a2f232b4
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,35 @@
+FROM python:3.10-slim
+
+# Prevent Python buffering & writing bytecode
+ENV PYTHONDONTWRITEBYTECODE=1
+ENV PYTHONUNBUFFERED=1
+
+WORKDIR /app
+
+# 1. Install all Linux tools needed by your converters
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ ffmpeg \
+ libreoffice \
+ pandoc \
+ potrace \
+ imagemagick \
+ p7zip-full \
+ unzip \
+ libcairo2 \
+ libheif-dev \
+ && rm -rf /var/lib/apt/lists/*
+
+# 2. Copy requirements & install Python dependencies
+COPY requirements.txt .
+RUN pip install --no-cache-dir -r requirements.txt
+
+# 3. Copy project files
+COPY . .
+
+# 4. Create working folders with full permissions
+RUN mkdir -p static/output tmp temp && chmod -R 777 static tmp temp
+
+# 5. Port 7860 for Hugging Face Spaces
+EXPOSE 7860
+
+CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
diff --git "a/\\" "b/\\"
new file mode 100644
index 0000000000000000000000000000000000000000..6a98339563174d61ce631f80731992c6ac80534a
--- /dev/null
+++ "b/\\"
@@ -0,0 +1,6 @@
+from core.database import engine, Base
+from core.models import rating
+
+Base.metadata.create_all(bind=engine)
+print("✅ Tables created")
+
diff --git a/__pycache__/celery_app.cpython-312.pyc b/__pycache__/celery_app.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac08a6885524226a2232c3cd3cc0a82c51d566f5
Binary files /dev/null and b/__pycache__/celery_app.cpython-312.pyc differ
diff --git a/__pycache__/main.cpython-312.pyc b/__pycache__/main.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2fe3ec895c659fc2ec0d5d2d2975a3ecf0ba01b0
Binary files /dev/null and b/__pycache__/main.cpython-312.pyc differ
diff --git a/__pycache__/main.cpython-39.pyc b/__pycache__/main.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..35cae2aa2da620dc7338e6b43228865541069785
Binary files /dev/null and b/__pycache__/main.cpython-39.pyc differ
diff --git a/admin/auth.py b/admin/auth.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a4ef96dee02c2c58ab480cd9f480c68470606e7
--- /dev/null
+++ b/admin/auth.py
@@ -0,0 +1,8 @@
+# admin/auth.py
+from fastapi_admin.providers.login import UsernamePasswordProvider
+
+auth_provider = UsernamePasswordProvider(
+ login_logo_url="",
+ admin_model="admin.models.AdminUser",
+)
+
diff --git a/admin/models.py b/admin/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..67229f32d833f3eacf10835b041935645b821491
--- /dev/null
+++ b/admin/models.py
@@ -0,0 +1,11 @@
+# admin/models.py
+from sqlmodel import SQLModel, Field
+from datetime import datetime
+
+class AdminUser(SQLModel, table=True):
+ id: int = Field(default=None, primary_key=True)
+ username: str = Field(index=True, unique=True)
+ password_hash: str
+ is_active: bool = True
+ created_at: datetime = Field(default_factory=datetime.utcnow)
+
diff --git a/admin/resources.py b/admin/resources.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa6946609cc72847d87b637e4b19903f943d575c
--- /dev/null
+++ b/admin/resources.py
@@ -0,0 +1,16 @@
+# admin/resources.py
+from fastapi_admin.resources import Model
+from fastapi_admin.widgets import inputs, displays
+from admin.models import AdminUser
+
+class AdminUserResource(Model):
+ model = AdminUser
+ icon = "fa-solid fa-user"
+ label = "Admin Users"
+ fields = [
+ "id",
+ "username",
+ "is_active",
+ "created_at",
+ ]
+
diff --git a/admin/setup.py b/admin/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..5526ab576a9ed9ddd40739084d1c332729acce1c
--- /dev/null
+++ b/admin/setup.py
@@ -0,0 +1,29 @@
+# admin/setup.py
+import aioredis
+from fastapi import FastAPI
+from fastapi_admin.app import app as admin_app
+from fastapi_admin.providers.login import UsernamePasswordProvider
+from fastapi_admin.template import templates
+from fastapi_admin.resources import Resource
+from admin.resources import AdminUserResource
+
+
+async def setup_fastapi_admin(app: FastAPI):
+ redis = await aioredis.create_redis_pool("redis://localhost")
+
+ admin_app.init(
+ app=app,
+ redis=redis,
+ providers=[
+ UsernamePasswordProvider(
+ admin_model="admin.models.AdminUser",
+ )
+ ],
+ resources=[
+ AdminUserResource,
+ ],
+ template_folders=["templates"],
+ )
+
+ app.mount("/admin", admin_app)
+
diff --git a/alembic.ini b/alembic.ini
new file mode 100644
index 0000000000000000000000000000000000000000..3e9f95c68d618dfed692fdcc39745bbfac90613c
--- /dev/null
+++ b/alembic.ini
@@ -0,0 +1,116 @@
+# A generic, single database configuration.
+
+[alembic]
+# path to migration scripts
+script_location = alembic
+
+# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
+# Uncomment the line below if you want the files to be prepended with date and time
+# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
+# for all available tokens
+# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
+
+# sys.path path, will be prepended to sys.path if present.
+# defaults to the current working directory.
+prepend_sys_path = .
+
+# timezone to use when rendering the date within the migration file
+# as well as the filename.
+# If specified, requires the python>=3.9 or backports.zoneinfo library.
+# Any required deps can installed by adding `alembic[tz]` to the pip requirements
+# string value is passed to ZoneInfo()
+# leave blank for localtime
+# timezone =
+
+# max length of characters to apply to the
+# "slug" field
+# truncate_slug_length = 40
+
+# set to 'true' to run the environment during
+# the 'revision' command, regardless of autogenerate
+# revision_environment = false
+
+# set to 'true' to allow .pyc and .pyo files without
+# a source .py file to be detected as revisions in the
+# versions/ directory
+# sourceless = false
+
+# version location specification; This defaults
+# to alembic/versions. When using multiple version
+# directories, initial revisions must be specified with --version-path.
+# The path separator used here should be the separator specified by "version_path_separator" below.
+# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
+
+# version path separator; As mentioned above, this is the character used to split
+# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
+# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
+# Valid values for version_path_separator are:
+#
+# version_path_separator = :
+# version_path_separator = ;
+# version_path_separator = space
+version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
+
+# set to 'true' to search source files recursively
+# in each "version_locations" directory
+# new in Alembic version 1.10
+# recursive_version_locations = false
+
+# the output encoding used when revision files
+# are written from script.py.mako
+# output_encoding = utf-8
+
+sqlalchemy.url = postgresql://gpr3:gpr3.admin@localhost/gpr3db
+
+
+[post_write_hooks]
+# post_write_hooks defines scripts or Python functions that are run
+# on newly generated revision scripts. See the documentation for further
+# detail and examples
+
+# format using "black" - use the console_scripts runner, against the "black" entrypoint
+# hooks = black
+# black.type = console_scripts
+# black.entrypoint = black
+# black.options = -l 79 REVISION_SCRIPT_FILENAME
+
+# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
+# hooks = ruff
+# ruff.type = exec
+# ruff.executable = %(here)s/.venv/bin/ruff
+# ruff.options = --fix REVISION_SCRIPT_FILENAME
+
+# Logging configuration
+[loggers]
+keys = root,sqlalchemy,alembic
+
+[handlers]
+keys = console
+
+[formatters]
+keys = generic
+
+[logger_root]
+level = WARN
+handlers = console
+qualname =
+
+[logger_sqlalchemy]
+level = WARN
+handlers =
+qualname = sqlalchemy.engine
+
+[logger_alembic]
+level = INFO
+handlers =
+qualname = alembic
+
+[handler_console]
+class = StreamHandler
+args = (sys.stderr,)
+level = NOTSET
+formatter = generic
+
+[formatter_generic]
+format = %(levelname)-5.5s [%(name)s] %(message)s
+datefmt = %H:%M:%S
diff --git a/alembic/README b/alembic/README
new file mode 100644
index 0000000000000000000000000000000000000000..98e4f9c44effe479ed38c66ba922e7bcc672916f
--- /dev/null
+++ b/alembic/README
@@ -0,0 +1 @@
+Generic single-database configuration.
\ No newline at end of file
diff --git a/alembic/__pycache__/env.cpython-310.pyc b/alembic/__pycache__/env.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9e3a2c5a169bdb0cf54b69293663ac4b024e6a9c
Binary files /dev/null and b/alembic/__pycache__/env.cpython-310.pyc differ
diff --git a/alembic/__pycache__/env.cpython-312.pyc b/alembic/__pycache__/env.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..214d2b1b289193fffcc463e8e71fe0c9eb358eff
Binary files /dev/null and b/alembic/__pycache__/env.cpython-312.pyc differ
diff --git a/alembic/env.py b/alembic/env.py
new file mode 100644
index 0000000000000000000000000000000000000000..36112a3c68590d6a8e07fea0ce70a5afb38c951a
--- /dev/null
+++ b/alembic/env.py
@@ -0,0 +1,78 @@
+from logging.config import fileConfig
+
+from sqlalchemy import engine_from_config
+from sqlalchemy import pool
+
+from alembic import context
+
+# this is the Alembic Config object, which provides
+# access to the values within the .ini file in use.
+config = context.config
+
+# Interpret the config file for Python logging.
+# This line sets up loggers basically.
+if config.config_file_name is not None:
+ fileConfig(config.config_file_name)
+
+# add your model's MetaData object here
+# for 'autogenerate' support
+# from myapp import mymodel
+# target_metadata = mymodel.Base.metadata
+target_metadata = None
+
+# other values from the config, defined by the needs of env.py,
+# can be acquired:
+# my_important_option = config.get_main_option("my_important_option")
+# ... etc.
+
+
+def run_migrations_offline() -> None:
+ """Run migrations in 'offline' mode.
+
+ This configures the context with just a URL
+ and not an Engine, though an Engine is acceptable
+ here as well. By skipping the Engine creation
+ we don't even need a DBAPI to be available.
+
+ Calls to context.execute() here emit the given string to the
+ script output.
+
+ """
+ url = config.get_main_option("sqlalchemy.url")
+ context.configure(
+ url=url,
+ target_metadata=target_metadata,
+ literal_binds=True,
+ dialect_opts={"paramstyle": "named"},
+ )
+
+ with context.begin_transaction():
+ context.run_migrations()
+
+
+def run_migrations_online() -> None:
+ """Run migrations in 'online' mode.
+
+ In this scenario we need to create an Engine
+ and associate a connection with the context.
+
+ """
+ connectable = engine_from_config(
+ config.get_section(config.config_ini_section, {}),
+ prefix="sqlalchemy.",
+ poolclass=pool.NullPool,
+ )
+
+ with connectable.connect() as connection:
+ context.configure(
+ connection=connection, target_metadata=target_metadata
+ )
+
+ with context.begin_transaction():
+ context.run_migrations()
+
+
+if context.is_offline_mode():
+ run_migrations_offline()
+else:
+ run_migrations_online()
diff --git a/alembic/script.py.mako b/alembic/script.py.mako
new file mode 100644
index 0000000000000000000000000000000000000000..fbc4b07dcef98b20c6f96b642097f35e8433258e
--- /dev/null
+++ b/alembic/script.py.mako
@@ -0,0 +1,26 @@
+"""${message}
+
+Revision ID: ${up_revision}
+Revises: ${down_revision | comma,n}
+Create Date: ${create_date}
+
+"""
+from typing import Sequence, Union
+
+from alembic import op
+import sqlalchemy as sa
+${imports if imports else ""}
+
+# revision identifiers, used by Alembic.
+revision: str = ${repr(up_revision)}
+down_revision: Union[str, None] = ${repr(down_revision)}
+branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
+depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
+
+
+def upgrade() -> None:
+ ${upgrades if upgrades else "pass"}
+
+
+def downgrade() -> None:
+ ${downgrades if downgrades else "pass"}
diff --git a/app.py b/app.py
new file mode 100644
index 0000000000000000000000000000000000000000..77db412b11cc777a8decf920567745c6822ab46f
--- /dev/null
+++ b/app.py
@@ -0,0 +1,5 @@
+import uvicorn
+from main import app
+
+if __name__ == "__main__":
+ uvicorn.run(app, host="0.0.0.0", port=7860)
diff --git a/celery.txt b/celery.txt
new file mode 100644
index 0000000000000000000000000000000000000000..a442228a2ddec1e44073cb11c9adf60294b2c346
--- /dev/null
+++ b/celery.txt
@@ -0,0 +1,10 @@
+redis-server
+celery -A celery_app.celery_app worker -c 4 --loglevel=info
+gunicorn main:app -k uvicorn.workers.UvicornWorker -w 4 --timeout 0
+redis-cli ping
+celery -A celery_app.celery_app worker -c 4 --loglevel=info
+gunicorn main:app \
+ -k uvicorn.workers.UvicornWorker \
+ -w 4 \
+ --timeout 0
+
diff --git a/celery_app.py b/celery_app.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b588b874666c4ac076323a00bbad32b1b58a3d0
--- /dev/null
+++ b/celery_app.py
@@ -0,0 +1,16 @@
+from celery import Celery
+
+celery_app = Celery(
+ "converter",
+ broker="redis://localhost:6379/0",
+ backend="redis://localhost:6379/1"
+)
+
+celery_app.conf.update(
+ task_serializer="json",
+ accept_content=["json"],
+ result_serializer="json",
+)
+
+# 👇 FORCE IMPORT
+import workers.converter_worker
diff --git a/cleanup.py b/cleanup.py
new file mode 100755
index 0000000000000000000000000000000000000000..18fac5ac88498150a6477d0ace36fcc1d572fbbe
--- /dev/null
+++ b/cleanup.py
@@ -0,0 +1,48 @@
+import os
+import time
+from datetime import datetime, timedelta
+from core.config import settings
+
+OUTPUT_DIR = settings.OUTPUT_DIR
+TEMP_DIR = settings.TEMP_DIR
+TTL_HOURS = 6 # delete files older than 6 hours (change if needed)
+
+def auto_cleanup():
+ now = datetime.utcnow()
+ cutoff = now - timedelta(hours=TTL_HOURS)
+
+ removed = []
+
+ for folder in [OUTPUT_DIR, TEMP_DIR]:
+ if not os.path.exists(folder):
+ continue
+
+ for filename in os.listdir(folder):
+ file_path = os.path.join(folder, filename)
+
+ try:
+ # modification time
+ mtime = datetime.utcfromtimestamp(os.path.getmtime(file_path))
+
+ if mtime < cutoff:
+ if os.path.isdir(file_path):
+ import shutil
+ shutil.rmtree(file_path, ignore_errors=True)
+ removed.append(file_path)
+ else:
+ os.remove(file_path)
+ removed.append(file_path)
+ except Exception:
+ continue
+
+ if removed:
+ print(f"[CLEANUP] Removed {len(removed)} old files:")
+ for path in removed:
+ print(" -", path)
+ else:
+ print("[CLEANUP] No old files found.")
+
+
+if __name__ == "__main__":
+ auto_cleanup()
+
diff --git a/config.json b/config.json
new file mode 100644
index 0000000000000000000000000000000000000000..87f9a427f395caebf56492968ce966ae697b8c63
--- /dev/null
+++ b/config.json
@@ -0,0 +1,16 @@
+cat > config.json << 'EOF'
+[
+ {
+ "page": 0,
+ "type": "text",
+ "text": "TEST WATERMARK",
+ "fontSize": 48,
+ "color": "#999999",
+ "opacity": 0.5,
+ "rotation": -45,
+ "x": 300,
+ "y": 400
+ }
+]
+EOF
+
diff --git a/core/admin.py b/core/admin.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa7da646a62c08c6dac792a07e6a252d148f7c40
--- /dev/null
+++ b/core/admin.py
@@ -0,0 +1,345 @@
+
+
+import os
+import uuid
+import anyio
+
+from starlette.requests import Request
+from starlette.datastructures import UploadFile
+from markupsafe import Markup
+
+# Import WTForms fields
+from wtforms import FileField, SelectMultipleField, StringField, TextAreaField, SelectField
+
+from sqladmin import Admin, ModelView
+from sqladmin.authentication import AuthenticationBackend
+
+# Import your application-specific components
+from core.database import engine
+from core.config import settings
+from core.models import (
+ UsageStat, AdUnit, AdPlacement, AdStat, AdGlobalSettings, Rating,
+)
+from core.models import ToolRatingAggregate
+# ==============================================================
+# 🗄️ CONFIGURATION & UTILITIES
+# ==============================================================
+
+UPLOAD_DIR = "static/uploads"
+os.makedirs(UPLOAD_DIR, exist_ok=True)
+
+async def save_ad_file(upload: UploadFile) -> str:
+ """Saves the UploadFile asynchronously using a unique name and returns the public file path."""
+
+ # 1. Generate a unique and safe filename
+ file_extension = upload.filename.split(".")[-1] if "." in upload.filename else "file"
+ unique_filename = f"{uuid.uuid4().hex}.{file_extension}"
+ save_path_full = os.path.join(UPLOAD_DIR, unique_filename)
+
+ # 2. Asynchronously read content
+ content = await upload.read()
+
+ # 3. Use anyio to safely run the blocking file write operation on a thread pool
+ def write_file_sync():
+ with open(save_path_full, "wb") as f:
+ f.write(content)
+
+ await anyio.to_thread.run_sync(write_file_sync)
+
+ # 4. Return the web-accessible path
+ return f"/{save_path_full}"
+
+def detect_file_type(filename: str) -> str:
+ """Utility to determine file category based on extension."""
+ ext = filename.lower().split(".")[-1]
+ if ext in ["jpg", "jpeg", "png", "gif", "webp"]:
+ return "image"
+ if ext in ["mp4", "mov", "mkv", "avi"]:
+ return "video"
+ if ext in ["mp3", "wav", "ogg"]:
+ return "audio"
+ return "unknown"
+
+
+# ==============================================================
+# 🔑 AUTHENTICATION BACKEND
+# ==============================================================
+class AdminAuth(AuthenticationBackend):
+ async def login(self, request: Request) -> bool:
+ form = await request.form()
+ username = form.get("username")
+ password = form.get("password")
+
+ if username == settings.ADMIN_USER and password == settings.ADMIN_PASS:
+ request.session["authenticated"] = True
+ return True
+ return False
+
+ async def logout(self, request: Request) -> bool:
+ request.session.clear()
+ return True
+
+ async def authenticate(self, request: Request) -> bool:
+ return request.session.get("authenticated") is True
+
+# ---
+
+# ==============================================================
+# 📊 MODEL VIEWS - STATS & GLOBAL SETTINGS
+# ==============================================================
+
+class UsageStatAdmin(ModelView, model=UsageStat):
+ column_list = [
+ "id", "tool_name", "usage_count", "last_used_at",
+ "open_count", "process_count", "download_count",
+ ]
+
+
+# ==============================================================
+# ⭐ USER RATINGS ADMIN
+# ==============================================================
+
+class RatingAdmin(ModelView, model=Rating):
+ name = "Rating"
+ name_plural = "Ratings"
+ icon = "fa-solid fa-star"
+
+ column_list = [
+ "id",
+ "tool",
+ "rating",
+ "created_at",
+ ]
+
+ column_searchable_list = ["tool"]
+ column_sortable_list = ["created_at", "rating"]
+
+class ToolRatingAggregateAdmin(ModelView, model=ToolRatingAggregate):
+ name = "Rating Aggregate"
+ name_plural = "Rating Aggregates"
+ icon = "fa-solid fa-chart-simple"
+
+ column_list = [
+ "tool",
+ "average_rating",
+ "rating_count",
+ "updated_at",
+ ]
+
+ column_sortable_list = [
+ "average_rating",
+ "rating_count",
+ "updated_at",
+ ]
+
+ can_create = False
+ can_edit = False
+ can_delete = False
+
+
+
+class AdGlobalSettingsAdmin(ModelView, model=AdGlobalSettings):
+ column_list = [
+ "id",
+ "all_ads_enabled", "banners_enabled", "popups_enabled",
+ "predownload_enabled", "sidebar_enabled", "mobile_enabled",
+ "audio_enabled", "rotation_enabled", "updated_at",
+ ]
+
+# ---
+
+# ==============================================================
+# 🎯 AD UNIT ADMIN (Final Logic for File Upload)
+# ==============================================================
+
+# ==============================================================
+# 🎯 AD UNIT ADMIN (Final Logic for File Upload)
+# ==============================================================
+
+class AdUnitAdmin(ModelView, model=AdUnit):
+ name = "Ad Unit"
+ name_plural = "Ad Units"
+ icon = "fa-solid fa-ad"
+ delete_redirect_url = "/admin/ad-unit/list" # <-- 🔥 ADD THIS LINE
+ column_list = [
+ "id", "name", "placement", "ad_type",
+ "file_path", "priority", "enabled", "created_at", "vast_url",
+ ]
+
+ column_formatters = {
+ "file_path": lambda obj, _: (
+ Markup(f" ") if getattr(obj, "file_type", None) == "image"
+ else Markup(f" ") if getattr(obj, "file_type", None) == "video"
+ else Markup(f" ") if getattr(obj, "file_type", None) == "audio"
+ else "-"
+ )
+ }
+
+ # ... (Keep form_columns, form_overrides, form_args as they are) ...
+ form_columns = [
+ "name",
+ "placement",
+ "ad_type",
+ "file_path",
+ "preset_size",
+ "custom_width",
+ "custom_height",
+ "priority",
+ "enabled",
+ "target_devices",
+ "target_categories",
+ "target_countries",
+ "vast_url",
+ "html_code",
+ "duration_seconds",
+ "skippable_after",
+ ]
+
+ form_overrides = {
+ "file_path": FileField,
+ "target_devices": SelectMultipleField, "target_categories": SelectMultipleField,
+ "target_countries": SelectMultipleField, "placement": SelectField,
+ "ad_type": SelectField, "preset_size": SelectField,
+ "html_code": TextAreaField, "vast_url": StringField,
+ }
+
+ form_args = {
+ "target_devices": {
+ "choices": [("all", "All Devices"), ("mobile", "Mobile"), ("desktop", "Desktop"),
+ ("tablet", "Tablet")],
+ },
+ "target_categories": {
+ "choices": [("all", "All Categories"), ("finance", "Finance"), ("photo", "Photo"),
+ ("pdf", "PDF Tools"), ("developer", "Developer Tools"), ("games", "Games"),
+ ("education", "Education"), ("shopping", "Shopping"),
+ ("entertainment", "Entertainment"), ("fitness", "Fitness"), ("news", "News")],
+ },
+ "target_countries": {
+ "choices": [("all", "All Countries"), ("US", "United States"), ("IN", "India"),
+ ("UK", "United Kingdom"), ("AE", "UAE"), ("CA", "Canada")],
+ },
+ "placement": {
+ "choices": [("landing_top", "Landing Top"), ("landing_bottom", "Landing Bottom"),
+ ("tools_top", "Tools Top"), ("tools_bottom", "Tools Bottom"),
+ ("tool_popup", "Tool Popup"), ("predownload_video", "Pre-download Video"),
+ ("download_page_banner", "Download Page Banner")],
+ },
+ "ad_type": {
+ "choices": [("image_banner", "Image Banner"), ("video_ad", "Video Ad"),
+ ("audio_ad", "Audio Ad"), ("popup", "Popup Ad"),
+ ("vast_url", "VAST URL"), ("html_snippet", "Custom HTML Snippet")],
+ },
+ "preset_size": {
+ "choices": [
+ ("none", "Custom Size"),
+
+ ("300x250", "300 × 250 (Medium Rectangle)"),
+ ("336x280", "336 × 280 (Large Rectangle)"),
+ ("728x90", "728 × 90 (Leaderboard)"),
+ ("970x90", "970 × 90 (Large Leaderboard)"),
+ ("970x250", "970 × 250 (Billboard)"),
+ ("468x60", "468 × 60 (Banner)"),
+ ("234x60", "234 × 60 (Half Banner)"),
+
+ ("320x50", "320 × 50 (Mobile Banner)"),
+ ("320x100", "320 × 100 (Large Mobile Banner)"),
+
+ ("250x250", "250 × 250 (Square)"),
+ ("200x200", "200 × 200 (Small Square)"),
+ ("180x150", "180 × 150 (Small Rectangle)"),
+
+ ("120x600", "120 × 600 (Skyscraper)"),
+ ("160x600", "160 × 600 (Wide Skyscraper)"),
+ ("300x600", "300 × 600 (Half Page)"),
+ ],
+},
+
+ }
+
+ # ===========================
+ # 🎯 CORRECTED LOGIC: on_model_change (The Final Edit Fix)
+ # ===========================
+ async def on_model_change(self, data: dict, model: AdUnit, is_created: bool, request: Request):
+ """
+ Handles file uploads and multi-select fields safely before database commit.
+ This hook fixes the AttributeError when editing without changing the file.
+ """
+
+ upload_value = data.get("file_path")
+
+ if isinstance(upload_value, UploadFile) and upload_value.filename:
+ # Case 1: NEW file uploaded and it is not empty.
+ try:
+ # Save the new file using your existing function
+ data["file_path"] = await save_ad_file(upload_value)
+ data["file_type"] = detect_file_type(upload_value.filename)
+ except Exception:
+ # Fallback on failure (retain existing path on update, clear on create)
+ data["file_path"] = model.file_path if not is_created else None
+ data["file_type"] = model.file_type if not is_created else None
+
+ elif not is_created:
+ # Case 2: EDIT operation and NO new file was provided.
+ # This is the essential fix: explicitly retain the existing file path/type
+ # if the form element was present but no new file was attached.
+ data["file_path"] = model.file_path
+ data["file_type"] = model.file_type
+
+ else:
+ # Case 3: Create operation with no file, or explicitly removed file.
+ data["file_path"] = None
+ data["file_type"] = None
+
+
+ # 2. MULTI-SELECT FIELDS HANDLING (Required for your setup)
+ # Ensure list of choices is converted to a CSV string.
+ data["target_devices"] = ",".join(data.get("target_devices") or [])
+ data["target_categories"] = ",".join(data.get("target_categories") or [])
+ data["target_countries"] = ",".join(data.get("target_countries") or [])
+
+ # Call the parent method
+ # Note: The original logic for insert_model and update_model is now gone,
+ # and all necessary pre-save modifications are in this single hook.
+ # super().on_model_change() is technically not needed here unless the parent
+ # class has custom logic you need to run, but keeping it is harmless.
+
+# ---
+
+# ==============================================================
+# 🎯 AD PLACEMENT & STATS
+# ==============================================================
+
+class AdPlacementAdmin(ModelView, model=AdPlacement):
+ column_list = [
+ "id", "ad_unit_id", "placement", "priority", "enabled",
+ "custom_width", "custom_height", "created_at", "updated_at",
+ ]
+ form_columns = ["ad_unit_id", "placement", "priority", "enabled", "custom_width", "custom_height"]
+
+
+class AdStatAdmin(ModelView, model=AdStat):
+ column_list = [
+ "id", "ad_unit_id", "placement", "impressions", "clicks",
+ "last_served_at", "updated_at",
+ ]
+
+# ---
+
+# ==============================================================
+# 🚀 SETUP FUNCTION
+# ==============================================================
+
+def setup_admin(app):
+ """Initializes and configures the SQLAdmin panel."""
+ admin = Admin(
+ app=app,
+ engine=engine,
+ authentication_backend=AdminAuth(secret_key=settings.SECRET_KEY),
+ )
+ admin.add_view(UsageStatAdmin)
+ admin.add_view(AdUnitAdmin)
+ admin.add_view(AdPlacementAdmin)
+ admin.add_view(AdStatAdmin)
+ admin.add_view(AdGlobalSettingsAdmin)
+ admin.add_view(RatingAdmin) # ⭐ ADD THIS
+ admin.add_view(ToolRatingAggregateAdmin)
diff --git a/core/config.py b/core/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..6011fc9241a0816fb96a4d5ce570f69d3d07d9bc
--- /dev/null
+++ b/core/config.py
@@ -0,0 +1,31 @@
+from pydantic_settings import BaseSettings, SettingsConfigDict
+from functools import lru_cache
+
+class Settings(BaseSettings):
+ DATABASE_URL: str
+ ADMIN_SECRET: str
+ SECRET_KEY: str
+
+ # 🌟 REQUIRED: Admin login credentials (FastAPI Admin)
+ ADMIN_USER: str
+ ADMIN_PASS: str
+
+ # 🌟 Ad Manager settings
+ GAM_NETWORK_CODE: str
+ DEFAULT_SITE_URL: str
+
+ # Optional directory paths
+ TEMP_DIR: str = "./temp"
+ OUTPUT_DIR: str = "./output"
+ UPLOAD_DIR: str = "./uploads"
+ # Pydantic v2 config
+ model_config = SettingsConfigDict(
+ env_file=".env",
+ env_file_encoding="utf-8",
+ extra="ignore" # ignore unused environment variables
+ )
+
+settings = Settings()
+@lru_cache()
+def get_settings():
+ return settings
diff --git a/core/database.py b/core/database.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fe8aad61b584e42647c6fda03c55c1e6a253092
--- /dev/null
+++ b/core/database.py
@@ -0,0 +1,32 @@
+# core/database.py
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker, declarative_base
+from sqlalchemy.pool import StaticPool
+
+# SQLAlchemy Base
+Base = declarative_base()
+
+# 🚀 100% in RAM using SQLite (Zero external DB, 100% Free)
+# StaticPool ensures all FastAPI threads share the same in-memory database
+engine = create_engine(
+ "sqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ future=True,
+ echo=False
+)
+
+# Session factory
+SessionLocal = sessionmaker(
+ bind=engine,
+ autoflush=False,
+ autocommit=False
+)
+
+# Dependency for routes (kept identical so nothing breaks)
+def get_db():
+ db = SessionLocal()
+ try:
+ yield db
+ finally:
+ db.close()
diff --git a/core/dependencies.py b/core/dependencies.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc625ca14823383818459dcc63b16f6d7e644662
--- /dev/null
+++ b/core/dependencies.py
@@ -0,0 +1,20 @@
+# core/dependencies.py
+
+from fastapi import Depends
+from sqlalchemy.orm import Session
+from services.stats_service import increment_tool_usage
+from core.database import get_db
+
+def LogToolUsage(tool_name: str, event_type: str = "open"):
+ """
+ Logs tool usage automatically when added as a dependency.
+
+ tool_name → name of the tool: "audio_compress", "pdf_split", etc.
+ event_type → "open", "process", or "download"
+ """
+ def log_and_pass(db: Session = Depends(get_db)):
+ increment_tool_usage(db, tool_name, event_type)
+ return None
+
+ return log_and_pass
+
diff --git a/core/models.py b/core/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c958d91ca898ba2136d8700627e317478db0fa5
--- /dev/null
+++ b/core/models.py
@@ -0,0 +1,188 @@
+# core/models.py
+from sqlalchemy import Column, Integer, String, DateTime, Text, Boolean, ForeignKey, func
+from sqlalchemy.orm import relationship
+from sqlalchemy.sql import expression
+from datetime import datetime
+from core.database import Base
+from sqlalchemy import Float
+
+
+# -----------------------
+# AdUnit
+# -----------------------
+class AdUnit(Base):
+ __tablename__ = "ad_units"
+
+ id = Column(Integer, primary_key=True)
+ name = Column(String(255), unique=False, nullable=False)
+ placement = Column(String(80), index=True, nullable=True) # canonical placement string
+ ad_type = Column(String(50), nullable=False) # image_banner, video_ad, audio_ad, vast_url, html_snippet, popup
+ preset_size = Column(String(32), nullable=True)
+ custom_width = Column(Integer, nullable=True)
+ custom_height = Column(Integer, nullable=True)
+ file_type = Column(String(32), nullable=True) # image/video/audio/unknown
+ file_path = Column(String(1024), nullable=True)
+ vast_url = Column(String(1024), nullable=True)
+ html_code = Column(Text, nullable=True)
+ click_url = Column(String(1024), nullable=True)
+ priority = Column(Integer, default=0)
+ duration_seconds = Column(Integer, nullable=True)
+ skippable_after = Column(Integer, nullable=True)
+ enabled = Column(Boolean, server_default=expression.true(), default=True)
+ created_at = Column(DateTime, default=datetime.utcnow)
+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ # CSV targeting fields
+ target_devices = Column(Text, nullable=True)
+ target_categories = Column(Text, nullable=True)
+ target_countries = Column(Text, nullable=True)
+
+ # relationships
+ # FIX: Added cascade for placement editing/deletion
+ placements = relationship(
+ "AdPlacement",
+ back_populates="ad_unit",
+ cascade="all, delete-orphan",
+ single_parent=True
+ )
+ # FIX: Added cascade for stats deletion (Resolves 500 Error)
+ stats = relationship(
+ "AdStat",
+ back_populates="ad_unit",
+ cascade="all, delete-orphan",
+ passive_deletes=True
+ )
+ # FIX: Added cascade for impressions deletion
+ impressions = relationship(
+ "AdImpression",
+ back_populates="ad_unit",
+ cascade="all, delete-orphan",
+ passive_deletes=True
+ )
+
+
+# -----------------------
+# AdPlacement
+# -----------------------
+class AdPlacement(Base):
+ __tablename__ = "ad_placements"
+
+ id = Column(Integer, primary_key=True)
+ ad_unit_id = Column(
+ Integer,
+ ForeignKey("ad_units.id", ondelete="CASCADE"),
+ nullable=False
+)
+
+ placement = Column(String(80), index=True, nullable=False)
+ priority = Column(Integer, default=0)
+ enabled = Column(Boolean, server_default=expression.true(), default=True)
+ custom_width = Column(Integer, nullable=True)
+ custom_height = Column(Integer, nullable=True)
+ created_at = Column(DateTime, default=datetime.utcnow)
+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ ad_unit = relationship("AdUnit", back_populates="placements")
+
+# -----------------------
+# Tool Ratings (Public)
+# -----------------------
+class Rating(Base):
+ __tablename__ = "tool_ratings"
+
+ id = Column(Integer, primary_key=True, index=True)
+ tool = Column(String(100), index=True, nullable=False)
+ rating = Column(Integer, nullable=False) # 1–5
+ created_at = Column(DateTime, server_default=func.now())
+
+
+# -----------------------
+# Tool Rating Aggregate
+# -----------------------
+class ToolRatingAggregate(Base):
+ __tablename__ = "tool_rating_aggregates"
+
+ tool = Column(String(100), primary_key=True)
+ average_rating = Column(Float, nullable=False, default=0)
+ rating_count = Column(Integer, nullable=False, default=0)
+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+# -----------------------
+# AdStat
+# -----------------------
+class AdStat(Base):
+ __tablename__ = "ad_stats"
+
+ id = Column(Integer, primary_key=True)
+ ad_unit_id = Column(
+ Integer,
+ ForeignKey("ad_units.id", ondelete="CASCADE"),
+ nullable=False
+)
+
+ placement = Column(String(80), nullable=False)
+ impressions = Column(Integer, default=0)
+ clicks = Column(Integer, default=0)
+ last_served_at = Column(DateTime, nullable=True)
+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ ad_unit = relationship("AdUnit", back_populates="stats")
+
+
+# -----------------------
+# AdImpression (optional detailed events)
+# -----------------------
+class AdImpression(Base):
+ __tablename__ = "ad_impressions"
+
+ id = Column(Integer, primary_key=True)
+ ad_unit_id = Column(
+ Integer,
+ ForeignKey("ad_units.id", ondelete="CASCADE"),
+ nullable=False
+)
+
+ client_id = Column(String(64), nullable=True)
+ placement = Column(String(80), nullable=True)
+ timestamp = Column(DateTime, default=datetime.utcnow)
+
+ ad_unit = relationship("AdUnit", back_populates="impressions")
+
+
+# -----------------------
+# AdGlobalSettings
+# -----------------------
+class AdGlobalSettings(Base):
+ __tablename__ = "ad_global_settings"
+
+ id = Column(Integer, primary_key=True)
+ all_ads_enabled = Column(Boolean, server_default=expression.true(), default=True)
+ banners_enabled = Column(Boolean, server_default=expression.true(), default=True)
+ popups_enabled = Column(Boolean, server_default=expression.true(), default=True)
+ predownload_enabled = Column(Boolean, server_default=expression.true(), default=True)
+ sidebar_enabled = Column(Boolean, server_default=expression.true(), default=True)
+
+ # NEW FIELD YOU REQUESTED
+ mobile_enabled = Column(Boolean, server_default=expression.true(), default=True)
+
+ audio_enabled = Column(Boolean, server_default=expression.true(), default=True)
+ rotation_enabled = Column(Boolean, server_default=expression.true(), default=True)
+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+# --------------------------------------
+# APP USAGE & TOOL USAGE STATS
+# --------------------------------------
+class UsageStat(Base):
+ __tablename__ = "usage_stats"
+
+ id = Column(Integer, primary_key=True)
+ tool_name = Column(String(255), nullable=False)
+
+ open_count = Column(Integer, default=0)
+ process_count = Column(Integer, default=0)
+ download_count = Column(Integer, default=0)
+ usage_count = Column(Integer, default=0)
+ last_used_at = Column(DateTime, default=datetime.utcnow)
+ created_at = Column(DateTime, default=datetime.utcnow)
+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+
diff --git a/create_table.py b/create_table.py
new file mode 100755
index 0000000000000000000000000000000000000000..e5086550a8fc810b93746bf4a447c1d6e5a35863
--- /dev/null
+++ b/create_table.py
@@ -0,0 +1,5 @@
+from core.database import engine, Base
+from core.models import rating
+
+Base.metadata.create_all(bind=engine)
+print("✅ Tables created")
diff --git a/create_tables.py b/create_tables.py
new file mode 100644
index 0000000000000000000000000000000000000000..69081644387a49ab923150c801c53fc9e3cdb9e0
--- /dev/null
+++ b/create_tables.py
@@ -0,0 +1,5 @@
+from core.database import engine, Base
+from core.models import ToolRating
+
+Base.metadata.create_all(bind=engine)
+print("✅ ratings table created")
diff --git a/dependencies/__init__.py b/dependencies/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/dependencies/__pycache__/__init__.cpython-312.pyc b/dependencies/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e3db1fb1d2eff37f4ea3694a1c00dd50e4dba6fc
Binary files /dev/null and b/dependencies/__pycache__/__init__.cpython-312.pyc differ
diff --git a/dependencies/__pycache__/__init__.cpython-39.pyc b/dependencies/__pycache__/__init__.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c0ed80ecf3feabc756da4859c244fdff731578ba
Binary files /dev/null and b/dependencies/__pycache__/__init__.cpython-39.pyc differ
diff --git a/dependencies/__pycache__/api_auth.cpython-312.pyc b/dependencies/__pycache__/api_auth.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d99c6b469e513b5caebd85cd24dac80e42494035
Binary files /dev/null and b/dependencies/__pycache__/api_auth.cpython-312.pyc differ
diff --git a/dependencies/__pycache__/auth.cpython-312.pyc b/dependencies/__pycache__/auth.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..903ade920e8f438fc3a3ec44aacb5c9185393444
Binary files /dev/null and b/dependencies/__pycache__/auth.cpython-312.pyc differ
diff --git a/dependencies/__pycache__/auth.cpython-39.pyc b/dependencies/__pycache__/auth.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ed74604d5a2d609e6563ba19c3a8d385401b67a
Binary files /dev/null and b/dependencies/__pycache__/auth.cpython-39.pyc differ
diff --git a/dependencies/api_auth.py b/dependencies/api_auth.py
new file mode 100644
index 0000000000000000000000000000000000000000..57dd2384ebb372c08d1d4b555e418fedf1a3851d
--- /dev/null
+++ b/dependencies/api_auth.py
@@ -0,0 +1,34 @@
+# dependencies/api_auth.py
+import secrets
+import os
+from fastapi.security import HTTPBasic, HTTPBasicCredentials
+from fastapi import Depends, HTTPException, status
+
+# Load credentials securely from environment variables (matching the values in auth.py)
+ADMIN_USERNAME = os.environ.get("ADMIN_USER", "admin")
+ADMIN_PASSWORD = os.environ.get("ADMIN_PASS", "1234")
+
+# Initialize HTTP Basic Security Scheme
+security = HTTPBasic()
+
+def get_current_admin_user(credentials: HTTPBasicCredentials = Depends(security)):
+ """
+ FastAPI dependency function to check HTTP Basic Auth credentials.
+ This protects API routes (like the ones in routers/stats.py)
+ that are not part of the starlette-admin dashboard.
+ """
+
+ # Use secrets.compare_digest for secure, constant-time comparison
+ is_valid_username = secrets.compare_digest(credentials.username, ADMIN_USERNAME)
+ is_valid_password = secrets.compare_digest(credentials.password, ADMIN_PASSWORD)
+
+ if not (is_valid_username and is_valid_password):
+ # Raise an exception if authentication fails
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Incorrect username or password",
+ headers={"WWW-Authenticate": "Basic"},
+ )
+
+ # Return the username on success (or any user object if needed)
+ return credentials.username
diff --git a/dependencies/auth.py b/dependencies/auth.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f53370f4b63ee70f563a232f44e6aa4b1b66514
--- /dev/null
+++ b/dependencies/auth.py
@@ -0,0 +1,31 @@
+# dependencies/auth.py
+from starlette.requests import Request
+from starlette_admin.auth import BaseAuthProvider
+import secrets
+
+ADMIN_USERNAME = "admin"
+ADMIN_PASSWORD = "admin123"
+
+
+class BasicAdminAuthProvider(BaseAuthProvider):
+
+ async def login(self, request: Request) -> bool:
+ form = await request.form()
+ username = form.get("username", "")
+ password = form.get("password", "")
+
+ if secrets.compare_digest(username, ADMIN_USERNAME) and secrets.compare_digest(password, ADMIN_PASSWORD):
+ request.session["is_authenticated"] = True
+ return True
+ return False
+
+ async def is_authenticated(self, request: Request) -> bool:
+ return request.session.get("is_authenticated") is True
+
+ async def logout(self, request: Request) -> None:
+ request.session.clear()
+
+ async def setup_admin(self, admin):
+ # MUST exist — required by Starlette-Admin
+ return
+
diff --git a/e8604869-ecdd-420e-926d-bd6afc04f3fe_map.shtml b/e8604869-ecdd-420e-926d-bd6afc04f3fe_map.shtml
new file mode 100644
index 0000000000000000000000000000000000000000..72d3fae3449d4446d92e2c59f64ff80bca54f472
--- /dev/null
+++ b/e8604869-ecdd-420e-926d-bd6afc04f3fe_map.shtml
@@ -0,0 +1,3 @@
+
+
+
diff --git a/fastapi b/fastapi
new file mode 100644
index 0000000000000000000000000000000000000000..0975dc59445bf1290abb058c1ced3a7b42929565
--- /dev/null
+++ b/fastapi
@@ -0,0 +1,11 @@
+python -c "import fastapi; print('FASTAPI OK')"
+pip install fastapi
+pip install "uvicorn[standard]"
+pip install python-multipart
+pip install aiofiles
+pip install pydantic
+pip install requests
+pip install python-dotenv
+pip install psycopg2-binary
+pip install pillow
+
diff --git a/filespath.sh b/filespath.sh
new file mode 100644
index 0000000000000000000000000000000000000000..938f83ba42d8351d15b3ea1ce05e38b593f96c84
--- /dev/null
+++ b/filespath.sh
@@ -0,0 +1,4 @@
+sudo nano /etc/systemd/system/backend.service
+sudo nano /etc/systemd/system/celery.service
+sudo nano /etc/systemd/system/backend.socket
+
diff --git a/img.txt b/img.txt
new file mode 100644
index 0000000000000000000000000000000000000000..d8b8f569943e239bbe33d58fc99a925c332b860b
--- /dev/null
+++ b/img.txt
@@ -0,0 +1 @@
+iVBORw0KGgoAAAANSUhEUgAAAyAAAABkCAYAAAB+UVSPAAAACXBIWXMAAAsSAAALEgHS3X78AAAQAElEQVR4AexdB4BU5dU933vTt7NLEVSw94JoDCj2mij2XmIvsYs9JtH8GjVqrDExSmJi79gwJhpBEXsvwa70sn2nz7z3/nPf7CxL21lgFVjuuGe+fu/9zvfUe96b2bVgaj2FcqDXgF4Deg3oNaDXgF4Deg3oNaDXgF4DP8Y1YEFfyoAysJwYULfKgDKgDCgDyoAyoAysegyoAFn1zlx3rAwoA8qAMqAMKAPKgDKgDCw3BlSALDfq1bEyoAwoA8qAMqAMKAOrHgO6Y2VABYheA8qAMqAMKAPKgDKgDCgDyoAy8KMxoALkR6N6QUfaVgaUAWVAGVAGlAFlQBlQBlY9BlSArHpnrjtWBpQBZUAZUAaUAWVAGVAGlhsDKkCWG/XqWBn4cRmwouU/rkP1pgwoA8rAIhjQLmVAGVAGVIDoNaAMrCIM9D3nNtSe8DuYUHQV2bFuUxlQBpQBZUAZUAY6MbDCVFWArDBHoYH0BgZMpGyx21jeTyCMbaP6gF9itSsehAmGFxvn0g4c94vDccVvL1rlUIovwwm1fWr4DkTCYcSiKgB9MvRNGVAGlAFlYJVlwFpld64bX4iByy49F7/59QUL9fe6jh9wQ+Xb7csE/2EEB623kJfVb52Ayp+dAFj2QmM/Rkd+7nTMue08zLj8IHi5TI+7/OCDTzB+/GurHEoRaYzBxRefjQ3WXxdXXnkxIpGeF3+lYtBxZUAZUAaUAWVgRWLAWpGC0ViWHwN/vuN6nHfe6TjttONwy82/X36B9ALPsWG7Yo0/vYrak66Cicz73oVVUYO+p/8Ba9w+EZFNR/zoO63/66Vo+/e9gOvgh3h98CEFyAQKkFUMpbh0PQ/XXXcrxo69F48++jQam5pLLenV47o5ZUAZUAaUAWVABYheA1h7rcEYMeInGDhwE6y55hYYPnwbv0+pWXoGjB1A9X6nYc2/voWKXQ+fz1BojfUw6Jqn0f/iv8GuXW2+MW30PgZsy8IdFPh7730ozjzzJP13q/cdse5IGVhZGNA4lYEVhgFrhYlEA1luDEyfPhO2beOgg/bFMcccimg0ghkzZi23eHqT40BNP/Q793YMuuGFhT56Vb79KKz5lzdRc+j5+sXw3nToC+zFcV2cfPK5+O77qXzCOBrTps2AvpQBZUAZUAaUgVWZgVVPgKzKp72YvWeyWey558H+3dnjjz8So0YdhXSm578jsBj3q0R3ZINhsKJlC+3VisTQ55jLMPD3Y7G8vhuyUFDa0aMM2JaFTTbZ0Lc5cOAA1NXV+nV9UwaUAWVAGVAGVlUGVICsqie/wL6n84nH9iN/jh123BfffjdlgVFtLisD6c/fhZtKLGTGTSfReN81mHHZ/j/YdzMWcrocO1ZF1/IEZL311sFppx6HE044CrNmzV4VadA9KwPKgDKgDCgDHQyoAOmgQivKQM8zkG+agzk3n4XpF+y5kMCIT3waU07bFk0P3wgvm+p552pxhWHggw8+xlFHHYJ33vkA8qX0FSYwDWRVYkD3qgwoA8rACsOACpAV5ig0kN7EgOfk0fzUXzDllJ+g7aUH59taduqXmH7pKMy+7gQ4DTPnG9NG72PAtiz/44077zwKm266ITbcYOFf0dz7dq07UgaUAWVAGZjHgNYWZEAFyIKMaFsZWEYGku++hKlnjETD3ZfDS8c7rLltTZj754sw9cztkf5kUke/Vno3A/IRrFNOPR95x8FVV/8Rkz//sndvWHenDCgDyoAyoAyUYEAFSAmCdLjnGFgVLMVfewYzrzgMuekLJ5nTzt4RreP+ttBHsVYFXlblPVrGYMTwbXwK5FdeD+jfz6/rmzKgDCgDyoAysKoyoAJkVT153fcPwoCXXviL5kVHbmre05Bin5a9nwH5zof89quTTzoGxx57GGbNnrM8Nq0+lQFlQBlQBpSBFYYBFSArzFFoIMuPAUPXBO9UY0GA/UuKBW10p72kPnp6fndiXNScpYqDdK9iP1988TW22WYrvP32+6vYznW7yoAyACgHyoAysCADKkAWZETbqwADFBWLSqYX1WctMFfaRSxq/srYJ/uZL27+Z8EUscD+55vHMVm7OCw4d1FtX8D07kvO4r633XYYTjn1PDiOg9UHrQZ9KQPKgDKgDCgDqzIDzDJ+nO2rF2VghWCAyWAh52XyzCTbWDZ82FIGWF8EZKwIq9O4zbr0F21I6bfZ33neouqytnO/tGXtIkF7/riUjFPmiK8ipL0g/DGL+xFwjbQXnOO3abMYx4I+iuPF/uK87pb++nbf4t+SWAQ2GBghZ9AO9N6XfATrrrvv9Tf4rxf+i2nT9Tef+WTomzKgDCgDysAqy4C1yu5cN77qMWCY7Ir6KAoPJshgco0Ak/BACCbYjlB76beDMDIm8NsLjyEYhMCw9OdKudBcrguFYYoIdq5zTNaIj85YlA3pkzmcLz4FJhAsxFgcYxvcE/wyCAQCRJBzFkS7X1kncUlMwQjMItEpXn+urF0c6CdISJwSA+voiCcAkHcjsESIGF6HhH82rPbCn8qKctxy8+9hcY/XXvNr9Kmp7oW71C0pA8qAMqAMKAPdZ8Dq/lSdqQyszAwwyZXwmQQaSXwlAZYEmcm0FY7BRKIEy2gZrEg5TFRQBhMRxFgKpE5wjhH4Y1FYYSLE9Sx9O749md8OmUtYnG/RbgEVKJTlfjm/n/Z1nF/ob/fZ0eY4ffh+xSfrJlLoK5SMh32WxETMm9ceI8f8ebKGNjviiDGmhcD4YgKOdcRe5sdcWNc5ttg8noo+WBb8x1CMxwQjMOQedgAFISL/GeL5GELOqJehtS2OBx98HBMnjsN//jMBjU3NvWyHup2uGdBRZUAZUAaUgQUZkP/zL9inbWVghWFAUtJS6FawvhEDw6cfkI8CMQGWpxFWuAyGCbZdVoVAebUPu6JQdrTZbxN+2x+rKczjGjtWCdtP2sth+WUlLPYLxGYRslbs2uU1sCv6wK5kWcmygmW7bbu8CsX5dntfgPMDFRIP57GUfrFtldEPfVsCqQu4vthvKBaMiB5C6hb3aMUq4M8vlozTt8cYLMZksbT9uOiro2SMjFPGrGLJmPw247FYFxt+7OXVsGhzHhhjWQXsmKAcVowQwSPCJ0wRIk9eKEJg+J8hY3iMRbC6jD9FS8tSLmMI8y0fOXI4xoy5D9tsM3S+fm0oA8qAMqAM/IAMqOkVlgH+n3+FjU0DWwUZmD9hnNcyWPQ/mK9fWgVgvpfxW0bmWgYWk14rGMTW5QMxtGI1BJjEb1WxOtauGACrshbDKgehsrIONhPuLSoGYUu2A0zQh1VyTtUA7FQ1GDtWDcFIwirvA6usGnY76sprMVTmMzHfkvN3qhyCnSoHY0diI/qStTtx3U+q1kCgqg6bVA2E9O1Im9IfoM/BlQUfA6v6w66q5fhaxBAEGFOfyn7YuWotbMm4bPqoqajFzvRRVVEHiXFL+h5Q0Q8BCgFfzMQqIQJgU+5t7fL+sChShtP3OvRhU3DsQL9rsb5T9WDfx7Zs29X9sH716mwX/G5QNQhB9g2vXBPie+eqIdiaNraqXAMjqtaETc42rVodG1UMhMSyc+Vg7Ew7P+X4MPK6MfctokR48GOgONqpYg30jVTA2EFABKGx4L+M/+6/SXV+GDnBBQC2i5g3XuwplvNGFl8rzi2W82YWe7BUr2gkghdfnIAxf7sfzz//IirKy5fKji5SBpQBZUAZUAZ6CwPt/9fvLdvRfSyCgRW+yzDCAorvhkmlgVyclmG5GBhTHAPnCwrr5q9JS8AxzoexYawALD4B2SHSH/+t2BYbRGvxYngz7BEdgOmBofinvT5m2UNxSnQwrgyv7UOeQtwUWhdHhNbAOGt9/DEwBLcG18IX0a1RE6tCgHf3ry/bAP+OboGTwqvjpuj6nLsabguujecDG+BXwTXwC/aPM+viN/YgPIR1cD/9nB8cjIes9XB5cAguDw2BTVFxTXRdrtkIV9B3gMJnHMcFe5YNxDmRwRzbAL+LrgO7rAKbxPpiXGhj7BRdDZ+Gh+K0yBr4a3RDbFfWH4FIOVaLVWNyxXa4O7YJxse2wvkx+g1vjOOia/pi5AV7AxwZGYTnvbXxO2sQ7sVg7m9dnBoYiEe9wbjMGojXvHVxBmMfY4bgTrMmfhVYHceHBuIPjP0lsz72iQ7EZaE1cRrnXEZ+nghugLuD6+J01m+MrIeLGWsgVokzo4Nxf8Xm2Kucfqq3RobnIALEWDaMMQUAMIAPeTeszYP0LIh5owaAJTCAZUCYDhhjYEzXsDg+PwADEMZH5xqW4JVKp/H+Bx/7Kz786FO0xfXvwfhk6JsyoAwoA8rAKsuA/P96ld28bnz5MmDoXgA/vTN8R0fCaPvJoAWbvQHALwt106le7LdgG6tjrWXAVQLD0gD+uym8G7YszmXSe0duGupNHk8HNsBYuxVbmRjy8LBt1Rw8HUrhdKcGlm1gWRaCoRgMDVu2DXDO/2wHn9l5VMOGFYwgEIpge1OFjRHFNqYMnwfyuDLair+E2iCvA2L1+CDkcKWHN4MOpgdc1FpcS8B4vu1/BzPoEy7HAU45Hg4lMIplKBLjcg9vB3I40a3GkW4V3rFzgGX5PgPyMSZjsHawDIO9IA7lnIQFtPAJjx2O4KBgf6xpQjjVno31Ql/h9jDjMZxgB2BFyiAvYwelwNsR4LuAhxrasQIBtDHaSexrNUCdFYGxLFiGDZbjonnABDDL9nBbvh9qTRAzaGb/2BxMt/IYG0jijEg9DOdaRCAcxZWBemxFbm4JrY//y3xLAQLImGUMjCEwPywAxhjIuMBmfUFIv6DYbxkLNoowCABLDBuGNgQWbPoU+wWAI+BL4kR7HSVeOqwMKAPKgDKgDCgDCzJgLdihbWXgx2DA+E4MkzjDdBGQBE+SPZs9AQETv6APC0FjI0SELZZEsZS+EBPOwjyDAOfbXGvD6kgcjTGwDGCMYWlgAwW4hfL2/HSsjiBut5ow1eQRg0GVazDIsdHiuch6wGqsB9nf37HgGBrgzxdWFhu4QfzHSiALF0HPw/nWdJwVmInJJosbsn0x0DOwaQN8BVwP1By0AnwUyGJYzsbYcAY2x6ZaLm6KJPByMIv9cxH2AJvmQ6jk+lGZQvueSBp7Z8N4285gNhN8i5aEJ5ulR6HwjpXC6HAjfhWqxzAvggvdOu7KoAUO7RmsgQBGueXYzitDhvEO9AIY4NkcA1IWN8nae4E8huYsPBrNUGMZJCguWi0H/bnpp6NZzvDwRiiHm6JJfMEYDP3eEGnDXONgh3wYhjMCvikDMRkgJxJnfwqaHbwYQp6Fx9AEmflAbhbnGO7fIwCZZ4wBfwgDixWBDcNxAznbAizWBZ37DOTakXG5FgqlxWvGQpDXjSDEsjsozJV1Fv2Ij0JpA7DkH4mLdcO4QBjoSxlQBlZYBjQwZUAZWGEZsFbYyDSwXsmAJGwFGKZzgCSZlrFgM5kL2XP/3gAAEABJREFUsAwSIREZJoAIEbUCKMBGlO0Y0VH6YzYiLMPsD/tJpsWk0/jJo02bBVi0D9hMiG0AkhgHXQehvINvcgm84cXRkk3gXrce40wb3m/th4zn4ILAbNxpGtBmHExuG4CPmOQ/5zXhTSuDd9w4bjb16C9iJeMgkMngkFwFbsj1wzoULFeZWWhMJzAnl8Ikk0AonUJrLsm1abzhtOK2YAtGpix866URB32lYrg+WYkN8hYuCzZgVGg6Hg/EsUHOw5sUHZOcZoyzE/ibacSXbhKfuwkE6TOVpT2k0Cfj4uxsOc7JVONbN4M/52cgmM3imdxc/NGdibvyA3F6rhrIZvBrzMQmTgCT4gNwR6AZrzgtmGhnMcFtxh/4hOQnaWAK7U/ifsdQMPwrmMZecQ8fmjQGZQ0uiEdwUVsEkxn7jHwCJ9oz8LqVxGzuL5BO40OunUpIfJ9J6Xm4OF+LvfNRfOTEMTHfjGDOQcghb44HCzwbeKDeYd2CDUMAASb7QSJkLISMjbAJEFLabAcIKQsonH3AH5frRq4JgVw7MSsAKbuLiGVD1oqdgl2bsQjA+ABjDMES8mJdCoUyoAwoA8qAMqAMdDBQqmKVmqDjykBPMWB8Qwb+P0ziRHzY7CskmlYheZRkkcmmJI1ldhDlVhAVRKUdQmdUcKyCfeVW2J9TxnWyRhJHSVRDTFaDTFyD9BMwYAJpYLMdYgoZYtIbdl2Eczm8n5iFX7R+ADfZBhNvxRWZbzEi/ylOy32JhmQTvk014pTsl9iOfZdwLJ5owUlsf56ci0nJWTgx+SkS6VbEmHhfn/wSmyTfwqHJj/D3xHeIJNowMTkTx3FOlPWPk3NwYvpzWPFm3JWdjstz3+G+zAyckv+6HV/iT5mpeIZ9Zck4rsx+h3+kp+PE3NfIJpoxOvcNPk/U40/p73Bj8luEkwl8l2zA0alP8H5qNvZguWfmI5yS/gxTU02IpJMIpVK4KfkV43oD+yc/xBuc92xyGnZMfYgh2XdwUeprvJ+YjZ/lPsWcljm4JfUdjs19gbvSU3FR9lvYrc04Pf8NxqSn4cL89zjO/RrHO1/jqvx3uI7xvc09zUk04ajUZPwrOQMh7vOi5Od4JDEN0VQC16S+wfGpz3B88hPcn5qChxK02/YJovkswq5DeHwywvPhVRGQswJ4TobnZVNI2hQZAcgTLxGdIiDkjIuQtt/P60XEQozCQcY6XzcVvHaK10rn66dYl2toHoL+tVZhhTquqSivqwjtixAJsgzwGrIZq0UwXL5DX8qAMqAMKAPKgDKwhAxYSzhfpysDCzEQGrIJokN3Xqi/c4fxG8ZP2IwxlAGmI9GUu9siHKJMIEVIlFNYSIJYzUSwmvWaQAR97HZIXeC3w6gJhFBth1FFVHK+JJxiQ2yJzRCFiNgPwUaYXkOeQRRAmeuhPO+iPJdDBZ8kVKYyqE4lUZUQJFAtJRP8qkSCffNQzXZlog2VHK/keCUT/IpUGuXtKGM7xv4yojyZZH8SFbRbmWTZvkZsVLXFURUnEgLajwtSEP/VCSnjBR/iK96GCs4t55oyzo8xhrJkHGX0IShnou+XbFfQVwVjKE9nUEZRFMukEGE7xDkBiiyLIstQRLnxZrjxJnhtDXBbGuEQbmsDvJYGgHXDMsAy1NqISFszom2tKOPacpblEg9jKWdshXjaEKXtqB+TxBVv33MKwk8V/VcxnirGU5lJozKbJ+8OyigEo3w6EvEshHg2QWNRdLDOUs5Mkn45xzKKiHIRnCxFHBQQ9EVCuR2AjFf44yFfpFbxOqiW64bXxHzXjn/NRCDXUg3rAqn3kXk+IqgOhCFrq7hersHC9RTkExQbYWMxPpviyDBa8Fo2KLwM64WavisDyoAyoAwoA8pAaQas0lN0hjKwaAas8mrUnX49Vr/lZYTWWH/Rk9hrCDBFk9IYQylgmMQBQaZxYd5VjhJlvNMsiWWVnwiGIYlhLYVG30AMfQNRH/2CkULJdj/C77ejqGO9lomjJJvVXF9JiK0yK4gYRU3Eh+UnkTH6KkcAFUx6q1ygj0PkXNTmHNRmHdQxOa7L5FjPoS6TZ5t1aRN9sjn0yWZR69dZsl3DtTVcV5PPo4piplJAGxVEZY59nFuTcdCH9VqOiX1ZX5fJoi4tyPhlLdsF0Af7+6RZsq+GqKZAqpIEvr2sZL2SviuISvFDH1VcU83Yaji/hnHX0F8N9yTjZRyPcE0onUIgFYehiDHJViDeAjfRSjRBBIkXb2ZfMwzLAMWGPM2Icq6Im0oKmOpkGjUUEYJqluKzknZFvFUytgofWVTSbxVjqGZshX2TV8ZTm/NQlyffjosacl/lARU8izKeiVwDEV4Zcj0I5MxiVqAgLigoCqIiTMFZgJyzXCtVfAImpYhPKX1RwWuhjtdOHa+Lfrx+5Fopwr9m/P4I+nJOAVHWY5D5dbyeajkuoqSaIkVsllOMSCwFQWvBfwpiLF69BsYQ0NcKyYAGpQwoA8qAMrDCMmCtsJFpYCs+A0y+uhuk4URjDFNMgo0ga2Er4IsC+ciMCAZJKmspHiQRLCSMMey04wjsve8eOODoA3HEacfgxItOxbHnHI9DTjgM+xy8D3bbc2esN2A1FBNNWduHCajYqmLiKMljuRVkIhtAGZ+GSL2CfqtMELVs18FGPybA/ZlODnBtDHAtgqVjQb7fIV8878++/nxyIu1+rBdRx3qda1DLsT6OQR+W1Q5QzacrNUQf3uGv5bjM6cu5/Wm/P8sBtC1+pN6f4/2YjBdKA6n3kz7a6ctkvW/eoC/LOs6p5RMbsVnDseq8hxo/kffQh23x05fr+tK+lHUsJR6Jo5LzYhRIYSJIERTIpmH4JMJQkCCdANJJmHQchk9PLNblexwhiolINoMyipwqiodqCq0+tFNLvyIi6rjfOtkf+yQOiaea7RqiD1HLeCWWfoyjP8Vefy+AQmmhn2ejjvKzjwmhimch51HO8xCxGGVbEKNoLOO5VfDJRhWvCRGXtRQMtRQFIg76sC4itbr9rDvG2d/PFx0xDAgSrA8IlmM1qROrBcvYX4b+LPsHWBKF+VFeQ0Qwir600fk6qrRCvH6CiPJ6EXEU4PViw8Ay4Dv0pQwoA8qAMrAAA9pUBkoxYJWaoOPKwOIYcNuaUP/nCzHtvN2QnfL5IqcxR2O/AbUHLBhI0iYJnHzRPMJETpJMSfBqmEhKgtmXCeOeP98do2/7Le7+fBwue/p2nH3vNTjx9stwxDXnYL9LT8LBV/wSx/7xQpx+95W44JEb8WfOu/LRW3HIiYdj03XXQT/ewRZbNRQg8jGuCisEQTmT2UoryKQ3hAkt72Nc41t4vH4SHpj9Cu6Z9TLunvUi/jrzP7hz5r9x54x/468z/gNp38W+u2a8iLuJMcTfZr6Iv898Cf/kmvtnj8fDc17B43Mn4qk5r+GGsX9CHwR8nHjRKXiS/Y9wXObdM+u/GMO1YlPs3znjBdw5nX7acRd93k2fYwSc93fiH8S9XPfgzJfxKOMcO+dVPDv3NWy3/TaoYUIsvp5h+0n2P8Lxh2ZPwEP09ygh8bxQ/yYmNr6DCgqBKMVDiILBdl1YTh5wcgAFCXJZllmYfA4WRUqAYyHHQZRCYuR2wzB+7pt4nnt7ctYEPDJrPB7ivh8mHmP7qdkTcSP3XEuBUeuJqAsxvkn+vh+eMwH3cd49M//r8yX7v1f4IidPNbyOQ39xMGqtMGqISp5NOc+pjAIkxjMqY72c5Y4UoBPbPsKLcl7N7+LZ5nfwHMvniZvH3Q0RIUUx8sfn7sLTTW/j0cY38EDDJPyjfiL+Vv8K7p47AXfNfaUdE/z2GLZlTPD3+ldxDyHz761/jWtf922IrX+3vAfxf9bl5/hfTA9ZFk/XQH5xAq9qFAB9KQPKgDKgDCgDysASMGAtwVydukQMrDqTs998hNQH4xfasPF7DJM0EAZysQX4Lp/v7xAfFAk1vMMtd7a3GbYl/m/s7Tj3/mux/dE/R0XfGnT3tfGuP8HRN4zGje8+ipN+fRZWL69GLYWI3BkvPg2pYlJbRX/VRHftLum8AHdaSWEgT1jkY0VLur6782PGRhWfIojA6s6aMj7piRoLQQ8I8OmMRSFiCFBowC9dGNZt1/HHQ56HKPcS5TqUeMl3N2ooFnzwSUaJ6R3DJ954EbbaYlPIE41qXgOVPBcRISI8BBVsx3hmHQsWqMi1JNdODeeJDRG2C0zpsWbAWAgRQV6/AWPIimENZAgA2waFf6AvZUAZUAaUAWVAGSjJgFVyhk5QBpaBAcO1xhgmawaSuAWZxIWJGO90Fz9eI3ewT73iHFz50hhssMMwLOtrr/OOxm+evQO77bMbRNj04dMVSXCrmOQWEFpWF4tdb3GvxeRZ9rnYics4IAKunE8NKpn4d8dUmW0jQt5DTJQDhCXwAEOhYTyKD3isA/KrcAOA/4XrKIVUxNhsdf0jQqCaIqCa/NYEQl1P7jRq2RZOuPFCCsUIari2SvZDOxXck0D2VsbrBIt5iSgQn3Km1VwX5J46pvZwxaZt8SdPPoQ749svvPtVfVMGlAFlQBlQBpSBbjNgdXumTlQGlpiBQoImF5nFqi0JMCFJrS9AeHe7monneXf8Fnudc9QSW+9qwRpbboBTxlyJEbtsB7k7XvxCsSS1krB2tXZZxiwmqiHLhv+0oRvJ+9L6krvxPo8UCd2xIWIizHhEANpyFiI4uNAYD6I82AWLdYuVAPcg8yLGomixUeoVMAbyMboKioUKEyo1fb7xwVtvjON+fx5qAxHIF8irKCQqiYp2xChGsJiX+K3geAWfulTwWrIZ72KmLnM3aSErhphnysyrak0ZUAY6MaBVZUAZUAZKMWCVmqDjysDSMCDJmQ9jmLQZ2LD4BMSCn5wzaSxnwiiJ5qjjDsKIw/dGd1+N//se6YbWbk23gwEcc/sl2GyrzSFCpyO5pf9uGVjKSTZ3HJD9slxKE91aJn6C3Uy65Qv/QZ5FgPMtxmUEBnwXmI5SxmzOE7shCpaQZVDqJWtEKJSR1zKKkFLzFxwfcfL+2PmQvSEflyuIkHDhOzu0J19GX3B+sV3wG4D4jtGv8FEc6+nSpWBz4PIfjzW0g+Ktpx2pPWVAGVAGlAFlYOkZWGlWWitNpBroSsmAYdRykflJLZNyuQsftWzIb74a2Lcv9j3/WM4o/fPWNffhnm1Oxn27n4u7tjwOT+7/K8x974uSCyv698EhfzgXIj7kLnm5CaKMQIlX85tf4Otbn8LkW8bik1uewIc3P4b3bnoU7xBv3fQI3vjjQ3jtxgfx6o0PYPyN9+OlG+7Dizfci68nfegnqYYpPfP4El6Ab297Gl/Sz2e3PImPb34c79PPu/TxNn28+ceH8Tr9TKSfCfTzX/p58cZ78R/6cT0mvwZk1JT0IROCDCZA8SFJutUeW2Fl4R3SB8AY49uUeYX5Fkq9LK6J0LacbYRnW5G+shUAABAASURBVGr+osb3u/ZMrLPWYFTzyYeclYhTeQoS6eIJjwWDMMfFr5QSx6Jsd+77+tanC2d68xP4YAGuJ/3xQUwkJgjP5Pj5G/6JsX/4Gx6+9i445DvvuRAsKETAMY+SRNDZl9aVAWVAGVAGlAFlYNEMWIvu1l5lYFkZMEwPQRhIYmjDQvGuepR31st4x3rE3juiZvX+KPV66Yyb8NqfHsfM6bPQ4mbR4mTx1duf4InDr8C0/76/8PIFegZssS6G7bOj/4frynhXXQTQAlMW0fTahQET1Zsew9t/FNHxMEXHA3jlhgfw8g0iOu7FC0xSx13/Dzx7/T14hniO9ZznwKEMWYTRhbqa3vycCfGTFB+PQYTHWxQdkgi/SsExnomwCJv/UHQ8f8M/8Nz1f8czf7jH9/X5a+8zGe5+yitPZERUyFlQL/jngo53qYGv9jPjBJlns8fmHBZd/licE+SZBilCAiy7nLyYwVBFDAdefw7kN2JV2+GCYKRQlI+OYTEviTFAn+I3aAqxL2ZqR/dXvth7wheU71DkvUG+XyPXrxDjea4vXV8402d5jk9cdzceuvZu/OPav+Cvv/8Tsq6LHMWGiBERgC5FhzwL8Tqsa0UZUAaUAWVAGVAGusOA1Z1JOkcZWBIGTHFye1JoMUGVJyABJothIkIREKMA2fbA3YozF1vWf/QNPn7qFbS6GTQTTRQfzW6a9SyaEnH87/GFf/vWooxtefjuKKPPKBHpRpIse/CYYLqEJJwOyxzvgOeYgGYpMARpioy0l0eKkDLt5pFhPcc5sobFokJZqE/muewVH3KHPef7cZGlnwyljNhNuw4KyEN8ZTlH5soaLi35I8m6MYYnAaJYYr6X8Vtm3jjnyzq/u8SbCJUiSkxd7PCaI7fAXpeegGorhCrCfwJS4omK+LR4TVkUuIaRL9b4AgMuz9OlcnB5hsKhcJlnPUtkyLWcY5r8p3mewru05Tzy7MvzwGSNx5ImFrCsTWVAGVAGlAFlQBkoxYBVaoKOKwNLw4DhoiIkibWZHAaY0AaZ/IsIGbzOEKy341ac1fXPZAqMuJujAMmi2cmgyUkTWT4FyaCNT0M+emo8GihSurYCrLnLVogFQxDf8t2GUvPBeA2B9pckmp4kre1wjMcnEK5/R1wS0wzvjosoEOQkSeU8md++fLGF78MUhwsr5N2/w84E1yFyPhyKG9eH3InP+j4cOBQixdVdlYZ7KQCsYbEvwxEBOMv4QMmX4QxjDIwxvgzAMryGnXUgNttzBPyPYVGodvUExNCPxTeLXEvJZskf+Q8el8D4/8ipmo41Pue05bBHREau40wdZKlWcuQ6TzgUKa4PI5++4mz9UQaUAWVghWBAg1AGVhoG5P/HK02wGujKwsC8pI45qZ/qWazIExARICHe1V536Ebd2szU9yYj4eXQ5uR8EdJK0dHKpyAiPtooTJJ86tDw5dRu2aqoroKIjwBFUMkF3MJ6Z++PTc85EEPPOxg/Oe9QjBh9OEaOPgI7jj4KO48+GrtfcAz2uuBY/PzC45FnQioJqqCYpEp6W8pPn203wEbnHIDNzz0Iw+jjp+cfhu3OPxI7XHAkdrrgaOxK7HnhMdj7wl9g3wuP80WP+MozUc7TgcuylA8Z53Z4DlKbH6X7Zcb8axbVklmCRY117stPa+jcXGR9+2tPRd+6OsgTEHlitchJ7Z2GuyqivavLYuv7L8LIBy/DHg9djn0euRIHPvI7HPbo1Tjq8d/juMevw8mPX48zn7wRF4y9Gb9++k8Fvik68jzfPLkWcSJChZqQLa8TunSrg8qAMqAMKAPKgDLQiYHeJ0A6bU6ry5cBQ/fGTxDh3xm3+R6gEAkaC/2GDOJo6Z/WxhakXcf/mJOIDUGCwiNB4ZFimeaTgKYps0ob4oxoVYX/m7gCho0SP1U/WR/rnD0KG7aLg63OO4Qi5DAMP/9wX4TsTBEiAkSEwSgKA/k4jsskVZJTh9mplNQHJbwAg8/aF+udvR82odDZ8tyDsXWHCDmCQudI7EqhsydFzj7ig9ZceHzq4UHsu6xLye6SP7LlAox/IsV3sCUotgul9OAHec24/MGSdiN9q/DT606G/NKArgWIRFvS3HwTaij46rbdEP1+ujFWIwYN3wSrD98Uaw7fDENGbIa1R2yOdUdsgQ22G+qv88ixQwjPLoWIf7bSJrpzvr4RfVMGlAFlQBlQBpSB+Riw5mtpQxnoKQaMGDId6a08ARHYFCDycay+gwfKhJJoa2pBliIj67r+x48yFB5+W/qYEEp97udTStqRCdHqMkgMlh+V9PQcJFF1mZGKKPDrP0iCKpYLED8uhY5nurcHwz0LLE63DAo88CysDkifx1loh2EpwBK9Sk3OUEzOuOWZUtPQb7eh2PD0fbv8OySm3Qq3wFjbGz1ceLQn8Pn268I/Kz+YR7GtUAaUAWVAGVAGejcDko/07h3q7pY7Ax2JIiMxTNwEtYNXY6v0T6Kplc8VPDhM6B0KjkLJttSZgLvS78hXuEvbMkY8w48APfySCArwGC8YlTiQ1FXKnoFYc6k4XFZ88UEvrHbLuGUA24DCw4INgWEJQkqB9BEGsMhTASBX6NGXfJn7qz89i6aJn5W0u+bo/RG27C7nmR6PcH53ns9x5/fCuPQUavquDKwwDGggyoAyoAysNAxYK02kGmivYqDh+5nd2k9ZnyqmmIU002qvScuHgd9TM2QAuvPKtiaZToo46G7a3h2rhTl5iiFfING0iAMRCawWBnvo3RdblDcOIfUiumPehuV//CxoLAQpMEIsQ8ZGyC8t9ln+eIB9Ac6VtN9iaQxJRvdehf0W3he3Qj5O1+Zk8O7Fd8NJZRc3raN/jf87sqP+Y1dEZMhZ8mj966bov+sdFmdpqQwoA8qAMrDqMKA7XVIGrCVdoPOVge4zUEjV5F0gyZwPpnMN38/olpkKCpAAk+RC4mx1JMySOAd5/17Gqtco/bdExFm6NQERBvKkQto9iayXR85/KuP6T2tc7rEn7Ysth5lw1nP8L0Y79CVcyndPZKwUhL8QxYX8FrCI/CpiHzbkOxYdbX/chvySgADrAQORIFiSl5xzV/NTjF9+ecCc6bPx5kV3djXVHwuuWeeXXb+Zroc7jcrfXal/YzJmv/EZZr7xKaa//immvv4Jvp/0Mb6d9JH/hyS/eO0D/O+1wt+Xkf14nc5SPBUg750Ma1UZUAaUAWVAGVAGus2ACpBuU6UTSzEw37hkbuyQ5M0Hk2dJyuXuvcP63O+69wSksrbG/x6AJMoLw0aYKXLVoL7ozivV0kZx4Ppf4i41v/HNyRh/xNV47rAr8eghl+OfB1+Cuw+6CHcccAFuPuA8/GH/c3DVqDPxm31PxyX7nIKU6/jfVZFfweuIOGDS2h1xMOnIa/Hvw6/C2EN/gwcP/hX+Tj93HnghbjvgfNxIH9fsdxauHHUGfrXvaXj31bcg36HI0n6e9v3fyMSy1F5kXP72ifxK25gVRBlRTlQQ5VbI/wON5RQkZXYAMZYyN0wBEiRsPmNCD75Sbh5tThatxMdPvYL//fPfPWC9/WLrhqU3jroW/z3iKv9cHz/kN3iAnP/joEsw5uCL8ZeDLsCt5P36/c/G/436JS7d51SyW7BtaNsiF8YH+O4R0JcyoAwoA8qAMqAMLAUD1lKs0SXKQLcY8DiLWoNJHOCLDzbko0o5JtDffPA/jpb+WX/XrREzAT9Jll/LWsmEWcpyJs+SSK+xwdpYY4ctShpqmjwFqXSaTykc/1fmllrgMNavJ32Iya+9h4+J9199B2+/8ibefOUNvD7hTeJ1THqFmECwL8nEOs2nIFmukz063KPsv5QfSci/5N32Tye+hw9eewfv+j7exBu0+Trr83y8jtfpL0UfGT5FEA7FhzwFKeVDxkW8ldlBVBBV5LDaDqHajqDGDvtlFUvhtsBrgE9GbD5tsv2PZaEbL9lrEV1Nl9jjbg4tbgYtFCEvXPZnNHz2XVdLSoyJV/jXWImJ/rCcTY5nlOP5ZH0eHeR4deYoIHPsL3A6z55FmWHzCZxNoWuxbhnDmmHNQF7F90IpPcsN6lgZUAaUAWVAGVhpGLBWmkg10JWIgUJSKAFLzWV6KIldXhI9Jn4ZJtFTv56Cr195T6Z0iQ0P2gnV4Sgq/YRZkuV5kIR5y4N2gRUMdGlDBr988hX/1/lmXNcXIdLXFSRmuUvf7GbRmE+jwUmj3kcKDXmC9SYnw0Q6i7iTQ9LL+fZzTGrz3KfDPXtEVz5kLEkuJBFvYkIufuppu95JoV58st6Uz6CZfiSWBBP3FIVOhhzmCPHjdsOH+BGxVmlCqKbQqAmE0ScQQR1RS9SxXev3RyBCRARejAJPnoTYTLVlfSnIXovoaq48wYlzH/IxrBbuWfY27sLbu1rS5ZhcXwUU3ruczMHCR/A8iHCTj+IJfx45lNUc5m4NLAPYsBCk8AjyKVDQLwvtAGfYbFvtQgQsDfSlDCgDqzYDuntlQBlYUgasJV2g85WBUgxIMtcZkuzJx4Xk7nOWCbok0Ekmoe888d9SplA2sBY7Xng0qkwYNbxzL4lzHyuMamLYqJ2w9VkHlbSRT2fx0ePj/Y9JpZnwiwgptcjh3XA/SeZdekmSRRwUkEEjxYf0tVAYyMeJ5gkDB1kRBoRDSIJbyk+K4kX+uKLYEkHTRH+NFB2N9CFt8SPjkrQnKD7SvFOfJXK0Lz6E01I+ZHydEVtgo+2HYsvtt8E2I7fF8B1+ihE7DsdIYvsdt8P2O47AiB2G46c7bIthI7fB5tsP8z/6FmCyLeu7gpy1nHERXc3N8PxFdLVR2LVwr80sJ7/3Cf57xZiuli1ybJ5f+IJC2ouc2KnTGFBaEKzY7Le5P9sz/pOeEOsiNuTjZ2ErAPkNXCLCBFIvjtswtGH4Dh/QlzKgDCgDyoAyoAwsEQM9JkCWyKtOXgUYYDrIJJ7vfB7goZAsO5AENMVEOkm8+fwEdOePCA494wDsf/to/OTA3TCgTx+st/mG2OHUA7H3Xy5Ad17v3DkWM2fMRJzJrvhN8WlFqXXyBCNOkSQCQ54+tPJuvYgESZoF0tdG8SCiIElBkOaTFREfIgwEeXj+vkv5STMhFz+t9CV2iz7EfivtS788YRE/Ij5kfpZr8hQgOfIrvJbyIeO7P3Q5Dnjkdzjqsd/jpMf/gDOeuBHnPnkTRo+9BRcRFz91KwQXsn7ekzdjo+22giTiNhN1Wd8VPO5V4skznjzj6mpulqwkefay5zaeh+y3mULuP3c+gs+fm9TV0oXGCn49/0v5efqWa22hSQt0bHjOAdjivIPxk/MPw/ajj8ROxG4XHoM9LjgGe8kffLzoOOx30Qk4+OITccQlp+LYS0/DSZedgV/+6iyEKEpEoATIifBiGVCAGAL6UgaUAWVAGVAGlIElYEAFyBKQpVOXjAFJCCVJlDvjktDnmJzK3fsUE9AEE+5Z9Q24g9SrAAAQAElEQVR46qq7u2V03QNGYs/bz8Ppn9yHo174I7b77fHdWvfh/S/guev+jlYmu21eFnGKjyT9l1rsMKFNMEZBnGXcySPOdVKXviT7UnyakmJfhmWWyFEYCPLcZ44QG6X8pLgmTlsJxpdgWajnIPUE+5K0n6LtDEWO+BG7RYifLP0AKOVmicflLn+ATwRMN1a68PwnP1nupVQ8cv7CXYJ7FQEn5yICRJ72PHbRzUjObe6Gx8IU+ZJ/wadD/w6kXRhZ/Pv6Z++HTc85EEPPPRjbnHcohp9/OLY7/wjsQCGy0+ijsMvoo7E7xcjeFCOjLjwOIkSOuuQUPiExkCcgwolNXizKDuNDfElNSoUyoAwoA8qAMqAMdIcBqzuTdI4ysDQMFAQImJ7CfwKSY1KfYcIsCbUk2q288/3yEy/g6SvuXBrzJdckG1vxwOgb0ZRPQ5LcVifr/wYm8V1qsdt+p16S5VS7CEizTIsYYKKdEVAUZFnmuKcCPN6N9yD1LJ+IOLRRyk+a65O0m6StFJPyog/p932IP45lOS9H/nIsRXjk6DPLuqCUj6UZN8b45ybfmSi1XubIUyU5Vym7mi/7Svr7FUGX88+jhefSnM9g6tw5eOKiW7paPt+YywhT5EBsSumwPd+EHmxYsChCBIa1AjpkhwFAvgwM9LUqMqB7VgaUAWVAGVhSBlSALCljOr9bDIj4EOkhd6UlUZSnIJI4S8KcZkKd4BMFEQTNThpP3n4fbt/vPDjZXLdsd2fS9A++wGUbHYgGipxGoplJbot8pIllK58slLIhTy8SFARJP8HNo/AEwuGddtcXGDkKgDwFhg+/7lF8uBwrzMlQOOQoGEr5SfvJeA4ictK0kyFEvGRZ5gjhLC9+inWWOSbaWcaVIVL0U8rH0ozLeYkPQan1DuNrI7dx8iVlV/ML+823P+HJoY1r5DzkuyBNFCETn3sZr97xWFcmOsby5DfOJ1pFyJl1DPZwReRYQV6YDplhetiHmlMGlAFlQBlYQgZ0+krLgAqQlfboVp7ARYy4DNdhoppjAp1m0pygCGhl8tlMcdBAEfLWa2/j4g33x1v/fI4zl+3npZsfwP/tcQrq80kiBfl4j/hpoa9W+m2hCCnlIc8kP8H4UhQIaT7NEEEgCa/D+POEw00JJFF3ONdhMiz9Mk/2l+S6LAVCKT9JciFzJTHPsp7jmhx5cnwfLp8cwf+CdYcPGpQ5WY6nRcjRD7t6/CfPGBJM7pOMp5Rx2XcLuRJepexqfop7jDNm2bM8XUqw3sbzaOXZyDk18mnVvb+9Dd+99WlXZvwxiVHWiZCVUtr+wA/wxuP2z8HjWUu9iB/AlZpUBpQBZUAZUAZ6PQMqQFb+I15hd1BM0opPQSSpzjFxzjChTzGxjbcnrY28812fT2FqcyP+Ovo6XL/H6Xj+qjH45tX3u7W3xm9n4I0xT+Pek/8Pl215CP551R2YS3v1TGYbKW4ksZXkuCg+RIiUMiyxSnwpxihPGnKMVxJch0JDxJTLRLSAdoHAfeXZV9ifA0mw5fsOpfwk+SRI5qZpP0sbOdp3WDos5/kRH2j/I4qu/6RFYkoxeZcvqJfysTTjaYob4ayNgq3U+hzjbfJ5TlPspbucLk++EuQ0ydgLyPFpSB5tfIIi59JIISLnNubC67u0I4N5ctTE+U2+7wx5kStORnoe4kv2medeHZ6z1w7fk7hlLNLnt/VNGVAGlAFlQBlQBrpkQAVIl/To4LIzUEjLRIQUfhWv639MKcMEN8lEtI13v/3Ek2JBRMjsXBLvvPMBHr75Hlx34Lk4q98u+N1WR+L2/c7FA7+8Bs9f/Tc8ccmtGHP05bh+p1NwyXqjcPm2R+HuS27EC0/8C59PmYI5vvhItf+63CxamaRKIt1GX3K3vJnlHlVbYf+an+Dw2uE4tm57/II4unY7HNpnOPapHoYzf3YC5IvnSYolSfZzTDKLooBVpp9oh/FLEQt5JqEiIkRcJbi3O66+HXvT1kF9tsVRtP2LupH0NRJH1o7AAfQtMUx8ZRIT8Jz/N0REsOT55MGlRbEn6OxLvmshMUgsGcYlTyfi9LNr1VDuZVscXbs9Tu67I84kZ+f23w3nD9gdo9sh9fP7747z2H9u/11xNnEWcQbnnt5vJ67bAScwvmPqtvPju/fav6CBif0br7xOu9vhOI6d2HcHztvRxwl1O3Av2/v8Xbrv6eRafj1xhmsy3Nu2OKTPTzkmGO7XR9Vsg90Zp+xXYpazF57S7UJE+kQgNtNng5PCex9+7J/FsTyXk7inU9shMUjfYTwn+Qv0jbxuipD24ez/Bdecwvln9NsZ53CPsmfZu3AgdeFG+n0OuP8zOU/mCg/ip7OPUdVbY9fKLfHnq29D4TpwKXRcikGPpySQf0OKpdQVyoAyoAwoA8qAMlCKARUgpRjS8WViQBJoSdWlFBEiybUk2Vne8U9ThCSYgBYST0le05A/9jcnn8RsYlY7/vf9t3h94lt4/pFn8eBNf8PYux7Gy8+/jPc//gTfNszFLIqWWbmEv2YO6yJkGvlURYSGiA5JbuVJQZy+RIiICJG75g2+UEljTi7li5a57e1G3vWXjxLFvTwkSc5SFOSNx6QTcE1BcHj+NwEKdenzxRVT0iyR5l3yBPfX5uXQRFsN+SyfyNAP7c+lr7mSNLsZyPce2hhTkn7StC7fgHG43qFtz/cj3zIQHwSrnrHgsMzBRZZIcV0bIbE20t5c2p+dS2MmOZjRCdKeSb8zfT5TmEX/s9mezTnC9Ry255KvuSwbfGTQwLagnqX0y5w5tD2b47PpZ46A7Xq2Rag0UOTJ0wsfjEX653KtlIJG1ps5p41POpLkJMWzz3DvwlWGXKUopBIcK5xN1vc/h/FKjLN4thK7YLbEzNjljzU2Uqw00mYTBWUjy0a2pX8OY/OvHc6dKWuJGfk4eSHyifbrJQmxNZtzZb5gLvciqGdfAyH25BpqZbwiKP2YGasITYdnLB+/E+nhLdO/IbpYGVAGlpoBXagMKAMrLQMqQFbao1t5ApcErZiouZJg80lBjglclsmcfPQoyUS0jQloCxPJJiaBkszOZQIomN2ehM5mezYTT19sSF36fSQ6iYeUfye+mcmoJI1x2kwQSSa7KfpK+vU8OnzRnySakrSK8Glg4iyJfDPnifhIMsnPWh7yloFLeLYFASwbBfBfH6sAj6XLap7CIWuAFPcZ5x5bKRCakUMjJUMDE9kGLwsROM2SbPt+HCQ5V8RHnutcQyP0BcLQJnzQn7F93x77HSLHaWnOT9JHG/cmMTfQR72XwRwfaczmfma7UqYxh+UcJuiziTl8wiDtuRwXzCHnc9lfz3YDOREOJMZG1psYcyNjFm7qWcocv2Rd/DVSZDVzjy1F8Cybua6Z/bK+gWfRSN/NtN3CfjkTOQ859wxjl6c+IkDSrKe4jzjXt3FeE+MRAVDPWOU6KAi3FIVciiKV58yYm9pFTTN9CKTdwH4RELLGv2Z4jcwiZlOMyLUj5WyKkDnSR0jZGXPZV08bDbQtMche2nhWCcaV5p6yjDPPOB2emStCceX511AjVQaUAWVAGVAGeoyBZTXENGZZTeh6ZaA0Ax0ihBWXyZskcDkKkSyTObkTnmKCl2Cy28qkvIUJZZOfBKZ5JzwNSQjrmRjOJaQsIOX3S6LYwCS1mCzKHfRiwig20+32xUeG9RTFSJI+4kQb/bUw2W1m2cyyiaUIhjjnJYyHtG2QtW3kAwE4hBcIAXYAXjAIBCgK/L4gPOlj3WGZZ3+WyFAkpCwgTkHSajy0wEWL5aLJsBSwHmd/ihCRk6XQyFPgOFzrBoLwbIIlaFd8FXwG4DIGl2N5+spaNmO0kLA8tBEttCv2m4yDBgjykLKe+6mnQJiLPOpRQEOxZH+TyaOJIqmZnBTFRCvHW+GgmbYETSyb2FcoC/0t9Cd7a2Mp/uOModXmXlnKfls5v5V8t/JsBQn6Eu7lyZcIjxzjytOHJPRSlzNKca5cB22MxT8bCgERIj54TTTx2mgmWnheLTyvNpZFSFv6mzneyLmNvC7qWS4ODRwT1NNHA1FYk6GITfvfZZFropU+4oylELeLHPeT51nKx+E88B9ew7ykoS9lQBlQBpQBZUAZ6D4DTJG6P1lnKgPLwoAkakzZIMmbfHzFZQInH2fJ8q6yiANJTFN+AppDnElfG5O/FiaYkggW0cR2Ec1MNAUiOlp5l1rWJLg+xURXklmxKQljjvYLcJDlmIiSFOcl6CPOdpusZZngPF8UUHSkmejniHwoAiccgReJAeEoDEuLpcXShGOQuglzLBT1x71wGE4wjCzLdDiEVCiIJJEg4hQXyaCNJAVMmuJCkGVd/DihEDz6QigGw1JsFm1btG+FI7QfAyJReNEoHJb5MP1wXZrwfdBWG+23UrS0st7KeosgZKMlaEHG2gIWWhlHK/fYZlsQtEppGdaBuOVSNLE0QCJgkOC8JMVOgjbjtCXr27g+zr44ywT9yH5SwUBhX5wj9QT9JGxDex4SFCgpipEkk/cMk3c5g5wvPDzkeVEU4CFH/rMUJZ2vgzaeURvPvFXA60FKacdZl7MWJP2zzEPq8fb5bRxv4ZoCMmhuv1YWVbZwrIAsWrjG98H1cdYTLJO0L9eMxJZj/P5vP+O1K9cww+e/Eh5bLPRHGVAGlAFlQBlQBrrFgAqQbtGkk3qKgc4JmyRwriR0TN9yvJNcECJ5pJnwpQhJ/BJMKAVxlm2ElB2gcJCkM8m5IjpkXYZCIsskNkeIuMnTttMOSXRz9COiJMvxNBPitKxlDPKRKXlikWEynmUynY+E4UTL4MYqgLIqmFglTHk1jNTLWGe/FSuHIaxYGUvOYx/KKuCxdNnvEDmOZaMxZGgrw3aG7Uw0giwFTI5CIs/SiZRRVBAcNz4qYHGeYd2iLUOblvj0wVhYeuWV8BiLw3qec7K+/TKkWaa4NkXb6VgMadoo9iUZhyDFMsXxFEVMMhJBikJJREwqSMFEQZEOBZCmuMlQ9GQ4N8O5gjTnZxivXy+LIUP7WdkL54j/HPeRFVCgZSmiMhRZwmfGWEjzAsoZjwLQpdAAHJ6Dy3MpwmE9L2B/lkIk034+KTkf1uV7MsVzTrGd4tkVRWaGZ55hn7T982Rd5goSvGYKKAgUuV4WjxxFTM7/DWZJ2hc/aZZZ2s/RZp4Q8SGxyrXb+Vrm9vTnx2ZA/SkDyoAyoAystAyoAFlpj27lDXxe4uZ1ehri8p64xzviHhNUz09U/aSSSV+aCWCaiaggxVKQZmIp/RmOCYof6ckxgS0ID1BWuLTvzQN7HElyCZmXY5llspsjshzLWRbyFB8On2a4TKQ9Jv6mggl/OYVHZR2syhrYlX1gV/SBVVFTgIwRlsxjP8pqgMoqoLwGHvsFLkuniLJq5DnmlFOoUDyID1BMGMKioDDtdg1tWT6qfT/StqVN/6aiFoZ1j3WPMblcVmzWqwAAEABJREFU4/ugbYdxOBWVyLPM0me2vArZCvrsDL+P/Ywzx7k5xpGjaMlRTOQpMvIUEA6Rp5jxwfG8gOv8+YxVRE8+Sj+xSojQmh9lFG8xiLjKh8LI8UlJjk9Y5HsuDi9bl0LEJfd+Es/zkl9OIJC2nI9AzlDOJcfzz4gIELAu5yyQ/izbOZ5djjZyLLNsZ6Xk3AzrGf/acJBmPc26oNCXx4KljKU5L+OjMF70k6N9icePndeJxDrvGuaG9EcZUAaUgVWMAd2uMrCsDKgAWVYGdf1SMSAJnABMRD2i+LEsh8mewyTPYZ8kfXkmlJIAFuBSnBThsS6Qtoe8zGckLtdKIitJotgUH0X4bdqXcZnncI38VilJLPPGQL7cLd+/eK52O4yr3AbPlQ3Fc5HNMDq2Dv4V3pjYFM+z3Y8C4OKy9fB42Ra4vnwjrFveD/+KbYXNy/php/LVMS6yJc6OrYVnwpvhGc5/mvh52UBcHVsXT0U3xWblA7BR+Wp4tmIYhlT0hWFif0T5OniwYkvUUliMpd3tywfiqPLBuL9sc4yJbYJNafvO6IaFGMKb4k/hDXFVdB362AQDy/vg3LJ1cGZsMJ4Kb4KxoQLuiqyP30XXZt9GGMv4r4uuizqKligFy1PRzfAw4ZZX4djytTCmaiu40QqI8JKnN25ZBR6uGoYDywfjsPI18aeyjbFzbCCejmyBM6Nr4eno5ngmJtgCl8XWw7OxoXiWfD1bthV+X74x/lq5BU6oXAcun6Q4wSBcOwCXIsSVM+KBuJ4h+yDk9Itgu3g+PHc5nzznF0rPF6dyztKWMyvA84XrvD6vcC3QTo6Q66czcrS7KHSek/fXFewUffjXDPtdxs4fRiUxs9AfZUAZUAaUAWVAGVhiBlSALDFlxQVa9gQDkswJmHq2J6PgEwuBx9IrfFSHSaNDYbEgXOn3k8LC3Hmiw/NtwX8v1OV9Xhu0DRTme7TscSbbsOAZG1dlv0OIZcCycW24BeubKNZECBNDeTwezuASrIaz3Dr8MtKEuQELG4aqMBIxbB+swUiLdS+Kl8J5vBDOYnsvhr9HkpgSDuI4pxr9TAhH2LWoipRje5SjLFz4ONeagTJsgzLcg7XwadBDKFSGu9zV8XA4jWdCOaxNH1uZMoRMABPDDsZF89jUxLCDG8Pf3DWwMetVdgTXRuIYhBBabeCOSBqbIooZAeD0ijacQP8HW3X4ebAv+lhB7OaVYWSoL4YEyzHMqgCiMXh86uFFyoBIDMOtSuwdrMUV3kDcGEmgKhTD9ohhfDCH5wNJ1hmv1YwnrDb83p6LofT1hZXBg3YbtubatQMV8IJhwA4Blk1uhV/DUk68gMI7IKW8y0kICkKFtU7n6y5Ql/MTSL+UAql3hi9ouW5Jy842/DoK0RXeGRfb+qMMKAPKgDKgDCgDS8eAtXTLdJUy0LMMSAJaQPFdkrwCCskoIHef5wNDWHi2rIGf0MoYp3T8SLuA4rvMbQfFjAeXPly8mm9EI/I+XjXy7YWiCYNZtoe1vSCSlocG1p8KpPCdJRECW7phbMQxmf2V7eBjK8uqh7ftHH7qhvC95eCTQB4H58tgW/KvngcvwMQ8EIQk6BUUQD91wkhzaD3DpJ2rp9HHuxQgrwXFFjsMAYOZdsHn9dE4NnUCOCQXRYpjE+005Iv00+nrbTtLHgx2yocxrq0Ws4yLMZEsDsvF8A7jmMY5h7kV8CgOYAxjoU+JxQfrdLUjBU6YY1mbxlmyC1+ZHD42GaniXZPEJ0hhoheHQ2/fIIcPDTnjdI/zPe7TL1mH3wfOoi+p+xbmvRVORcYFhRYZ4vxFvHfqLczues6yjIp9QSGiefFqTRlQBpQBZUAZUAaWjgGmOku3UFcpAz8UA8VEb15ZKn2U9LCA7sbUYZuVjjvnLlNoJw83x2TfY9114WVTAPuqXYPtcwGcmYxirGnF6q6NR5J1mJgaiG1yhX+N/okmPGlaIC8vm6SdQpLuZtM4JBPBZCbtM5BFX9fCyGwhwb8jXYtxyX5YzTFIwMXZ4Xpckq5AwHHQYBz8OVWDcfG+GJ2KcYMeBnHt9lkbJybCfILjYoqbxuhQvbiEl8/BySY5j3EzZieTALinl60UTqbdAZ6FvVIWdsqFMMfL4VMKpFHZCCKOhzW9AMa5a+HPWAOTsD6ucvv7Nu+wmvAtRcW9yVqE8nm/z8ul4QlHbDnZNNxMCg4BePDo181x33zqcJBVg3/FhuLo6BoyQnDBEvzwaPw1K0q5BKHrVGWgVzOgm1MGlAFlYFkZKGROy2pF16/UDNTV9umIv09NdUe911eYJPtJs5R8AiJCw2Ni7TGpvrz1M1yZ/AJuohU3ZKfgMPdrXJ2fhqudafhHZhqGuZ/h5tw0DHc+wcPp6djL+Rwfp+bi5dRs7JWfjGS8Be8l52Cv3GTMSjbg1/mpOC3/NS7Jfoe9zTcYm5uNvfE1fuVMpc3puMOZgSO9b/FQZgZ2xVeYlGnwfVyU/x4nu9/icq47jeVJ7vf+/LvzM/Cr/BQ8n56J+1NTsSf9P8C43Hgrfpn9En9Kfw+XMVyS+wZ/yH2PV5OzfH/fZ5qxm/kaV7DvZOdbHIrv8A9nJiT+q3NT8NfsdMj6u7JTcVD+CzyYnYEDafsSxvFOugF75f6HlkQz9zYbeyY/wLREI9xkm48Dkx/h0eRUuKk2HJ/6FMcnPsVV8cl4JTkToJijYoKvKPDDvaxo+TzjxsDIx8nm9WhNGVAGlAFlQBlYmRnoNbGrAOk1R7n0Gxk4cADOPedU/Pxnu2OXXUYuvaGVdaXHe+xMkOXuvZfPwuPd/I8Ts/Fx2yw48Wb8r3UmxrdOacdUOG1N+Ix9E9qm4cvW2UiwPaF1KpraGjC7bQ4mcK7MaWirx/i2KRxvhKxvbm2AQ8j4h20zMKFtKsbHCZZi7zXacGnrdbbfa5tOW7J+Gl5vnQ6x9xbL8a3f09b3eLt1Gj5smY7prXPgtDbhFfr8jrHIPBn7nPGJrQ9aZ+DTlpmc08h1U2hrKiaJn9ZG1LfOZQxT8CHnTohPx4T4NLydmIV3EjPxVbweE9mewj3MIsZzzacSM/24iRY0xBswgX0JihERaW6yFa8ypinxOZD2m3HZ3zTanI7v0s3+kxHPdShA5KNj5Js/PXm5hIZsgoG/fwplI/bxzUY2HYHVb34Z4XW39Nv6pgwoA8qAMqAMKAMrDgMqQFacs1hukXz08WewLAv77bc3Hnv8meUWR7cd9+REPxH2eHOeFceFL0D4BMRNJ3knP+4n044k2RQiro8mFMqWQslkXBJyHxx3+NTBma+vBQ77C2sKa522ZhThtrXQzjwU+qXdzP5O4JqCjfY+v017FCzS78zntxUiAvw+9su4G5e5zfTbRBTLQt3157RwTRvcZBG0wacp7nx7b4HDJ0Ji25+XisNLJeCmE37pse0KknHaicNjv3w8y8tlyGsOcNt5FsHXQ2doV9Wh75k3YfVbXkZ0s+1gsd3/0nsw6JqnEV570x7yomaUAWVAGVAGlAFloCcZUAHSk2yupLZ223UHfPrpZFx//e049ZRfrKS7WNqwKTz4A8+FR8Bx/GTZy6XhZpLwBEUxIsl1Eek4XEm+fUidYMItSbfHPo9rCmByzrpbXCfJeYpJfrHdUUof0SEAaM+fy7I4R9pFdNhIMI44FvbL2Nvj8X3LOlkjZdFH0a70S53zXR9JFMq4b9tf7/cnCn6EEz4lEn7cbAoeIaW0PfZ3gP2eLz6yFB/k1X8CImTLWRVLqS8d7JoBWP3W8ajc8xgYCmix0ueoS1De/hRE2oqeZ0AtKgPKgDKgDCgDy8qACpBlZbAXrH/xpVfwwr9fxpdffYM7//qPXrCjJd0Ck2H+gALEk49iSaJMIYJ8Hl4uBy/LO/iSSPPJiNcZFCmej/Zxf47Us/DkuyRFzLeeCXsmDUna5wf7/H6WnX34da7xy+JYp3bRv+9jAb/i3++XmBaxVgSCD46Jnfl8sG/BtuxPbAoneT7RID/CUWd47O8Mf8zn1AX8Jx8k2i+X9IwWnu80zcK0s3dC6wv3Qs5NZjTefy3ik56VqkIZUAaUgd7GgO5HGeg1DKgA6TVHufQb2XrYloiEw76B7Ub8xC9XvbdiYiwln4b4SbPctacIoSDxKEi6BZnryprOoJ351nOMybu3IBz2LxKyvvOYtBfAIv1yjcQyn29Zx37xs0j/Mt4Fin7Epl/n3A6uWPf7aV/8dhqnQigIkB4SH8Xr02mpx9zbz8O0c3ZG6uPX4LI9+5rjMP3SUch880lxmpbKgDKgDCgDyoAysAIxsPIJkBWIvN4SyjfffIfrr78S1137W6TTmd6yraXbhyTIC0Hu3i8JRMR0xpKsXZa5nX12ri+LzUWtpW35dVYL8bSI/s7zpL50p1JyVfa7TzHjsv2QaH/6kf5kEqaduzMyX31Qcq1OUAaUAWVAGVAGlIEflwEVID8u3yukt6amZv9L6JtvvjEmT/5yhYzxxw9qEcn0ohLuVawPnffrC4p2nor1zuPFuj/245ygfF+lwxP9y3djOtpaUQaUAWVAGVAGlIEVggEVICvEMSzfIE488Wg8+ODjOP30C3Dppecu32DUuzKgDCgDysCiGNA+ZUAZUAZ6DQMqQHrNUS79Ru4ecx8mvvYmvvt+Ki7/9e+X3pCuVAaUAWVAGVAGlAFloNcxoBvqaQZUgPQ0oyuhvf33+xkG9O/nfxH9hOOPXAl3oCErA8qAMqAMKAPKgDKgDKwsDKgAWVlO6geMc/z4ibjmml9jzJhb8eqrbyzWkw70PAMWDEb3G4rHh/wMz661L/6y+s5YP1y9kKNL+g/DOI4viOfW2ge7VKy+0HzpCBoL5VZoPkQsG/pSBpQBZUAZUAaUAWVgeTJgLU/n6nvFYCAeT6C5uQWu66KhoXHFCGoViKLGjuCjDY7AwVXrImRs/6vaawTL8cH6R+CAqnU6GNivam1cPWA49qwc3IHhZQOwW8Wa2KtyCP6z9v4QW7JgcKgSX290LJKbn4705r9Ey2anzIfEZqcju8UZaNz0FJxUu4ksUawcDGiUyoAyoAwoA8pAr2FABUivOcql38gee+yMW265E6edNho///keS29IVy4RAzcPGokJ8Rn4PN2EKjtEERFCJcsrZ72FR4bshQor6NsbFCzzy+Lb1bNfQf9PrseTLf8rdsE2heq2sf4YQhESpqAp9Cz8bvOpi/j7WcWQhQe1p8cZGDJ4Dcye9T8ceMDPe9y2GlQGlIEfgwH1oQwoAz3NgAqQnmZ0JbQ37vkX/S+gJ5JJ3HvfIyvhDla+kAPG8p98vJmcjWP6bIg7Gz7BDXM/wJeZFuxXvTYcz8WoqrUXubF7Gz/E02vzyUn1xguNrxOumq8v7mYx/Iu78XWmab5+adQGwlIofkAGRgzfBi+99CTa2uK46qpf4Zenn/ADelPTyoAyoAwoA8rAysFAtwXIyrEdjXJpGFahAf8AAARBSURBVDj7rJOx1dDNseEG62H0+b9cGhO6ZgkZqLXDkO9jBIzB2xQhtw7aAY8P2RtvJGd2WBpVuVZHvVhZ67ObKVIasdfX9+Ghpk+K3R1lGAv/K/1Wcjo2mXw7jvz+cf9jXsXJ8nGtYl3LH4aBkSOH480338W6622Da665GfvttzcsnvkP402tKgPKgDKgDCgDKwcDC2crK0fcGmUPMnDHHX/DJZecg9/+9kLcfvvdPWhZTS2OgTY3B7ddDqwVqsRFM1/Dg01f4MDqdTuWvJmaXax3lPeseQDWDffBVavtgp3KF/4Ilddus2MBK0E+bTmzblvcOmhvtH9Si71As5P2S3374Rj4179ewjbbDMVtt16L888/HY899jRcT/544w/nUy0rA8qAMqAMKAMrOgMqQFb0E/oR4ltjjUGYMWMWpk+fibXXHvwjeFQXSTePj1MNiFoBXzL8edDOGFW1FnYqG4SX26ZSKBg81vzVQkTtWD6YY8DWsYEYECxfaHxaPjlfX8jYeHuDU3HDoD1QF4jNNzYzN//c+Qa10SMMfPjRpzj88JNRUVGOX//6Gtx19709YleN/JgMqC9lQBlQBpSBnmZABUhPM7oS2ltttf644ILf4MILf4u6utqSO/j5z3bHy/8du8phrz13KcnNkkwYPXMirhzwE9xU/wGOnPICTpj6Eo6f+iI2jdbhlfh0TMm2+eZSFCt+pYs3z5clwGfpBuQ8t2OmCJDNIv062p0r37Xb79yn9Z5n4N33PsRxx5+JZ5/7d88bV4vKgDKgDPRmBnRvvZYBFSC99mi7v7FJr7+NvOP4d+JfnVj674A8N+4/2HmX/Vc5/OuF/3af1G7MfLltGjaefD8OrVoX96+5Bx5Yc0/8dfVdcHfjp9j9m6c6LIxr/R5vJWdDvqAuuHON/TEgUN3ebsa/26agzcn6819PzMLh3/8L1895D8+0fouP+JSlM8bHp+Ev9Z/g3Bmv4FczX/fX6JsyoAwoA8qAMqAMKAM/JgMqQH5MtpfOl67qxQzMyaew9RcPo/zjO1H58V9Q/cmdeKbl2/l2PDufxPAvH8WGk+/1scvXT2HLLx706xtOvg97f/M0sp7TsWZsyze4ZOYk7P/tcxjKeZ2x69djccb08bht7kdo1O+AdHCmFWVAGVAGlAFlQBn48RhQAfLjca2elIFFMuCxN0cBkSYc/YIy2ViRfjQWZUAZUAaUAWVAGehpBlSA9DSjak8ZUAaUAWVAGVAGlp0BtaAMKAO9lgEVIL32aHVjyoAyoAwoA8qAMqAMKAPKwJIz8EOvUAHyQzOs9pUBZUAZUAaUAWVAGVAGlAFloIMBFSAdVGhFGViQAW0rA8qAMqAMKAPKgDKgDPQ0AypAeppRtacMKAPKgDKw7AyoBWVAGVAGlIFey4AKkF57tLoxZUAZUAaUAWVAGVAGlpwBXaEM/NAM/D8AAAD//94toV4AAAAGSURBVAMA1TDB+ZUDa+IAAAAASUVORK5CYII=
\ No newline at end of file
diff --git a/install.sh b/install.sh
new file mode 100755
index 0000000000000000000000000000000000000000..6441707075bda09e55181464d14761be197d1c75
--- /dev/null
+++ b/install.sh
@@ -0,0 +1,323 @@
+pip install fastapi-admin bcrypt python-jose
+sudo apt update
+sudo apt install ffmpeg -y
+sudo apt install ghostscript -y
+sudo apt install imagemagick -y
+pip install pydantic-settings
+pip install fastapi uvicorn sqlalchemy psycopg2-binary pydantic python-dotenv fastapi-admin bcrypt python-jose
+pip install sqlalchemy psycopg2-binary
+pip install fastapi uvicorn python-dotenv
+pip install pillow pikepdf wand python-magic ffmpeg-python pydub
+pip install chardet unidecode
+sudo apt install p7zip-full p7zip-rar -y
+sudo apt install pandoc -y
+chmod +x cleanup.py
+# system
+sudo apt update
+sudo apt install imagemagick -y # ensures 'magick' or 'convert' binary exists
+# python libs
+pip install pillow piexif pdf2image
+# (pdf2image used earlier; kept if needed)
+# system
+sudo apt update
+sudo apt install ffmpeg sox -y
+
+# python (inside your venv)
+pip install ffmpeg-python pydub numpy soundfile librosa matplotlib aubio faster-whisper demucs TTS
+# extras (optional, help)
+pip install scipy matplotlib python-soundfile
+sudo apt update
+sudo apt install ffmpeg sox ghostscript imagemagick tesseract-ocr poppler-utils -y
+pip install torch --index-url https://download.pytorch.org/whl/cu121
+pip install torch --index-url https://download.pytorch.org/whl/cpu
+sudo apt update
+sudo apt install -y ghostscript poppler-utils imagemagick tesseract-ocr
+pip install pikepdf pymupdf ocrmypdf pdf2image reportlab pillow python-magic
+sudo apt update
+sudo apt install -y ffmpeg libopencv-dev ffmpeg libavcodec-extra
+# For stabilization (optional): libvidstab
+# On Ubuntu you might need to build ffmpeg with libvidstab or use a custom build/distribution.
+
+# Python packages (inside your venv)
+pip install ffmpeg-python moviepy opencv-python numpy scikit-image
+sudo mkdir -p /opt/realesrgan-models
+cd /opt/realesrgan-models
+# Example model files (replace URLs with actual ones)
+wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.3.0/realesrgan-x4plus.param
+wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.3.0/realesrgan-x4plus.bin
+# Or use an anime/video-specific model if available: realesr-animevideov3-x2.param/.bin etc.
+pip install Pillow pymupdf markdown python-magic
+# System (already likely installed): poppler-utils (for pdf2image if used), but pdf->text uses PyMuPDF
+pip install qrcode[pil] python-barcode reportlab pillow
+pip install pygments sqlparse xmltodict requests
+python3.10 -m venv ttsenv
+source ttsenv/bin/activate
+#pip install TTS
+pip install pyttsx3
+sudo apt update
+sudo apt install python3.10 python3.10-venv python3.10-dev
+python3.10 -m venv venv
+source venv/bin/activate
+python --version
+pip install pydantic-settings
+pip install pikepdf==5.0.1
+sudo apt update
+sudo apt install -y libqpdf-dev
+pip install pikepdf==5.0.1
+pip install PyMuPDF pikepdf
+pip install "PyMuPDF==1.23.4" "pikepdf==5.0.1"
+sudo apt update
+sudo apt install -y libqpdf-dev
+pip install pikepdf
+pip install reportlab
+sudo apt install libfreetype6-dev libjpeg-dev
+pip install reportlab
+pip install pdf2image pillow pikepdf pymupdf reportlab ffmpeg-python moviepy numpy scipy librosa soundfile python-multipart
+sudo apt install poppler-utils
+sudo apt install ffmpeg poppler-utils -y
+pip install onnxruntime pillow numpy
+pip install gdown
+pip install realesrgan
+pip install basicsr
+pip install realesrgan[full]
+pip install realesrgan basicsr torch torchvision
+pip install torch==2.2.2 torchvision==0.17.2 --index-url https://download.pytorch.org/whl/cpu
+pip install realesrgan basicsr
+pip uninstall -y torch torchvision
+pip install torch==2.2.2 torchvision==0.17.2 --index-url https://download.pytorch.org/whl/cpu
+pip install realesrgan basicsr
+pip install torch==1.13.1 torchvision==0.14.1
+pip install realesrgan basicsr
+sudo apt install python3.10 python3.10-venv
+python3.10 -m venv venv310
+source venv310/bin/activate
+pip install torch==1.13.1+cpu torchvision==0.14.1+cpu --index-url https://download.pytorch.org/whl/cpu
+pip install realesrgan basicsr
+sudo apt install libvulkan1 vulkan-tools
+
+pip install \
+pdf2image pillow pikepdf pymupdf reportlab \
+ffmpeg-python moviepy numpy scipy librosa soundfile \
+opencv-python pandas python-magic filetype \
+python-multipart
+sudo apt update
+sudo apt install -y ocrmypdf tesseract-ocr tesseract-ocr-eng ghostscript qpdf
+pip install ocrmypdf[all]
+pip install ocrmypdf --no-binary :all:
+pip install pillow opencv-python piexif numpy
+pip install piexif
+sudo apt install ffmpeg -y
+pip install pydub
+pip install moviepy
+pip install --upgrade --force-reinstall moviepy
+sudo apt install ffmpeg -y
+pip install imageio imageio-ffmpeg
+pip install moviepy imageio imageio-ffmpeg numpy
+sudo apt install ffmpeg -y
+pip uninstall moviepy -y
+pip uninstall imageio imageio-ffmpeg -y
+pip install moviepy==1.0.3 imageio==2.31.1 imageio-ffmpeg==0.4.9 numpy
+pip cache purge
+sudo apt install ffmpeg -y
+rm -rf venv/lib/python3.9/site-packages/moviepy
+rm -rf venv/lib/python3.9/site-packages/moviepy-*
+pip install moviepy==1.0.3
+pip install markdown
+pip install qrcode[pil]
+pip install pillow
+pip install python-barcode
+pip install sqlparse
+pip install xmltodict
+pip install psycopg2-binary
+python -c "import fastapi, pydantic; print(fastapi.__version__, pydantic.__version__)"
+pip install --upgrade fastapi starlette
+pip install PyJWT
+pip install PyJWT[crypto]
+# If you haven't already installed the PostgreSQL driver
+pip install psycopg2-binary
+pip install itsdangerous
+pip install starlette-admini
+pip install pydantic-settings python-dotenv
+pip install fastapi-admin tortoise-orm aiofiles python-multipart jinja2
+pip install fastapi-admin tortoise-orm aiofiles python-multipart jinja2
+sudo apt install redis
+sudo service redis start
+pip uninstall starlette-admin
+# then remove imports and admin-specific files you added earlier (core/admin.py earlier version)
+pip install sqladmin sqlalchemy psycopg2-binary python-multipart
+pip install sqladmin psycopg2-binary
+pip install sqladmin psycopg2-binary sqlalchemy
+pip install PyPDF2
+pip install pytesseract
+sudo apt install tesseract-ocr
+python -m pip install fastapi uvicorn sqlalchemy alembic python-multipart itsdangerous email-validator jinja2 passlib[bcrypt] requests pydantic cryptography reportlab
+python -m pip install pydantic-settings
+python -m pip install psycopg2-binary
+pip uninstall onnxruntime torch realesrgan basicsr -y
+pip install super-image
+pip install pillow-heif
+pip install pillow pillow-heif cairosvg
+pip install cairosvg
+pip install pillow-heif
+pip install pillow
+npm install @mediapipe/tasks-vision
+npm install @tensorflow/tfjs @tensorflow-models/body-pix
+npm install @tensorflow/tfjs @tensorflow-models/body-pix
+pip install -r requirements.txt
+# or
+pip install Pillow reportlab
+pip install rawpy==0.25.1
+pip install opencv-python
+pip install opencv-python-headless
+pip install fastapi uvicorn pillow numpy opencv-python rembg
+pip install onnxruntime-gpu
+pip install onnxruntime
+pip install fastapi uvicorn pillow numpy rembg opencv-python
+sudo apt install libwebp-dev
+pip install pillow fastapi uvicorn
+npm install -g prettier
+npm install prettier --save-dev
+npm install prettier prettier-plugin-standalone --save
+sudo apt update
+sudo apt install -y \
+ ffmpeg \
+ ghostscript \
+ imagemagick \
+ graphicsmagick \
+ mupdf \
+ poppler-utils \
+ pandoc \
+ p7zip-full \
+ unzip \
+ unrar \
+ libimage-exiftool-perl
+sudo apt install -y gdal-bin libgdal-dev
+sudo apt install -y freecad
+sudo apt install -y libreoffice
+pip install python-multipart
+pip install pypdf2
+pip install python-docx
+pip install openpyxl
+pip install fastapi
+pip install uvicorn
+pip install pillow
+pip install pymupdf
+pip install pydub
+pip install ffmpeg-python
+pip install pandas pyarrow fastparquet
+pip install python-magic
+pip install aiofiles
+pip install --upgrade imageio imageio-ffmpeg
+pip install "setuptools<81"
+sudo apt install potrace
+sudo apt update
+sudo apt install ffmpeg -y
+pip install pydub
+pip install librosa soundfile matplotlib
+pip install openai-whisper
+# upgrade packaging tools first (recommended)
+python -m pip install --upgrade pip setuptools wheel
+
+# install numpy (required by whisper)
+python -m pip install numpy
+
+# (optional but often required) install/update whisper and its deps
+python -m pip install -U openai-whisper
+
+# If you plan to use PyTorch-backed whisper (recommended for performance),
+# install torch. For CPU-only builds use the CPU index:
+python -m pip install --index-url https://download.pytorch.org/whl/cpu torch
+
+# OR if you have CUDA and want GPU support, install the correct torch wheel from PyTorch site:
+# See https://pytorch.org/get-started/locally/ for the right command for your CUDA version.
+pip uninstall -y numpy
+pip install "numpy<2"
+pip install torch --index-url https://download.pytorch.org/whl/cpu
+pip install -U openai-whisper
+pip install "numpy<2"
+pip uninstall -y opencv-python opencv-python-headless
+pip install "opencv-python==4.7.0.72"
+pip install "opencv-python-headless==4.7.0.72"
+pip install --force-reinstall torch --index-url https://download.pytorch.org/whl/cpu
+pip install --force-reinstall openai-whisper
+pip install whisper
+pip install whisper
+pip freeze
+pip install torch==2.2.2 --index-url https://download.pytorch.org/whl/cpu
+pip install fastapi
+pip install uvicorn[standard]
+pip install python-multipart
+pip install pydantic
+pip install aiofiles
+pip install python-dotenv
+pip install psycopg2-binary
+pip install PyJWT
+pip install pillow
+pip install requests
+sudo apt install -y ffmpeg
+pip uninstall -y opencv-python opencv-python-headless moviepy numpy
+pip install numpy==1.26.4
+pip install opencv-python==4.7.0.72 opencv-python-headless==4.7.0.72
+pip install moviepy==1.0.3
+pip install --upgrade pip
+pip install fastapi uvicorn
+pip install numpy==1.26.4
+pip install opencv-python==4.7.0.72
+pip install opencv-python-headless==4.7.0.72
+pip install moviepy==1.0.3
+pip install whisper
+pip install torch==2.2.2 --index-url https://download.pytorch.org/whl/cpu
+python -c "import fastapi; print('FASTAPI OK')"
+python -c "import cv2; print('CV2 OK')"
+python -c "import moviepy; print('MOVIEPY OK')"
+python -c "import whisper; print('WHISPER OK')"
+python -c "import torch; print('TORCH OK')"
+pip install faster-whisper
+pip install PyPDF2==3.0.1
+pip install PyPDF2
+pip install python-docx
+pip install python-docx==0.8.11
+sudo apt-get install ghostscript
+pip install pikepdf
+sudo apt update
+sudo apt install handbrake-cli -y
+pip install fastapi uvicorn[standard] python-multipart ffmpeg-python
+pip install Flask flask-cors ffmpeg-normalize gunicorn
+pip install "fastapi[all]" python-multipart pydub numpy pyloudnorm
+sudo apt update
+sudo apt install -y qpdf ghostscript
+sudo apt install tesseract-ocr -y
+pip install pytesseract pymupdf pillow
+pip install markdown bleach
+pip install pillow pillow-heif pillow-avif-plugin cairosvg
+sudo apt install fonts-dejavu fonts-liberation ttf-mscorefonts-installer
+sudo apt install fonts-freefont-ttf fonts-lato
+pip install playwright
+playwright install chromium
+sudo apt install tesseract-ocr poppler-utils calibre
+pip install pytesseract pdf2image pillow
+sudo apt update
+sudo apt install gdal-bin
+sudo apt install poppler-utils
+sudo apt install openbabel
+sudo apt install ffmpeg
+pip install openai-whisper
+sudo apt install djvulibre-bin
+sudo apt install mupdf-tools
+sudo apt install graphicsmagick
+sudo apt update
+sudo apt install imagemagick
+sudo apt install potrace imagemagick
+cd ~/backend_copy
+source venv/bin/activate
+pip install pypdf
+sudo apt install tesseract-ocr
+sudo apt install tesseract-ocr-eng
+pip install pytesseract
+pip uninstall -y moviepy
+pip install "moviepy==1.0.3"
+pip install bleach
+pip install PyJWT
+pip install celery
+pip install redis
+
diff --git a/install1.sh b/install1.sh
new file mode 100644
index 0000000000000000000000000000000000000000..95daa5c99734d3da4d2f6b65ab57f56150781e38
--- /dev/null
+++ b/install1.sh
@@ -0,0 +1,323 @@
+sudo apt update
+sudo apt install fonts-dejavu-core
+pip uninstall pymupdf -y
+pip install --upgrade pymupdf
+pip uninstall pymupdf -y
+pip install --upgrade pymupdf
+sudo apt install qpdf
+sudo apt install qpdf
+
+pip install fastapi-admin bcrypt python-jose
+sudo apt update
+sudo apt install ffmpeg -y
+sudo apt install ghostscript -y
+sudo apt install imagemagick -y
+pip install pydantic-settings
+pip install fastapi uvicorn sqlalchemy psycopg2-binary pydantic python-dotenv fastapi-admin bcrypt python-jose
+pip install sqlalchemy psycopg2-binary
+pip install fastapi uvicorn python-dotenv
+pip install pillow pikepdf wand python-magic ffmpeg-python pydub
+pip install chardet unidecode
+sudo apt install p7zip-full p7zip-rar -y
+sudo apt install pandoc -y
+chmod +x cleanup.py
+# system
+sudo apt update
+sudo apt install imagemagick -y # ensures 'magick' or 'convert' binary exists
+# python libs
+pip install pillow piexif pdf2image
+# (pdf2image used earlier; kept if needed)
+# system
+sudo apt update
+sudo apt install ffmpeg sox -y
+
+# python (inside your venv)
+pip install ffmpeg-python pydub numpy soundfile librosa matplotlib aubio faster-whisper demucs TTS
+# extras (optional, help)
+pip install scipy matplotlib python-soundfile
+sudo apt update
+sudo apt install ffmpeg sox ghostscript imagemagick tesseract-ocr poppler-utils -y
+pip install torch --index-url https://download.pytorch.org/whl/cu121
+pip install torch --index-url https://download.pytorch.org/whl/cpu
+sudo apt update
+sudo apt install -y ghostscript poppler-utils imagemagick tesseract-ocr
+pip install pikepdf pymupdf ocrmypdf pdf2image reportlab pillow python-magic
+sudo apt update
+sudo apt install -y ffmpeg libopencv-dev ffmpeg libavcodec-extra
+# For stabilization (optional): libvidstab
+# On Ubuntu you might need to build ffmpeg with libvidstab or use a custom build/distribution.
+
+# Python packages (inside your venv)
+pip install ffmpeg-python moviepy opencv-python numpy scikit-image
+sudo mkdir -p /opt/realesrgan-models
+cd /opt/realesrgan-models
+# Example model files (replace URLs with actual ones)
+wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.3.0/realesrgan-x4plus.param
+wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.3.0/realesrgan-x4plus.bin
+# Or use an anime/video-specific model if available: realesr-animevideov3-x2.param/.bin etc.
+pip install Pillow pymupdf markdown python-magic
+# System (already likely installed): poppler-utils (for pdf2image if used), but pdf->text uses PyMuPDF
+pip install qrcode[pil] python-barcode reportlab pillow
+pip install pygments sqlparse xmltodict requests
+python3.10 -m venv ttsenv
+source ttsenv/bin/activate
+#pip install TTS
+pip install pyttsx3
+sudo apt update
+sudo apt install python3.10 python3.10-venv python3.10-dev
+python3.10 -m venv venv
+source venv/bin/activate
+python --version
+pip install pydantic-settings
+pip install pikepdf==5.0.1
+sudo apt update
+sudo apt install -y libqpdf-dev
+pip install pikepdf==5.0.1
+pip install PyMuPDF pikepdf
+pip install "PyMuPDF==1.23.4" "pikepdf==5.0.1"
+sudo apt update
+sudo apt install -y libqpdf-dev
+pip install pikepdf
+pip install reportlab
+sudo apt install libfreetype6-dev libjpeg-dev
+pip install reportlab
+pip install pdf2image pillow pikepdf pymupdf reportlab ffmpeg-python moviepy numpy scipy librosa soundfile python-multipart
+sudo apt install poppler-utils
+sudo apt install ffmpeg poppler-utils -y
+pip install onnxruntime pillow numpy
+pip install gdown
+pip install realesrgan
+pip install basicsr
+pip install realesrgan[full]
+pip install realesrgan basicsr torch torchvision
+pip install torch==2.2.2 torchvision==0.17.2 --index-url https://download.pytorch.org/whl/cpu
+pip install realesrgan basicsr
+pip uninstall -y torch torchvision
+pip install torch==2.2.2 torchvision==0.17.2 --index-url https://download.pytorch.org/whl/cpu
+pip install realesrgan basicsr
+pip install torch==1.13.1 torchvision==0.14.1
+pip install realesrgan basicsr
+sudo apt install python3.10 python3.10-venv
+python3.10 -m venv venv310
+source venv310/bin/activate
+pip install torch==1.13.1+cpu torchvision==0.14.1+cpu --index-url https://download.pytorch.org/whl/cpu
+pip install realesrgan basicsr
+sudo apt install libvulkan1 vulkan-tools
+
+pip install \
+pdf2image pillow pikepdf pymupdf reportlab \
+ffmpeg-python moviepy numpy scipy librosa soundfile \
+opencv-python pandas python-magic filetype \
+python-multipart
+sudo apt update
+sudo apt install -y ocrmypdf tesseract-ocr tesseract-ocr-eng ghostscript qpdf
+pip install ocrmypdf[all]
+pip install ocrmypdf --no-binary :all:
+pip install pillow opencv-python piexif numpy
+pip install piexif
+sudo apt install ffmpeg -y
+pip install pydub
+pip install moviepy
+pip install --upgrade --force-reinstall moviepy
+sudo apt install ffmpeg -y
+pip install imageio imageio-ffmpeg
+pip install moviepy imageio imageio-ffmpeg numpy
+sudo apt install ffmpeg -y
+pip uninstall moviepy -y
+pip uninstall imageio imageio-ffmpeg -y
+pip install moviepy==1.0.3 imageio==2.31.1 imageio-ffmpeg==0.4.9 numpy
+pip cache purge
+sudo apt install ffmpeg -y
+rm -rf venv/lib/python3.9/site-packages/moviepy
+rm -rf venv/lib/python3.9/site-packages/moviepy-*
+pip install moviepy==1.0.3
+pip install markdown
+pip install qrcode[pil]
+pip install pillow
+pip install python-barcode
+pip install sqlparse
+pip install xmltodict
+pip install psycopg2-binary
+python -c "import fastapi, pydantic; print(fastapi.__version__, pydantic.__version__)"
+pip install --upgrade fastapi starlette
+pip install PyJWT
+pip install PyJWT[crypto]
+# If you haven't already installed the PostgreSQL driver
+pip install psycopg2-binary
+pip install itsdangerous
+pip install starlette-admini
+pip install pydantic-settings python-dotenv
+pip install fastapi-admin tortoise-orm aiofiles python-multipart jinja2
+pip install fastapi-admin tortoise-orm aiofiles python-multipart jinja2
+sudo apt install redis
+sudo service redis start
+pip uninstall starlette-admin
+# then remove imports and admin-specific files you added earlier (core/admin.py earlier version)
+pip install sqladmin sqlalchemy psycopg2-binary python-multipart
+pip install sqladmin psycopg2-binary
+pip install sqladmin psycopg2-binary sqlalchemy
+pip install PyPDF2
+pip install pytesseract
+sudo apt install tesseract-ocr
+python -m pip install fastapi uvicorn sqlalchemy alembic python-multipart itsdangerous email-validator jinja2 passlib[bcrypt] requests pydantic cryptography reportlab
+python -m pip install pydantic-settings
+python -m pip install psycopg2-binary
+pip uninstall onnxruntime torch realesrgan basicsr -y
+pip install super-image
+pip install pillow-heif
+pip install pillow pillow-heif cairosvg
+pip install cairosvg
+pip install pillow-heif
+pip install pillow
+npm install @mediapipe/tasks-vision
+npm install @tensorflow/tfjs @tensorflow-models/body-pix
+npm install @tensorflow/tfjs @tensorflow-models/body-pix
+pip install -r requirements.txt
+# or
+pip install Pillow reportlab
+pip install rawpy==0.25.1
+pip install opencv-python
+pip install opencv-python-headless
+pip install fastapi uvicorn pillow numpy opencv-python rembg
+pip install onnxruntime-gpu
+pip install onnxruntime
+pip install fastapi uvicorn pillow numpy rembg opencv-python
+sudo apt install libwebp-dev
+pip install pillow fastapi uvicorn
+npm install -g prettier
+npm install prettier --save-dev
+npm install prettier prettier-plugin-standalone --save
+sudo apt update
+sudo apt install -y \
+ ffmpeg \
+ ghostscript \
+ imagemagick \
+ graphicsmagick \
+ mupdf \
+ poppler-utils \
+ pandoc \
+ p7zip-full \
+ unzip \
+ unrar \
+ libimage-exiftool-perl
+sudo apt install -y gdal-bin libgdal-dev
+sudo apt install -y freecad
+sudo apt install -y libreoffice
+pip install python-multipart
+pip install pypdf2
+pip install python-docx
+pip install openpyxl
+pip install fastapi
+pip install uvicorn
+pip install pillow
+pip install pymupdf
+pip install pydub
+pip install ffmpeg-python
+pip install pandas pyarrow fastparquet
+pip install python-magic
+pip install aiofiles
+pip install --upgrade imageio imageio-ffmpeg
+pip install "setuptools<81"
+sudo apt install potrace
+sudo apt update
+sudo apt install ffmpeg -y
+pip install pydub
+pip install librosa soundfile matplotlib
+pip install openai-whisper
+# upgrade packaging tools first (recommended)
+python -m pip install --upgrade pip setuptools wheel
+
+# install numpy (required by whisper)
+python -m pip install numpy
+
+# (optional but often required) install/update whisper and its deps
+python -m pip install -U openai-whisper
+
+# If you plan to use PyTorch-backed whisper (recommended for performance),
+# install torch. For CPU-only builds use the CPU index:
+python -m pip install --index-url https://download.pytorch.org/whl/cpu torch
+
+# OR if you have CUDA and want GPU support, install the correct torch wheel from PyTorch site:
+# See https://pytorch.org/get-started/locally/ for the right command for your CUDA version.
+pip uninstall -y numpy
+pip install "numpy<2"
+pip install torch --index-url https://download.pytorch.org/whl/cpu
+pip install -U openai-whisper
+pip install "numpy<2"
+pip uninstall -y opencv-python opencv-python-headless
+pip install "opencv-python==4.7.0.72"
+pip install "opencv-python-headless==4.7.0.72"
+pip install --force-reinstall torch --index-url https://download.pytorch.org/whl/cpu
+pip install --force-reinstall openai-whisper
+pip install whisper
+pip install whisper
+pip freeze
+pip install torch==2.2.2 --index-url https://download.pytorch.org/whl/cpu
+pip install fastapi
+pip install uvicorn[standard]
+pip install python-multipart
+pip install pydantic
+pip install aiofiles
+pip install python-dotenv
+pip install psycopg2-binary
+pip install PyJWT
+pip install pillow
+pip install requests
+sudo apt install -y ffmpeg
+pip uninstall -y opencv-python opencv-python-headless moviepy numpy
+pip install numpy==1.26.4
+pip install opencv-python==4.7.0.72 opencv-python-headless==4.7.0.72
+pip install moviepy==1.0.3
+pip install --upgrade pip
+pip install fastapi uvicorn
+pip install numpy==1.26.4
+pip install opencv-python==4.7.0.72
+pip install opencv-python-headless==4.7.0.72
+pip install moviepy==1.0.3
+pip install whisper
+pip install torch==2.2.2 --index-url https://download.pytorch.org/whl/cpu
+python -c "import fastapi; print('FASTAPI OK')"
+python -c "import cv2; print('CV2 OK')"
+python -c "import moviepy; print('MOVIEPY OK')"
+python -c "import whisper; print('WHISPER OK')"
+python -c "import torch; print('TORCH OK')"
+pip install faster-whisper
+pip install PyPDF2==3.0.1
+pip install PyPDF2
+pip install python-docx
+pip install python-docx==0.8.11
+sudo apt-get install ghostscript
+pip install pikepdf
+sudo apt update
+sudo apt install handbrake-cli -y
+pip install fastapi uvicorn[standard] python-multipart ffmpeg-python
+pip install Flask flask-cors ffmpeg-normalize gunicorn
+pip install "fastapi[all]" python-multipart pydub numpy pyloudnorm
+sudo apt update
+sudo apt install -y qpdf ghostscript
+sudo apt install tesseract-ocr -y
+pip install pytesseract pymupdf pillow
+pip install markdown bleach
+pip install pillow pillow-heif pillow-avif-plugin cairosvg
+sudo apt install fonts-dejavu fonts-liberation ttf-mscorefonts-installer
+sudo apt install fonts-freefont-ttf fonts-lato
+pip install playwright
+playwright install chromium
+sudo apt install tesseract-ocr poppler-utils calibre
+pip install pytesseract pdf2image pillow
+sudo apt update
+sudo apt install gdal-bin
+sudo apt install poppler-utils
+sudo apt install openbabel
+sudo apt install ffmpeg
+pip install openai-whisper
+sudo apt install djvulibre-bin
+sudo apt install mupdf-tools
+sudo apt install graphicsmagick
+sudo apt update
+sudo apt install imagemagick
+sudo apt install potrace imagemagick
+cd ~/backend_copy
+source venv/bin/activate
+pip install pypdf
+
diff --git a/lib.sh b/lib.sh
new file mode 100644
index 0000000000000000000000000000000000000000..beba1243ebfc6f7eb0c10dc68de33ffd13fe7760
--- /dev/null
+++ b/lib.sh
@@ -0,0 +1,15 @@
+sudo apt install libreoffice libreoffice-impress libreoffice-writer
+
+sudo apt update
+sudo apt install libreoffice-impress libreoffice-writer libreoffice-core
+pip install python-pptx beautifulsoup4 lxml
+sudo apt install texlive-xetex
+sudo apt install wkhtmltopdf
+sudo apt install calibre
+sudo apt update
+sudo apt install libreoffice-calc
+pip install pandas xlrd openpyxl
+pip install xlwt
+pip install "pandas<2.0"
+pip install xlrd==1.2.0 openpyxl
+
diff --git a/logs.sh b/logs.sh
new file mode 100755
index 0000000000000000000000000000000000000000..1e0ea46a61325118c6f42f5a23310335705788bc
--- /dev/null
+++ b/logs.sh
@@ -0,0 +1,3 @@
+sudo journalctl -u backend -f
+sudo journalctl -u celery -f
+
diff --git a/main.py b/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bdf6bcac9d12f37b1797060b191db602410cb9e
--- /dev/null
+++ b/main.py
@@ -0,0 +1,133 @@
+import os
+from fastapi import FastAPI
+from fastapi.middleware.cors import CORSMiddleware
+from starlette.middleware.sessions import SessionMiddleware
+from starlette.middleware.base import BaseHTTPMiddleware
+from fastapi.staticfiles import StaticFiles
+
+# 🚀 1. ENSURE DIRECTORIES EXIST (Prevents startup crash)
+os.makedirs("static/output", exist_ok=True)
+os.makedirs("uploads", exist_ok=True)
+os.makedirs("tmp", exist_ok=True)
+os.makedirs("temp", exist_ok=True)
+
+# 🚀 2. INITIALIZE RAM DATABASE TABLES (Prevents "no such table" error)
+from core.database import Base, engine
+Base.metadata.create_all(bind=engine)
+
+from core.admin import setup_admin
+from core.config import settings
+
+# Routers
+from routers.ratings import router as ratings_router
+from routers import ratings
+from routers import network_tools
+from routers import (
+ pdf,
+ image,
+ audio,
+ video,
+ utility,
+ business,
+ developer,
+ converter_tools,
+ admin_auth,
+ stats,
+ ads,
+ tool_tracking,
+ image_tools,
+ devtools,
+)
+from routers.pdf_watermark import router as watermark_router
+from routers.universal_converter_full import router as universal_converter_router
+
+# -------------------------------------------------------
+# 🚀 APP INIT
+# -------------------------------------------------------
+app = FastAPI(title="Tools Backend API", version="1.0.0")
+
+class LargeUploadMiddleware(BaseHTTPMiddleware):
+ async def dispatch(self, request, call_next):
+ request.scope["client_max_size"] = 5 * 1024 * 1024 * 1024
+ return await call_next(request)
+
+app.add_middleware(LargeUploadMiddleware)
+
+# -------------------------------------------------------
+# 🌍 CORS (Includes Hugging Face & Production)
+# -------------------------------------------------------
+LOCAL_ORIGINS = [
+ "http://localhost:3000",
+ "http://127.0.0.1:3000",
+ "http://localhost:7860",
+]
+
+PRODUCTION_ORIGINS = [
+ "https://cloudaipdf.com",
+ "https://www.cloudaipdf.com",
+ "https://api.cloudaipdf.com",
+ "https://upload.cloudaipdf.com",
+]
+
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=LOCAL_ORIGINS + PRODUCTION_ORIGINS,
+ allow_origin_regex=r"https://.*\.hf\.space", # ✅ Allows Hugging Face Space URLs
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+# -------------------------------------------------------
+# 🍪 SESSIONS
+# -------------------------------------------------------
+app.add_middleware(
+ SessionMiddleware,
+ secret_key=getattr(settings, "SECRET_KEY", "default-fallback-secret-key-32chars"),
+ same_site="none",
+ https_only=True,
+)
+
+# -------------------------------------------------------
+# 📁 STATIC FILES
+# -------------------------------------------------------
+app.mount("/static", StaticFiles(directory="static"), name="static")
+app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
+
+# -------------------------------------------------------
+# 🛡️ ADMIN (LOAD FIRST)
+# -------------------------------------------------------
+setup_admin(app)
+
+# -------------------------------------------------------
+# 🔌 ROUTERS
+# -------------------------------------------------------
+app.include_router(pdf.router, prefix="/pdf")
+app.include_router(image.router, prefix="/image")
+app.include_router(image_tools.router, prefix="/image-tools")
+app.include_router(image_tools.router, prefix="/converters")
+app.include_router(audio.router, prefix="/audio")
+app.include_router(video.router, prefix="/video")
+app.include_router(utility.router, prefix="/utility")
+app.include_router(business.router, prefix="/business")
+app.include_router(developer.router, prefix="/developer")
+app.include_router(converter_tools.router, prefix="/tools")
+app.include_router(universal_converter_router, prefix="/convert")
+app.include_router(network_tools.router, prefix="/network")
+app.include_router(ads.router)
+app.include_router(devtools.router)
+app.include_router(stats.router)
+app.include_router(tool_tracking.router)
+app.include_router(ratings_router)
+app.include_router(admin_auth.router, prefix="/admin-auth")
+
+# -------------------------------------------------------
+# 🏠 HEALTH CHECK
+# -------------------------------------------------------
+@app.get("/")
+def home():
+ return {"message": "Tools Backend Running Successfully!"}
+
+@app.get("/health", include_in_schema=False)
+def health():
+ return {"status": "ok"}
diff --git a/models/__pycache__/stats_model.cpython-312.pyc b/models/__pycache__/stats_model.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ef2e51cf39cd044fb61f68a033113e8f4b2ab5d
Binary files /dev/null and b/models/__pycache__/stats_model.cpython-312.pyc differ
diff --git a/models/__pycache__/stats_model.cpython-39.pyc b/models/__pycache__/stats_model.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb384038d14e3c19ea08eebc8a0e0d3b0dd63060
Binary files /dev/null and b/models/__pycache__/stats_model.cpython-39.pyc differ
diff --git a/models/admin_user.py b/models/admin_user.py
new file mode 100644
index 0000000000000000000000000000000000000000..adacc9b9e2f08d5220efd4d5d415b40d94b17aab
--- /dev/null
+++ b/models/admin_user.py
@@ -0,0 +1,13 @@
+# models/admin_user.py
+from sqlalchemy import Column, Integer, String, DateTime, func
+from core.database import Base
+
+class AdminUser(Base):
+ __tablename__ = "admin_users"
+
+ id = Column(Integer, primary_key=True, index=True)
+ username = Column(String(150), nullable=False, unique=True, index=True)
+ password_hash = Column(String(300), nullable=False)
+ full_name = Column(String(200), nullable=True)
+ created_at = Column(DateTime(timezone=True), server_default=func.now())
+
diff --git a/models/models.py b/models/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcae20b3500e6bdb4549d47a270c8d05ccff6443
--- /dev/null
+++ b/models/models.py
@@ -0,0 +1,23 @@
+# models/models.py
+
+from tortoise import fields
+from tortoise.models import Model
+
+class AdminUser(Model):
+ id = fields.IntField(pk=True)
+ username = fields.CharField(max_length=100, unique=True)
+ password = fields.CharField(max_length=200) # hashed later
+
+ class Meta:
+ table = "admin_users"
+
+
+class UsageStat(Model):
+ id = fields.IntField(pk=True)
+ tool_name = fields.CharField(max_length=200)
+ usage_count = fields.IntField(default=0)
+ last_used_at = fields.DatetimeField(auto_now=True)
+
+ class Meta:
+ table = "usage_stats"
+
diff --git a/models/rating.py b/models/rating.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1a60546e4813ac783827398518db749203be79b
--- /dev/null
+++ b/models/rating.py
@@ -0,0 +1,12 @@
+from sqlalchemy import Column, Integer, String, DateTime
+from sqlalchemy.sql import func
+from core.database import Base
+
+class Rating(Base):
+ __tablename__ = "tool_ratings"
+
+ id = Column(Integer, primary_key=True, index=True)
+ tool = Column(String(100), index=True, nullable=False)
+ rating = Column(Integer, nullable=False)
+ created_at = Column(DateTime(timezone=True), server_default=func.now())
+
diff --git a/models/stats_model.py b/models/stats_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..29b7e0ba3cf3228419e1786ff111426dc356467e
--- /dev/null
+++ b/models/stats_model.py
@@ -0,0 +1,12 @@
+from sqlalchemy import Column, Integer, String, DateTime
+from core.database import Base
+from datetime import datetime
+
+class UsageStat(Base):
+ __tablename__ = "usage_stats"
+
+ id = Column(Integer, primary_key=True, index=True, autoincrement=True)
+ tool_name = Column(String, nullable=False)
+ usage_count = Column(Integer, default=0)
+ last_used_at = Column(DateTime, default=datetime.utcnow)
+
diff --git a/netw.sh b/netw.sh
new file mode 100644
index 0000000000000000000000000000000000000000..dea19b24cf74154d6187e3911a2ea6ea6e40b5b2
--- /dev/null
+++ b/netw.sh
@@ -0,0 +1,27 @@
+pip install openpyxl
+pip install openpyxl pandas
+pip install beautifulsoup4 lxml
+pip install pyyaml
+sudo apt update
+sudo apt install texlive-latex-base texlive-latex-recommended texlive-fonts-recommended -y
+sudo apt install texlive-full -y
+sudo apt install unoconv
+pip install pdfplumber pandas
+pip install pdfminer.six
+pip install python-pptx
+sudo apt install unrar-free
+pip install rawpy pillow
+sudo apt update
+sudo apt install libraw-dev dcraw imagemagick
+sudo apt update
+sudo apt install p7zip-full
+sudo apt install inkscape
+pip install reportlab
+pip install ebooklib
+pip install html5lib
+sudo apt update
+sudo apt install libreoffice-impress
+pip install dnspython
+pip install mac-vendor-lookup
+
+
diff --git a/onn.txt b/onn.txt
new file mode 100644
index 0000000000000000000000000000000000000000..d6df6a80cc7791e83d17de14b2834e6a158fc93d
--- /dev/null
+++ b/onn.txt
@@ -0,0 +1,14 @@
+python3 - << 'EOF'
+import requests
+
+def gdown(url, output):
+ print(f"Downloading {output} ...")
+ r = requests.get(url)
+ open(output, "wb").write(r.content)
+
+gdown("https://drive.usercontent.google.com/download?id=1rZ8sW7oGSc6jw5jTNZf5a1QO5pRWYxkk&export=download", "RealESRGAN_x4plus.onnx")
+gdown("https://drive.usercontent.google.com/download?id=1J9J4IsuZ564CxJ7oRKPvE2dMMmvBNxLt&export=download", "RealESRGAN_x4plus_anime_6B.onnx")
+
+print("Done!")
+EOF
+
diff --git a/output.pdf b/output.pdf
new file mode 100644
index 0000000000000000000000000000000000000000..a45ee9bd1e9ee91fcb6021d0052d5da0ce3ff36a
--- /dev/null
+++ b/output.pdf
@@ -0,0 +1 @@
+Internal Server Error
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000000000000000000000000000000000000..747b14d866b5a45427e34ca10702d19189a3dfce
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,1956 @@
+{
+ "name": "backend_copy",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "dependencies": {
+ "@mediapipe/tasks-vision": "^0.10.22-rc.20250304",
+ "express": "^5.2.1",
+ "fs-extra": "^11.3.2",
+ "multer": "^2.0.2",
+ "pdf-lib": "^1.17.1",
+ "sharp": "^0.34.5",
+ "uuid": "^13.0.0"
+ },
+ "devDependencies": {
+ "autoprefixer": "^10.4.22",
+ "postcss": "^8.5.6",
+ "prettier": "^3.7.3",
+ "tailwindcss": "^4.1.17"
+ }
+ },
+ "node_modules/@emnapi/runtime": {
+ "version": "1.7.1",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.7.1.tgz",
+ "integrity": "sha512-PVtJr5CmLwYAU9PZDMITZoR5iAOShYREoR45EyyLrbntV50mdePTgUn4AmOw90Ifcj+x2kRjdzr1HP3RrNiHGA==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@img/colour": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.0.0.tgz",
+ "integrity": "sha512-A5P/LfWGFSl6nsckYtjw9da+19jB8hkJ6ACTGcDfEJ0aE+l2n2El7dsVM7UVHZQ9s2lmYMWlrS21YLy2IR1LUw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@img/sharp-darwin-arm64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz",
+ "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-arm64": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-darwin-x64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz",
+ "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-x64": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-arm64": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz",
+ "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-x64": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz",
+ "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz",
+ "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm64": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz",
+ "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-ppc64": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz",
+ "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-riscv64": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz",
+ "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-s390x": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz",
+ "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-x64": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz",
+ "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz",
+ "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz",
+ "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz",
+ "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz",
+ "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm64": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-ppc64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz",
+ "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-ppc64": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-riscv64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz",
+ "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==",
+ "cpu": [
+ "riscv64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-riscv64": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-s390x": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz",
+ "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==",
+ "cpu": [
+ "s390x"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-s390x": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-x64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz",
+ "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-x64": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-arm64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz",
+ "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-x64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz",
+ "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-x64": "1.2.4"
+ }
+ },
+ "node_modules/@img/sharp-wasm32": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz",
+ "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==",
+ "cpu": [
+ "wasm32"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/runtime": "^1.7.0"
+ },
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-arm64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz",
+ "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-ia32": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz",
+ "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==",
+ "cpu": [
+ "ia32"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-x64": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz",
+ "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@mediapipe/tasks-vision": {
+ "version": "0.10.22-rc.20250304",
+ "resolved": "https://registry.npmjs.org/@mediapipe/tasks-vision/-/tasks-vision-0.10.22-rc.20250304.tgz",
+ "integrity": "sha512-dElxVXMFGthshfIj+qAVm8KE2jmNo2p8oXFib8WzEjb7GNaX/ClWBc8UJfoSZwjEMVrdHJ4YUfa7P3ifl6MIWw==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/@pdf-lib/standard-fonts": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/@pdf-lib/standard-fonts/-/standard-fonts-1.0.0.tgz",
+ "integrity": "sha512-hU30BK9IUN/su0Mn9VdlVKsWBS6GyhVfqjwl1FjZN4TxP6cCw0jP2w7V3Hf5uX7M0AZJ16vey9yE0ny7Sa59ZA==",
+ "license": "MIT",
+ "dependencies": {
+ "pako": "^1.0.6"
+ }
+ },
+ "node_modules/@pdf-lib/upng": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@pdf-lib/upng/-/upng-1.0.1.tgz",
+ "integrity": "sha512-dQK2FUMQtowVP00mtIksrlZhdFXQZPC+taih1q4CvPZ5vqdxR/LKBaFg0oAfzd1GlHZXXSPdQfzQnt+ViGvEIQ==",
+ "license": "MIT",
+ "dependencies": {
+ "pako": "^1.0.10"
+ }
+ },
+ "node_modules/accepts": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-types": "^3.0.0",
+ "negotiator": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/append-field": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
+ "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
+ "license": "MIT"
+ },
+ "node_modules/autoprefixer": {
+ "version": "10.4.22",
+ "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.22.tgz",
+ "integrity": "sha512-ARe0v/t9gO28Bznv6GgqARmVqcWOV3mfgUPn9becPHMiD3o9BwlRgaeccZnwTpZ7Zwqrm+c1sUSsMxIzQzc8Xg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/autoprefixer"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "browserslist": "^4.27.0",
+ "caniuse-lite": "^1.0.30001754",
+ "fraction.js": "^5.3.4",
+ "normalize-range": "^0.1.2",
+ "picocolors": "^1.1.1",
+ "postcss-value-parser": "^4.2.0"
+ },
+ "bin": {
+ "autoprefixer": "bin/autoprefixer"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ },
+ "peerDependencies": {
+ "postcss": "^8.1.0"
+ }
+ },
+ "node_modules/baseline-browser-mapping": {
+ "version": "2.9.2",
+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.2.tgz",
+ "integrity": "sha512-PxSsosKQjI38iXkmb3d0Y32efqyA0uW4s41u4IVBsLlWLhCiYNpH/AfNOVWRqCQBlD8TFJTz6OUWNd4DFJCnmw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "baseline-browser-mapping": "dist/cli.js"
+ }
+ },
+ "node_modules/body-parser": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.1.tgz",
+ "integrity": "sha512-nfDwkulwiZYQIGwxdy0RUmowMhKcFVcYXUU7m4QlKYim1rUtg83xm2yjZ40QjDuc291AJjjeSc9b++AWHSgSHw==",
+ "license": "MIT",
+ "dependencies": {
+ "bytes": "^3.1.2",
+ "content-type": "^1.0.5",
+ "debug": "^4.4.3",
+ "http-errors": "^2.0.0",
+ "iconv-lite": "^0.7.0",
+ "on-finished": "^2.4.1",
+ "qs": "^6.14.0",
+ "raw-body": "^3.0.1",
+ "type-is": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/browserslist": {
+ "version": "4.28.1",
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz",
+ "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "baseline-browser-mapping": "^2.9.0",
+ "caniuse-lite": "^1.0.30001759",
+ "electron-to-chromium": "^1.5.263",
+ "node-releases": "^2.0.27",
+ "update-browserslist-db": "^1.2.0"
+ },
+ "bin": {
+ "browserslist": "cli.js"
+ },
+ "engines": {
+ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
+ }
+ },
+ "node_modules/buffer-from": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
+ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
+ "license": "MIT"
+ },
+ "node_modules/busboy": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
+ "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
+ "dependencies": {
+ "streamsearch": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=10.16.0"
+ }
+ },
+ "node_modules/bytes": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/call-bind-apply-helpers": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/call-bound": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "get-intrinsic": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/caniuse-lite": {
+ "version": "1.0.30001759",
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001759.tgz",
+ "integrity": "sha512-Pzfx9fOKoKvevQf8oCXoyNRQ5QyxJj+3O0Rqx2V5oxT61KGx8+n6hV/IUyJeifUci2clnmmKVpvtiqRzgiWjSw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "CC-BY-4.0"
+ },
+ "node_modules/concat-stream": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
+ "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
+ "engines": [
+ "node >= 6.0"
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "buffer-from": "^1.0.0",
+ "inherits": "^2.0.3",
+ "readable-stream": "^3.0.2",
+ "typedarray": "^0.0.6"
+ }
+ },
+ "node_modules/content-disposition": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz",
+ "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/content-type": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/cookie": {
+ "version": "0.7.2",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/cookie-signature": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.6.0"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/depd": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/dunder-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "gopd": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/ee-first": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
+ "license": "MIT"
+ },
+ "node_modules/electron-to-chromium": {
+ "version": "1.5.265",
+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.265.tgz",
+ "integrity": "sha512-B7IkLR1/AE+9jR2LtVF/1/6PFhY5TlnEHnlrKmGk7PvkJibg5jr+mLXLLzq3QYl6PA1T/vLDthQPqIPAlS/PPA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/encodeurl": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/es-define-property": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-errors": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-object-atoms": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/escalade": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/escape-html": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
+ "license": "MIT"
+ },
+ "node_modules/etag": {
+ "version": "1.8.1",
+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/express": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
+ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
+ "license": "MIT",
+ "dependencies": {
+ "accepts": "^2.0.0",
+ "body-parser": "^2.2.1",
+ "content-disposition": "^1.0.0",
+ "content-type": "^1.0.5",
+ "cookie": "^0.7.1",
+ "cookie-signature": "^1.2.1",
+ "debug": "^4.4.0",
+ "depd": "^2.0.0",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "etag": "^1.8.1",
+ "finalhandler": "^2.1.0",
+ "fresh": "^2.0.0",
+ "http-errors": "^2.0.0",
+ "merge-descriptors": "^2.0.0",
+ "mime-types": "^3.0.0",
+ "on-finished": "^2.4.1",
+ "once": "^1.4.0",
+ "parseurl": "^1.3.3",
+ "proxy-addr": "^2.0.7",
+ "qs": "^6.14.0",
+ "range-parser": "^1.2.1",
+ "router": "^2.2.0",
+ "send": "^1.1.0",
+ "serve-static": "^2.2.0",
+ "statuses": "^2.0.1",
+ "type-is": "^2.0.1",
+ "vary": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/finalhandler": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",
+ "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.0",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "on-finished": "^2.4.1",
+ "parseurl": "^1.3.3",
+ "statuses": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 18.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/forwarded": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/fraction.js": {
+ "version": "5.3.4",
+ "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz",
+ "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "*"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/rawify"
+ }
+ },
+ "node_modules/fresh": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",
+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/fs-extra": {
+ "version": "11.3.2",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.2.tgz",
+ "integrity": "sha512-Xr9F6z6up6Ws+NjzMCZc6WXg2YFRlrLP9NQDO3VQrWrfiojdhS56TzueT88ze0uBdCTwEIhQ3ptnmKeWGFAe0A==",
+ "license": "MIT",
+ "dependencies": {
+ "graceful-fs": "^4.2.0",
+ "jsonfile": "^6.0.1",
+ "universalify": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=14.14"
+ }
+ },
+ "node_modules/function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-intrinsic": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
+ "function-bind": "^1.1.2",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "hasown": "^2.0.2",
+ "math-intrinsics": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/gopd": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/graceful-fs": {
+ "version": "4.2.11",
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
+ "license": "ISC"
+ },
+ "node_modules/has-symbols": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/hasown": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/http-errors": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
+ "license": "MIT",
+ "dependencies": {
+ "depd": "~2.0.0",
+ "inherits": "~2.0.4",
+ "setprototypeof": "~1.2.0",
+ "statuses": "~2.0.2",
+ "toidentifier": "~1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/iconv-lite": {
+ "version": "0.7.0",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.0.tgz",
+ "integrity": "sha512-cf6L2Ds3h57VVmkZe+Pn+5APsT7FpqJtEhhieDCvrE2MK5Qk9MyffgQyuxQTm6BChfeZNtcOLHp9IcWRVcIcBQ==",
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/inherits": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+ "license": "ISC"
+ },
+ "node_modules/ipaddr.js": {
+ "version": "1.9.1",
+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/is-promise": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
+ "license": "MIT"
+ },
+ "node_modules/jsonfile": {
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz",
+ "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==",
+ "license": "MIT",
+ "dependencies": {
+ "universalify": "^2.0.0"
+ },
+ "optionalDependencies": {
+ "graceful-fs": "^4.1.6"
+ }
+ },
+ "node_modules/math-intrinsics": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/media-typer": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",
+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/merge-descriptors": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/mime-db": {
+ "version": "1.54.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",
+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "^1.54.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/minimist": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/mkdirp": {
+ "version": "0.5.6",
+ "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
+ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
+ "license": "MIT",
+ "dependencies": {
+ "minimist": "^1.2.6"
+ },
+ "bin": {
+ "mkdirp": "bin/cmd.js"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/multer": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/multer/-/multer-2.0.2.tgz",
+ "integrity": "sha512-u7f2xaZ/UG8oLXHvtF/oWTRvT44p9ecwBBqTwgJVq0+4BW1g8OW01TyMEGWBHbyMOYVHXslaut7qEQ1meATXgw==",
+ "license": "MIT",
+ "dependencies": {
+ "append-field": "^1.0.0",
+ "busboy": "^1.6.0",
+ "concat-stream": "^2.0.0",
+ "mkdirp": "^0.5.6",
+ "object-assign": "^4.1.1",
+ "type-is": "^1.6.18",
+ "xtend": "^4.0.2"
+ },
+ "engines": {
+ "node": ">= 10.16.0"
+ }
+ },
+ "node_modules/multer/node_modules/media-typer": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
+ "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/multer/node_modules/mime-db": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/multer/node_modules/mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "1.52.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/multer/node_modules/type-is": {
+ "version": "1.6.18",
+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
+ "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
+ "license": "MIT",
+ "dependencies": {
+ "media-typer": "0.3.0",
+ "mime-types": "~2.1.24"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.11",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
+ "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/negotiator": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/node-releases": {
+ "version": "2.0.27",
+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz",
+ "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/normalize-range": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz",
+ "integrity": "sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/object-inspect": {
+ "version": "1.13.4",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/on-finished": {
+ "version": "2.4.1",
+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
+ "license": "MIT",
+ "dependencies": {
+ "ee-first": "1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/once": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+ "license": "ISC",
+ "dependencies": {
+ "wrappy": "1"
+ }
+ },
+ "node_modules/pako": {
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
+ "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
+ "license": "(MIT AND Zlib)"
+ },
+ "node_modules/parseurl": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/path-to-regexp": {
+ "version": "8.3.0",
+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz",
+ "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/pdf-lib": {
+ "version": "1.17.1",
+ "resolved": "https://registry.npmjs.org/pdf-lib/-/pdf-lib-1.17.1.tgz",
+ "integrity": "sha512-V/mpyJAoTsN4cnP31vc0wfNA1+p20evqqnap0KLoRUN0Yk/p3wN52DOEsL4oBFcLdb76hlpKPtzJIgo67j/XLw==",
+ "license": "MIT",
+ "dependencies": {
+ "@pdf-lib/standard-fonts": "^1.0.0",
+ "@pdf-lib/upng": "^1.0.1",
+ "pako": "^1.0.11",
+ "tslib": "^1.11.1"
+ }
+ },
+ "node_modules/pdf-lib/node_modules/tslib": {
+ "version": "1.14.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
+ "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
+ "license": "0BSD"
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/postcss": {
+ "version": "8.5.6",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",
+ "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "nanoid": "^3.3.11",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/postcss-value-parser": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
+ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/prettier": {
+ "version": "3.7.3",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.7.3.tgz",
+ "integrity": "sha512-QgODejq9K3OzoBbuyobZlUhznP5SKwPqp+6Q6xw6o8gnhr4O85L2U915iM2IDcfF2NPXVaM9zlo9tdwipnYwzg==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "prettier": "bin/prettier.cjs"
+ },
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/prettier/prettier?sponsor=1"
+ }
+ },
+ "node_modules/proxy-addr": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
+ "license": "MIT",
+ "dependencies": {
+ "forwarded": "0.2.0",
+ "ipaddr.js": "1.9.1"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/qs": {
+ "version": "6.14.0",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz",
+ "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "side-channel": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=0.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/range-parser": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/raw-body": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",
+ "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",
+ "license": "MIT",
+ "dependencies": {
+ "bytes": "~3.1.2",
+ "http-errors": "~2.0.1",
+ "iconv-lite": "~0.7.0",
+ "unpipe": "~1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/router": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.0",
+ "depd": "^2.0.0",
+ "is-promise": "^4.0.0",
+ "parseurl": "^1.3.3",
+ "path-to-regexp": "^8.0.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "license": "MIT"
+ },
+ "node_modules/semver": {
+ "version": "7.7.3",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",
+ "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/send": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz",
+ "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.3.5",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "etag": "^1.8.1",
+ "fresh": "^2.0.0",
+ "http-errors": "^2.0.0",
+ "mime-types": "^3.0.1",
+ "ms": "^2.1.3",
+ "on-finished": "^2.4.1",
+ "range-parser": "^1.2.1",
+ "statuses": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/serve-static": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz",
+ "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==",
+ "license": "MIT",
+ "dependencies": {
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "parseurl": "^1.3.3",
+ "send": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/setprototypeof": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
+ "license": "ISC"
+ },
+ "node_modules/sharp": {
+ "version": "0.34.5",
+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz",
+ "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==",
+ "hasInstallScript": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@img/colour": "^1.0.0",
+ "detect-libc": "^2.1.2",
+ "semver": "^7.7.3"
+ },
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-darwin-arm64": "0.34.5",
+ "@img/sharp-darwin-x64": "0.34.5",
+ "@img/sharp-libvips-darwin-arm64": "1.2.4",
+ "@img/sharp-libvips-darwin-x64": "1.2.4",
+ "@img/sharp-libvips-linux-arm": "1.2.4",
+ "@img/sharp-libvips-linux-arm64": "1.2.4",
+ "@img/sharp-libvips-linux-ppc64": "1.2.4",
+ "@img/sharp-libvips-linux-riscv64": "1.2.4",
+ "@img/sharp-libvips-linux-s390x": "1.2.4",
+ "@img/sharp-libvips-linux-x64": "1.2.4",
+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.4",
+ "@img/sharp-libvips-linuxmusl-x64": "1.2.4",
+ "@img/sharp-linux-arm": "0.34.5",
+ "@img/sharp-linux-arm64": "0.34.5",
+ "@img/sharp-linux-ppc64": "0.34.5",
+ "@img/sharp-linux-riscv64": "0.34.5",
+ "@img/sharp-linux-s390x": "0.34.5",
+ "@img/sharp-linux-x64": "0.34.5",
+ "@img/sharp-linuxmusl-arm64": "0.34.5",
+ "@img/sharp-linuxmusl-x64": "0.34.5",
+ "@img/sharp-wasm32": "0.34.5",
+ "@img/sharp-win32-arm64": "0.34.5",
+ "@img/sharp-win32-ia32": "0.34.5",
+ "@img/sharp-win32-x64": "0.34.5"
+ }
+ },
+ "node_modules/side-channel": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
+ "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.3",
+ "side-channel-list": "^1.0.0",
+ "side-channel-map": "^1.0.1",
+ "side-channel-weakmap": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-list": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
+ "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-map": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-weakmap": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3",
+ "side-channel-map": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/statuses": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/streamsearch": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
+ "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/string_decoder": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.2.0"
+ }
+ },
+ "node_modules/tailwindcss": {
+ "version": "4.1.17",
+ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.17.tgz",
+ "integrity": "sha512-j9Ee2YjuQqYT9bbRTfTZht9W/ytp5H+jJpZKiYdP/bpnXARAuELt9ofP0lPnmHjbga7SNQIxdTAXCmtKVYjN+Q==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/toidentifier": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.6"
+ }
+ },
+ "node_modules/tslib": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "license": "0BSD",
+ "optional": true
+ },
+ "node_modules/type-is": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz",
+ "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==",
+ "license": "MIT",
+ "dependencies": {
+ "content-type": "^1.0.5",
+ "media-typer": "^1.1.0",
+ "mime-types": "^3.0.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/typedarray": {
+ "version": "0.0.6",
+ "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
+ "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
+ "license": "MIT"
+ },
+ "node_modules/universalify": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
+ "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10.0.0"
+ }
+ },
+ "node_modules/unpipe": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/update-browserslist-db": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.2.tgz",
+ "integrity": "sha512-E85pfNzMQ9jpKkA7+TJAi4TJN+tBCuWh5rUcS/sv6cFi+1q9LYDwDI5dpUL0u/73EElyQ8d3TEaeW4sPedBqYA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "escalade": "^3.2.0",
+ "picocolors": "^1.1.1"
+ },
+ "bin": {
+ "update-browserslist-db": "cli.js"
+ },
+ "peerDependencies": {
+ "browserslist": ">= 4.21.0"
+ }
+ },
+ "node_modules/util-deprecate": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
+ "license": "MIT"
+ },
+ "node_modules/uuid": {
+ "version": "13.0.0",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-13.0.0.tgz",
+ "integrity": "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w==",
+ "funding": [
+ "https://github.com/sponsors/broofa",
+ "https://github.com/sponsors/ctavan"
+ ],
+ "license": "MIT",
+ "bin": {
+ "uuid": "dist-node/bin/uuid"
+ }
+ },
+ "node_modules/vary": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+ "license": "ISC"
+ },
+ "node_modules/xtend": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
+ "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..f1cca98225b0b8a73d44da2ab77dc6926748e4d1
--- /dev/null
+++ b/package.json
@@ -0,0 +1,17 @@
+{
+ "dependencies": {
+ "@mediapipe/tasks-vision": "^0.10.22-rc.20250304",
+ "express": "^5.2.1",
+ "fs-extra": "^11.3.2",
+ "multer": "^2.0.2",
+ "pdf-lib": "^1.17.1",
+ "sharp": "^0.34.5",
+ "uuid": "^13.0.0"
+ },
+ "devDependencies": {
+ "autoprefixer": "^10.4.22",
+ "postcss": "^8.5.6",
+ "prettier": "^3.7.3",
+ "tailwindcss": "^4.1.17"
+ }
+}
diff --git a/packages.txt b/packages.txt
new file mode 100644
index 0000000000000000000000000000000000000000..7a9148ba242bf74e16e2177dfea3ffd84c2c3599
--- /dev/null
+++ b/packages.txt
@@ -0,0 +1,8 @@
+ffmpeg
+libreoffice
+pandoc
+potrace
+imagemagick
+p7zip-full
+unzip
+libcairo2
diff --git a/requ.txt b/requ.txt
new file mode 100644
index 0000000000000000000000000000000000000000..6229131535d58f6d2855393318b7efe6a4f90286
--- /dev/null
+++ b/requ.txt
@@ -0,0 +1 @@
+pip install pdfplumber pymupdf pillow pillow-heif cairosvg rawpy imageio xlrd openpyxl pdfminer.six python-docx python-pptx ebooklib beautifulsoup4 markdown bleach pyyaml pandas lxml reportlab camelot-py opencv-python-headless
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..bdb9de33ebf415857ead08bfb0ce0595ac2ce552
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,72 @@
+# --- Core Framework & Server ---
+fastapi==0.115.0
+uvicorn[standard]==0.30.1
+starlette==0.37.2
+python-multipart==0.0.9
+requests==2.32.3
+python-dotenv==1.0.1
+pydantic
+pydantic-settings
+python-dateutil
+itsdangerous==2.1.2
+jinja2==3.1.4
+orjson==3.10.3
+
+# --- In-Memory Database / Admin ---
+SQLAlchemy==2.0.30
+alembic
+sqladmin==0.15.2
+
+# --- Universal Document Converters ---
+python-docx
+python-pptx
+openpyxl
+pypandoc
+markdown
+bleach
+ebooklib
+lxml
+beautifulsoup4
+pandas
+pyyaml
+
+# --- PDF Tools ---
+PyMuPDF
+pdfplumber
+pdfminer.six
+pikepdf
+pdf2image
+ocrmypdf
+reportlab>=3.6.0
+
+# --- Image Processing & Formats ---
+Pillow==10.3.0
+pillow-heif==0.15.0
+cairosvg
+rawpy==0.25.1
+imageio==2.34.1
+imageio-ffmpeg==0.5.1
+piexif==1.1.3
+ExifRead==3.0.0
+defusedxml==0.7.1
+scikit-image==0.22.0
+opencv-python-headless==4.9.0.80
+
+# --- Audio & Speech Processing ---
+ffmpeg-python
+pydub
+soundfile
+librosa
+matplotlib
+
+# --- Machine Learning & AI Tools ---
+torch==2.2.2
+rembg
+onnxruntime
+faster-whisper
+openai-whisper
+whisper==1.1.10
+demucs
+spleeter
+numpy==1.26.4
+six==1.17.0
diff --git a/requirements_backup.txt b/requirements_backup.txt
new file mode 100644
index 0000000000000000000000000000000000000000..5517a1376ca85bd20526c30404ac06e8925cf7d7
--- /dev/null
+++ b/requirements_backup.txt
@@ -0,0 +1,126 @@
+# FastAPI & Server
+fastapi
+uvicorn[standard]
+python-multipart
+
+# Database
+SQLAlchemy
+psycopg2-binary
+alembic
+
+# Settings & Utils
+pydantic
+pydantic-settings
+python-dotenv
+
+# Universal Converter Tools
+python-magic
+pillow
+pypandoc
+openpyxl
+pydub
+
+# PDF Processing
+pikepdf
+PyMuPDF
+ocrmypdf
+pdf2image
+
+# Image Processing
+Pillow
+piexif
+wand # for ImageMagick binding
+numpy
+
+# Audio Processing (FFmpeg wrappers)
+ffmpeg-python
+pydub
+soundfile
+librosa
+pydub
+librosa
+soundfile
+matplotlib
+spleeter
+openai-whisper
+#TTS
+torch # install correct wheel for your CUDA or CPU version
+
+
+# Heavy Local AI
+faster-whisper # Coqui TTS
+demucs # AI vocal separation (requires torch)
+
+# Machine Learning backend
+torch
+
+# Visualization (for spectrum images)
+matplotlib
+
+# Utilities
+requests
+python-dateutil
+
+# Admin Panel (FastAPI Admin)
+fastapi-admin
+jinja2
+pyyaml
+markdown
+onnxruntime
+numpy
+pillow
+# --- Core Framework ---
+fastapi==0.115.0
+uvicorn==0.30.1
+python-multipart==0.0.9
+starlette==0.37.2
+
+# --- Database ---
+SQLAlchemy==2.0.30
+psycopg2-binary==2.9.9 # Optional (Postgres); remove if using SQLite
+
+# --- Image Processing ---
+Pillow==10.3.0
+numpy==1.26.4
+
+# For HEIC/HEIF image support (optional but recommended)
+pillow-heif==0.15.0
+
+
+
+# --- EXIF & Metadata ---
+piexif==1.1.3 # Helps with writing EXIF too
+ExifRead==3.0.0 # More robust metadata fallback parser
+defusedxml==0.7.1 # Safe XML (XMP metadata parsing)
+
+# --- Compression / WebP / PNG Optimizers ---
+imageio==2.34.1
+imageio-ffmpeg==0.5.1
+
+# --- Security & Sessions ---
+itsdangerous==2.1.2
+python-dotenv==1.0.1
+
+# --- Admin Panel Support ---
+sqladmin==0.15.2
+jinja2==3.1.4
+
+# --- Utils ---
+requests==2.32.3
+
+# --- Optional AI Tools (used in auto-enhance) ---
+scikit-image==0.22.0
+opencv-python-headless==4.9.0.80
+
+# --- Ads, Analytics / Misc ---
+orjson==3.10.3
+Pillow>=9.0.0
+reportlab>=3.6.0
+pip install rawpy==0.25.1
+numpy==1.26.4
+opencv-python==4.7.0.72
+
+torch==2.2.2
+whisper==1.1.10
+six==1.17.0
+
diff --git a/routers/__pycache__/admin_auth.cpython-312.pyc b/routers/__pycache__/admin_auth.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15d4d3e387864aaa578b2cce8f7cc81719617f38
Binary files /dev/null and b/routers/__pycache__/admin_auth.cpython-312.pyc differ
diff --git a/routers/__pycache__/admin_auth.cpython-39.pyc b/routers/__pycache__/admin_auth.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15c6fec7f519352e4f9b70a8f4a32c3cff1a29f7
Binary files /dev/null and b/routers/__pycache__/admin_auth.cpython-39.pyc differ
diff --git a/routers/__pycache__/ads.cpython-312.pyc b/routers/__pycache__/ads.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df9b185511e0e9c28069fb2ab33a9bcdfe97e704
Binary files /dev/null and b/routers/__pycache__/ads.cpython-312.pyc differ
diff --git a/routers/__pycache__/ads.cpython-39.pyc b/routers/__pycache__/ads.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3020a93afa0ac84afacd891d0c468e8a89d2c6c0
Binary files /dev/null and b/routers/__pycache__/ads.cpython-39.pyc differ
diff --git a/routers/__pycache__/audio.cpython-312.pyc b/routers/__pycache__/audio.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..356a7fdd513e616420257c00f57783e5149b13f2
Binary files /dev/null and b/routers/__pycache__/audio.cpython-312.pyc differ
diff --git a/routers/__pycache__/audio.cpython-39.pyc b/routers/__pycache__/audio.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..34a3ffaed8e285ae9222dfdab32b0240994be4ac
Binary files /dev/null and b/routers/__pycache__/audio.cpython-39.pyc differ
diff --git a/routers/__pycache__/business.cpython-312.pyc b/routers/__pycache__/business.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc181a7779039278a7f5534713f62717c8ea76e4
Binary files /dev/null and b/routers/__pycache__/business.cpython-312.pyc differ
diff --git a/routers/__pycache__/business.cpython-39.pyc b/routers/__pycache__/business.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad0cedbaf52e4a842b664c35e7361d8d119fb764
Binary files /dev/null and b/routers/__pycache__/business.cpython-39.pyc differ
diff --git a/routers/__pycache__/converter_tools.cpython-312.pyc b/routers/__pycache__/converter_tools.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54b60b68af90c601aff430ac8a1b1e9f9c3416cc
Binary files /dev/null and b/routers/__pycache__/converter_tools.cpython-312.pyc differ
diff --git a/routers/__pycache__/converter_tools.cpython-39.pyc b/routers/__pycache__/converter_tools.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5cc13a667b6c16e364c4796319e55a90db5913cb
Binary files /dev/null and b/routers/__pycache__/converter_tools.cpython-39.pyc differ
diff --git a/routers/__pycache__/developer.cpython-312.pyc b/routers/__pycache__/developer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1063accf31c4610da63d617bd98148de11540c2
Binary files /dev/null and b/routers/__pycache__/developer.cpython-312.pyc differ
diff --git a/routers/__pycache__/developer.cpython-39.pyc b/routers/__pycache__/developer.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4c1a3b91e15d96832b4562b376f1892b4505f26c
Binary files /dev/null and b/routers/__pycache__/developer.cpython-39.pyc differ
diff --git a/routers/__pycache__/devtools.cpython-312.pyc b/routers/__pycache__/devtools.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cf890082613671b83a3a4131b1b8317b821b5ce5
Binary files /dev/null and b/routers/__pycache__/devtools.cpython-312.pyc differ
diff --git a/routers/__pycache__/image.cpython-312.pyc b/routers/__pycache__/image.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ed2dd837f574edff60e97e2fc6d6c42f7c14d4e
Binary files /dev/null and b/routers/__pycache__/image.cpython-312.pyc differ
diff --git a/routers/__pycache__/image.cpython-39.pyc b/routers/__pycache__/image.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3d44f0973e79f72139652aac2c9d76b51db08a57
Binary files /dev/null and b/routers/__pycache__/image.cpython-39.pyc differ
diff --git a/routers/__pycache__/image_tools.cpython-312.pyc b/routers/__pycache__/image_tools.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b7a47143d3820cee68b9d384e4d4c2d02c467ab
Binary files /dev/null and b/routers/__pycache__/image_tools.cpython-312.pyc differ
diff --git a/routers/__pycache__/pdf.cpython-312.pyc b/routers/__pycache__/pdf.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..69bd2201c82b817d54fa8d2f0fccfd7905d29894
Binary files /dev/null and b/routers/__pycache__/pdf.cpython-312.pyc differ
diff --git a/routers/__pycache__/pdf.cpython-39.pyc b/routers/__pycache__/pdf.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..84aa87375601bba1500daa42905b6d43891ea396
Binary files /dev/null and b/routers/__pycache__/pdf.cpython-39.pyc differ
diff --git a/routers/__pycache__/pdf_watermark.cpython-312.pyc b/routers/__pycache__/pdf_watermark.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..10359117f953f98c06bd7f403d37dfbcda482e26
Binary files /dev/null and b/routers/__pycache__/pdf_watermark.cpython-312.pyc differ
diff --git a/routers/__pycache__/stats.cpython-312.pyc b/routers/__pycache__/stats.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..422eee11f83c64a2aa10ecba8819cd7c5d166ded
Binary files /dev/null and b/routers/__pycache__/stats.cpython-312.pyc differ
diff --git a/routers/__pycache__/stats.cpython-39.pyc b/routers/__pycache__/stats.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..58d30cdfafd0dd785a7f4ba038938b33fe22e365
Binary files /dev/null and b/routers/__pycache__/stats.cpython-39.pyc differ
diff --git a/routers/__pycache__/tool_tracking.cpython-312.pyc b/routers/__pycache__/tool_tracking.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e98fbe7629a46772efb16f6ff40ed4587988738a
Binary files /dev/null and b/routers/__pycache__/tool_tracking.cpython-312.pyc differ
diff --git a/routers/__pycache__/universal_converter.cpython-312.pyc b/routers/__pycache__/universal_converter.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e98fec94366e95d380ba973570a385507dfc4f3e
Binary files /dev/null and b/routers/__pycache__/universal_converter.cpython-312.pyc differ
diff --git a/routers/__pycache__/universal_converter.cpython-39.pyc b/routers/__pycache__/universal_converter.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c88c0eeaae935ea3547e8197269c753244ef5b87
Binary files /dev/null and b/routers/__pycache__/universal_converter.cpython-39.pyc differ
diff --git a/routers/__pycache__/universal_converter_full.cpython-312.pyc b/routers/__pycache__/universal_converter_full.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2215b5f005efe3bb28eaa6c12a0e5d5e96151e91
Binary files /dev/null and b/routers/__pycache__/universal_converter_full.cpython-312.pyc differ
diff --git a/routers/__pycache__/utility.cpython-312.pyc b/routers/__pycache__/utility.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7a914b55e5189ec91eb55eb5bb6c03421d9cead8
Binary files /dev/null and b/routers/__pycache__/utility.cpython-312.pyc differ
diff --git a/routers/__pycache__/utility.cpython-39.pyc b/routers/__pycache__/utility.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a70acff5895575663095e7f59a730c1478aa191e
Binary files /dev/null and b/routers/__pycache__/utility.cpython-39.pyc differ
diff --git a/routers/__pycache__/video.cpython-312.pyc b/routers/__pycache__/video.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d14aee5c6ef9f27930410b874994ff65e6ebba3
Binary files /dev/null and b/routers/__pycache__/video.cpython-312.pyc differ
diff --git a/routers/__pycache__/video.cpython-39.pyc b/routers/__pycache__/video.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..148cfd53ed40f759cf020b2b93a3990427d0b415
Binary files /dev/null and b/routers/__pycache__/video.cpython-39.pyc differ
diff --git a/routers/ad_manager.py b/routers/ad_manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a9026179275b2748dee7bb598991de103ab421c
--- /dev/null
+++ b/routers/ad_manager.py
@@ -0,0 +1,17 @@
+from fastapi import APIRouter, Depends
+from sqlalchemy.orm import Session
+from core.database import get_db
+from core.models import AdPlacement
+
+router = APIRouter(prefix="/ads", tags=["Ads Manager"])
+
+@router.get("/placements")
+def get_all_ads(db: Session = Depends(get_db)):
+ ads = db.query(AdPlacement).filter(AdPlacement.status == "active").all()
+ return {"ads": [ad.__dict__ for ad in ads]}
+
+@router.get("/placements/{name}")
+def get_ad_by_name(name: str, db: Session = Depends(get_db)):
+ ad = db.query(AdPlacement).filter(AdPlacement.name == name).first()
+ return {"ad": ad.__dict__ if ad else None}
+
diff --git a/routers/admin_auth.py b/routers/admin_auth.py
new file mode 100644
index 0000000000000000000000000000000000000000..379bd835810586378b6357a6d2a63a134158c731
--- /dev/null
+++ b/routers/admin_auth.py
@@ -0,0 +1,25 @@
+# routers/admin_auth.py
+from fastapi import APIRouter, HTTPException, Form
+import jwt
+from datetime import datetime, timedelta
+from core.config import settings
+
+router = APIRouter()
+
+# IMPORTANT: Do NOT use /admin/login (reserved by starlette-admin)
+@router.post("/api/admin/login")
+def admin_login(password: str = Form(...)):
+ if password != settings.ADMIN_SECRET:
+ raise HTTPException(status_code=401, detail="Invalid password")
+
+ token = jwt.encode(
+ {
+ "role": "admin",
+ "exp": datetime.utcnow() + timedelta(days=1)
+ },
+ settings.ADMIN_SECRET,
+ algorithm="HS256"
+ )
+
+ return {"token": token}
+
diff --git a/routers/ads.py b/routers/ads.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef958832c6c52cf66299e0af14346b9a850794be
--- /dev/null
+++ b/routers/ads.py
@@ -0,0 +1,176 @@
+from fastapi import APIRouter, Depends, Body, Request, Response, HTTPException
+from sqlalchemy.orm import Session
+from pydantic import BaseModel
+from typing import Optional
+
+from core.database import get_db
+from services.ads_service import (
+ select_ad_for_placement,
+ record_impression,
+ record_click,
+ issue_client_id,
+)
+from core.models import AdGlobalSettings
+
+router = APIRouter(prefix="/ads", tags=["Ads"])
+COOKIE_NAME = "client_id"
+
+
+# --------------------------------------------------------
+# PLACEMENT MAP
+# --------------------------------------------------------
+PLACEMENT_MAP = {
+ "landing_top": "landing_top",
+ "landing top": "landing_top",
+
+ "landing_bottom": "landing_bottom",
+ "landing bottom": "landing_bottom",
+
+ "tools_top": "tools_top",
+ "tools top": "tools_top",
+
+ "tools_bottom": "tools_bottom",
+ "tools bottom": "tools_bottom",
+
+ "tool_popup": "tool_popup",
+ "tool popup": "tool_popup",
+ "popup": "tool_popup",
+
+ "predownload_video": "predownload_video",
+ "predownload video": "predownload_video",
+ "pre-download video": "predownload_video",
+
+ "download_page_banner": "download_page_banner",
+ "download page banner": "download_page_banner",
+
+ # Missing placements fixed
+ "popup_global": "popup_global",
+ "tools_sidebar": "tools_sidebar",
+}
+
+
+# --------------------------------------------------------
+# MODELS
+# --------------------------------------------------------
+class FetchBody(BaseModel):
+ placement: str
+ device: Optional[str] = None
+ category: Optional[str] = None
+ country: Optional[str] = None
+ size: Optional[str] = None
+
+
+class RecordEvent(BaseModel):
+ ad_unit_id: int
+ placement: str
+ event: str
+
+
+# --------------------------------------------------------
+# ISSUE CLIENT ID
+# --------------------------------------------------------
+@router.get("/issue-client")
+def get_client_id(response: Response):
+ cid = issue_client_id()
+
+ response.set_cookie(
+ key=COOKIE_NAME,
+ value=cid,
+ httponly=False,
+ samesite="Lax",
+ max_age=60 * 60 * 24 * 365,
+)
+
+
+ return {"client_id": cid}
+
+
+# --------------------------------------------------------
+# FETCH AD
+# --------------------------------------------------------
+# --------------------
+# FETCH AD (FIXED)
+# --------------------
+@router.post("/fetch")
+def fetch_ad(
+ request: Request,
+ payload: FetchBody = Body(...),
+ db: Session = Depends(get_db)
+):
+
+ client_id = request.cookies.get(COOKIE_NAME)
+
+ raw = (payload.placement or "").strip().lower()
+ canonical = PLACEMENT_MAP.get(raw, raw)
+
+ ads = select_ad_for_placement(
+ db=db,
+ placement=canonical,
+ device=payload.device,
+ category=payload.category,
+ country=payload.country,
+ client_id=client_id,
+ size=payload.size,
+ )
+
+ # MUST ALWAYS BE A LIST
+ if isinstance(ads, list):
+ ads_list = ads
+ elif isinstance(ads, dict) and "ads" in ads:
+ ads_list = ads["ads"]
+ else:
+ ads_list = []
+
+ # ⭐ MATCH FRONTEND EXPECTATION EXACTLY ⭐
+ return {
+ "data": ads_list, # directly the array
+ "client_id": client_id # direct client id
+ }
+
+
+
+# --------------------------------------------------------
+# RECORD EVENT
+# --------------------------------------------------------
+@router.post("/record")
+def record_event(
+ request: Request,
+ body: RecordEvent,
+ db: Session = Depends(get_db)
+):
+ client_id = request.cookies.get(COOKIE_NAME)
+
+ if body.event == "impression":
+ record_impression(db, body.ad_unit_id, body.placement, client_id)
+
+ elif body.event == "click":
+ record_click(db, body.ad_unit_id, body.placement, client_id)
+
+ else:
+ raise HTTPException(400, "Unknown event type")
+
+ return {"status": "ok"}
+# --------------------------------------------------------
+# DYNAMIC GLOBAL AD SETTINGS (AUTO-DETECT FROM MODEL)
+# --------------------------------------------------------
+@router.get("/settings")
+def get_ad_settings(db: Session = Depends(get_db)):
+ settings = db.query(AdGlobalSettings).first()
+
+ # Table empty → fallback defaults using SQLAlchemy column defaults
+ if not settings:
+ return {
+ col.name: (
+ col.default.arg if hasattr(col.default, "arg") else True
+ )
+ for col in AdGlobalSettings.__table__.columns
+ if col.name not in ("id", "updated_at")
+ }
+
+ # Convert existing row → dict dynamically
+ return {
+ col.name: getattr(settings, col.name)
+ for col in AdGlobalSettings.__table__.columns
+ if col.name not in ("id", "updated_at")
+ }
+
diff --git a/routers/audio.py b/routers/audio.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce7d465d6d21a78d21f0ee05ca89480db4ffaa2e
--- /dev/null
+++ b/routers/audio.py
@@ -0,0 +1,3139 @@
+# routers/audio.py
+
+import uuid
+import subprocess
+from pathlib import Path
+import os
+import json
+import tempfile
+import numpy as np
+import librosa
+import pyloudnorm as pyln
+from fastapi import APIRouter, UploadFile, File, Form, HTTPException, Query, Request
+from fastapi.responses import FileResponse
+
+router = APIRouter(tags=["Audio"])
+
+UPLOAD_DIR = Path("temp/uploads")
+OUTPUT_DIR = Path("temp/output")
+
+UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
+OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
+
+
+def save_upload(file: UploadFile) -> Path:
+ ext = Path(file.filename).suffix or ".bin"
+ path = UPLOAD_DIR / f"{uuid.uuid4().hex}{ext}"
+ with open(path, "wb") as f:
+ f.write(file.file.read())
+ return path
+
+
+# Supported output formats + ffmpeg codecs
+CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+}
+
+
+@router.post("/compress")
+async def compress_audio(
+ audio: UploadFile = File(...),
+ bitrate: int = Form(128),
+ format: str = Form("mp3"),
+):
+ format = format.lower().strip(".")
+
+ if format not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported output format: {format}")
+
+ if bitrate < 32 or bitrate > 320:
+ raise HTTPException(400, "Bitrate must be 32–320 kbps")
+
+ src = save_upload(audio)
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{format}"
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ *CODEC_MAP[format],
+ ]
+
+ # bitrate only applies to lossy formats
+ if format not in ("wav", "flac"):
+ cmd += ["-b:a", f"{bitrate}k"]
+
+ # iOS / Safari compatibility
+ if format in ("mp3", "m4a"):
+ cmd += ["-ar", "44100", "-ac", "2"]
+
+ cmd.append(str(out))
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("\n===== FFMPEG ERROR =====")
+ print(result.stderr)
+ print("========================")
+ raise HTTPException(500, "Audio processing failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(format, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"compressed.{format}",
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Length": str(out.stat().st_size)
+ }
+ )
+
+@router.post("/cut")
+async def cut_audio(
+ audio: UploadFile = File(...),
+ start: float = Form(...),
+ end: float = Form(...),
+ fade: float = Form(0),
+):
+ if start < 0 or end <= start:
+ raise HTTPException(400, "Invalid cut range")
+
+ src = save_upload(audio)
+
+ ext = Path(audio.filename).suffix.lower().strip(".") or "mp3"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ duration = end - start
+
+ # codec per format (SAFE)
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ afilter = []
+ if fade > 0:
+ fade_out_start = max(0, duration - fade)
+ afilter = [
+ "-af",
+ f"afade=t=in:d={fade},afade=t=out:st={fade_out_start}:d={fade}"
+ ]
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-ss", str(start), # ⚠️ seek BEFORE input for accuracy
+ "-i", str(src),
+ "-t", str(duration),
+ "-vn",
+ *afilter,
+ *CODEC_MAP[ext], # ✅ MATCH container
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:", result.stderr)
+ raise HTTPException(500, "Audio cut failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(ext, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"cut.{ext}",
+ headers={"Content-Length": str(out.stat().st_size)}
+ )
+
+@router.post("/convert")
+async def convert_audio(
+ audio: UploadFile = File(...),
+ format: str = Form(...),
+ sample_rate: int = Form(44100),
+ channels: str = Form("stereo"),
+ quality: str = Form("medium"),
+):
+ format = format.lower().strip(".")
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if format not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported output format: {format}")
+
+ src = save_upload(audio)
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{format}"
+
+ bitrate_map = {
+ "low": "96k",
+ "medium": "128k",
+ "high": "192k",
+ }
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-ar", str(sample_rate),
+ "-ac", "1" if channels == "mono" else "2",
+ *CODEC_MAP[format],
+ ]
+
+ if format not in ("wav", "flac"):
+ cmd += ["-b:a", bitrate_map.get(quality, "128k")]
+
+ cmd.append(str(out))
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:", result.stderr)
+ raise HTTPException(500, "Audio conversion failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(format, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"converted.{format}",
+ headers={"Content-Length": str(out.stat().st_size)}
+ )
+
+
+@router.post("/merge")
+async def merge_audio(
+ files: list[UploadFile] = File(...),
+ silenceGap: float = Form(0),
+ format: str = Form("mp3"),
+):
+ if len(files) < 2:
+ raise HTTPException(400, "At least two audio files required")
+
+ format = format.lower().strip(".")
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if format not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {format}")
+
+ inputs = [save_upload(f) for f in files]
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{format}"
+
+ cmd = ["ffmpeg", "-y"]
+ for inp in inputs:
+ cmd += ["-i", str(inp)]
+
+ filter_graph = []
+ concat_inputs = []
+
+ # 🔒 Normalize EVERYTHING first
+ for i in range(len(inputs)):
+ filter_graph.append(
+ f"[{i}:a]"
+ f"aresample=44100,"
+ f"aformat=sample_fmts=s16:channel_layouts=stereo"
+ f"[a{i}]"
+ )
+ concat_inputs.append(f"[a{i}]")
+
+ # Insert silence BETWEEN tracks
+ if silenceGap > 0 and i < len(inputs) - 1:
+ filter_graph.append(
+ f"aevalsrc=0:d={silenceGap}:s=44100, "
+ f"aformat=sample_fmts=s16:channel_layouts=stereo"
+ f"[sil{i}]"
+ )
+ concat_inputs.append(f"[sil{i}]")
+
+ filter_graph.append(
+ f"{''.join(concat_inputs)}"
+ f"concat=n={len(concat_inputs)}:v=0:a=1[out]"
+ )
+
+ cmd += [
+ "-filter_complex", ";".join(filter_graph),
+ "-map", "[out]",
+ "-vn",
+ *CODEC_MAP[format],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:\n", result.stderr)
+ raise HTTPException(500, "Audio merge failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(format, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"merged.{format}",
+ headers={"Content-Length": str(out.stat().st_size)}
+ )
+
+
+@router.post("/denoise")
+async def denoise_audio(
+ audio: UploadFile = File(...),
+ type: str = Form("lowpass"),
+ frequency: int = Form(3000),
+ format: str = Form(None), # optional output format
+):
+ src = save_upload(audio)
+
+ # detect input format
+ input_ext = Path(audio.filename).suffix.lower().strip(".") or "mp3"
+ out_format = (format or input_ext).lower()
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if out_format not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {out_format}")
+
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{out_format}"
+
+ # build filter
+ if type == "lowpass":
+ afilter = f"lowpass=f={frequency}"
+ elif type == "highpass":
+ afilter = f"highpass=f={frequency}"
+ else:
+ raise HTTPException(400, "Invalid filter type")
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-af", afilter,
+ "-vn",
+ *CODEC_MAP[out_format],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:", result.stderr)
+ raise HTTPException(500, "Noise reduction failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(out_format, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"denoised.{out_format}",
+)
+
+
+@router.post("/eq")
+async def audio_eq(
+ audio: UploadFile = File(...),
+ preamp: float = Form(0),
+ bass: float = Form(0),
+ mid: float = Form(0),
+ treble: float = Form(0),
+):
+ src = save_upload(audio)
+
+ # Preserve original format
+ ext = Path(audio.filename).suffix.lower().strip(".") or "wav"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ # Build EQ filter chain
+ filters = []
+
+ if preamp != 0:
+ filters.append(f"volume={preamp}dB")
+
+ if bass != 0:
+ filters.append(f"lowshelf=f=200:g={bass}")
+
+ if mid != 0:
+ filters.append(f"equalizer=f=1000:t=q:w=1:g={mid}")
+
+ if treble != 0:
+ filters.append(f"highshelf=f=3000:g={treble}")
+
+ filter_chain = ",".join(filters) if filters else "anull"
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-af", filter_chain,
+ *CODEC_MAP[ext],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:", result.stderr)
+ raise HTTPException(500, "EQ processing failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(ext, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"eq.{ext}",
+ headers={
+ "Content-Length": str(out.stat().st_size),
+ "Accept-Ranges": "bytes",
+ }
+ )
+
+
+@router.post("/fade")
+async def fade_audio(
+ audio: UploadFile = File(...),
+ fade_in: float = Form(0),
+ fade_out: float = Form(0),
+ curve: str = Form("linear"),
+):
+ src = save_upload(audio)
+
+ ext = Path(audio.filename).suffix.lower().strip(".") or "wav"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ if fade_in < 0 or fade_out < 0:
+ raise HTTPException(400, "Fade values must be >= 0")
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ curve_map = {
+ "linear": "linear",
+ "exponential": "exp"
+ }
+
+ if curve not in curve_map:
+ raise HTTPException(400, "Invalid fade curve")
+
+ # get duration
+ probe = subprocess.run(
+ [
+ "ffprobe", "-v", "error",
+ "-show_entries", "format=duration",
+ "-of", "default=noprint_wrappers=1:nokey=1",
+ str(src)
+ ],
+ capture_output=True, text=True
+ )
+
+ duration = float(probe.stdout.strip())
+ fade_out_start = max(0, duration - fade_out)
+
+ afilters = []
+ if fade_in > 0:
+ afilters.append(
+ f"afade=t=in:st=0:d={fade_in}:curve={curve_map[curve]}"
+ )
+ if fade_out > 0:
+ afilters.append(
+ f"afade=t=out:st={fade_out_start}:d={fade_out}:curve={curve_map[curve]}"
+ )
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-af", ",".join(afilters),
+ *CODEC_MAP[ext],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:", result.stderr)
+ raise HTTPException(500, "Fade processing failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(ext, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"fade.{ext}",
+ headers={"Content-Length": str(out.stat().st_size)}
+ )
+
+
+
+@router.post("/channel-merge")
+async def merge_audio(
+ files: list[UploadFile] = File(...),
+ silenceGap: float = Form(0),
+ format: str | None = Form(None),
+):
+ if len(files) < 2:
+ raise HTTPException(400, "At least two audio files required")
+
+ # Detect output format
+ input_ext = Path(files[0].filename).suffix.lower().strip(".") or "mp3"
+ out_format = (format or input_ext).lower()
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if out_format not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {out_format}")
+
+ # Save inputs
+ inputs = [save_upload(f) for f in files]
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{out_format}"
+
+ cmd = ["ffmpeg", "-y"]
+ for inp in inputs:
+ cmd += ["-i", str(inp)]
+
+ filter_graph = []
+ concat_inputs = []
+
+ for i in range(len(inputs)):
+ # Normalize each track
+ filter_graph.append(
+ f"[{i}:a]"
+ f"aresample=44100,"
+ f"aformat=sample_fmts=s16:channel_layouts=stereo"
+ f"[a{i}]"
+ )
+ concat_inputs.append(f"[a{i}]")
+
+ # Optional silence gap
+ if silenceGap > 0 and i < len(inputs) - 1:
+ filter_graph.append(
+ f"aevalsrc=0:d={silenceGap}:s=44100,"
+ f"aformat=sample_fmts=s16:channel_layouts=stereo"
+ f"[sil{i}]"
+ )
+ concat_inputs.append(f"[sil{i}]")
+
+ filter_graph.append(
+ f"{''.join(concat_inputs)}"
+ f"concat=n={len(concat_inputs)}:v=0:a=1[out]"
+ )
+
+ cmd += [
+ "-filter_complex", ";".join(filter_graph),
+ "-map", "[out]",
+ "-vn",
+ *CODEC_MAP[out_format],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:\n", result.stderr)
+ raise HTTPException(500, "Audio merge failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(out_format, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"merged.{out_format}",
+ headers={
+ "Content-Length": str(out.stat().st_size),
+ "Accept-Ranges": "bytes",
+ }
+ )
+
+@router.post("/trim-advanced")
+async def trim_audio_advanced(
+ audio: UploadFile = File(...),
+ start: float = Form(...),
+ end: float = Form(...),
+ fadeIn: float = Form(0),
+ fadeOut: float = Form(0),
+ curve: str = Form("linear"),
+ gain: float = Form(1.0),
+ normalize: bool = Form(False),
+):
+ if end <= start:
+ raise HTTPException(400, "Invalid trim range")
+
+ # Detect original format
+ input_ext = Path(audio.filename).suffix.lower().strip(".") or "wav"
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if input_ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {input_ext}")
+
+ inp = save_upload(audio)
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{input_ext}"
+
+ duration = end - start
+
+ # 🔥 FIXED FILTER CHAIN (THIS IS THE KEY)
+ filters = [
+ f"atrim=start={start}:end={end}",
+ "asetpts=PTS-STARTPTS", # ✅ REQUIRED
+ f"afade=t=in:st=0:d={fadeIn}" if fadeIn > 0 else None,
+ f"afade=t=out:st={max(0, duration - fadeOut)}:d={fadeOut}" if fadeOut > 0 else None,
+ f"volume={gain}" if gain != 1 else None,
+ "loudnorm" if normalize else None,
+ ]
+
+ filter_chain = ",".join(f for f in filters if f)
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(inp),
+ "-vn",
+ "-af", filter_chain,
+ *CODEC_MAP[input_ext],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:\n", result.stderr)
+ raise HTTPException(500, "Trim failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(input_ext, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"trimmed.{input_ext}",
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Length": str(out.stat().st_size),
+ }
+ )
+
+
+@router.post("/render-eq")
+async def render_eq_audio(
+ audio: UploadFile = File(...),
+ preamp: float = Form(0),
+ bass: float = Form(0),
+ mid: float = Form(0),
+ treble: float = Form(0),
+ format: str | None = Form(None), # optional output format
+):
+ # Save input
+ src = save_upload(audio)
+
+ # Detect original format
+ input_ext = Path(audio.filename).suffix.lower().strip(".") or "wav"
+ out_format = (format or input_ext).lower()
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if out_format not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported output format: {out_format}")
+
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{out_format}"
+
+ # 🔥 EQ FILTER CHAIN (ORDER MATTERS)
+ filters = []
+
+ if preamp != 0:
+ filters.append(f"volume={preamp}dB")
+
+ if bass != 0:
+ filters.append(f"lowshelf=f=200:g={bass}")
+
+ if mid != 0:
+ filters.append(f"equalizer=f=1000:t=q:w=1:g={mid}")
+
+ if treble != 0:
+ filters.append(f"highshelf=f=3000:g={treble}")
+
+ filter_chain = ",".join(filters) if filters else "anull"
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-af", filter_chain,
+ *CODEC_MAP[out_format],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:\n", result.stderr)
+ raise HTTPException(500, "EQ processing failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(out_format, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"eq.{out_format}",
+ headers={
+ "Content-Length": str(out.stat().st_size),
+ "Accept-Ranges": "bytes",
+ }
+ )
+
+@router.post("/isolate")
+async def isolate_audio(
+ audio: UploadFile = File(...),
+ vocalBoost: float = Form(1.0),
+ removeReverb: bool = Form(False),
+ mode: str = Form("full"),
+ start: float | None = Form(None),
+ end: float | None = Form(None),
+):
+ print("\n====== ISOLATE AUDIO START ======")
+
+ # ---------------------------
+ # Save input
+ # ---------------------------
+ src = save_upload(audio)
+ input_size = src.stat().st_size
+ ext = Path(audio.filename).suffix.lower().strip(".") or "mp3"
+
+ print("Input file saved:", src)
+ print("Input size:", input_size)
+ print("Detected format:", ext)
+
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ uid = uuid.uuid4().hex
+ vocals_out = OUTPUT_DIR / f"{uid}_vocals.{ext}"
+ inst_out = OUTPUT_DIR / f"{uid}_instrumental.{ext}"
+
+ print("Vocals output path:", vocals_out)
+ print("Instrumental output path:", inst_out)
+ print("Mode:", mode.upper())
+
+ # ---------------------------
+ # Trim logic
+ # ---------------------------
+ trim_filter = ""
+ if mode == "selection":
+ if start is None or end is None or end <= start:
+ raise HTTPException(400, "Invalid trim range")
+
+ trim_filter = f",atrim=start={start}:end={end},asetpts=PTS-STARTPTS"
+ print("Trim start:", start, "Trim end:", end)
+
+ # ---------------------------
+ # Build filters
+ # ---------------------------
+ vocal_filter = (
+ f"pan=stereo|c0=0.5*c0+0.5*c1|c1=0.5*c0+0.5*c1"
+ f"{trim_filter},volume={vocalBoost}"
+ )
+
+ inst_filter = (
+ f"pan=stereo|c0=0.5*c0-0.5*c1|c1=0.5*c1-0.5*c0"
+ f"{trim_filter}"
+ )
+
+ print("Vocal filter:", vocal_filter)
+ print("Instrumental filter:", inst_filter)
+
+ # ---------------------------
+ # FFmpeg commands
+ # ---------------------------
+ cmd_vocals = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-af", vocal_filter,
+ "-ar", "44100",
+ "-ac", "2",
+ *CODEC_MAP[ext],
+ str(vocals_out)
+ ]
+
+ cmd_inst = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-af", inst_filter,
+ "-ar", "44100",
+ "-ac", "2",
+ *CODEC_MAP[ext],
+ str(inst_out)
+ ]
+
+ # ---------------------------
+ # Run FFmpeg (VOCALS)
+ # ---------------------------
+ print("\nRunning FFmpeg for VOCALS:")
+ print(" ".join(cmd_vocals))
+
+ res_v = subprocess.run(cmd_vocals, capture_output=True, text=True)
+ print("VOCALS return code:", res_v.returncode)
+ print("VOCALS stderr:\n", res_v.stderr)
+
+ # ---------------------------
+ # Run FFmpeg (INSTRUMENTAL)
+ # ---------------------------
+ print("\nRunning FFmpeg for INSTRUMENTAL:")
+ print(" ".join(cmd_inst))
+
+ res_i = subprocess.run(cmd_inst, capture_output=True, text=True)
+ print("INSTRUMENTAL return code:", res_i.returncode)
+ print("INSTRUMENTAL stderr:\n", res_i.stderr)
+
+ # ---------------------------
+ # Validate output
+ # ---------------------------
+ if (
+ res_v.returncode != 0 or
+ res_i.returncode != 0 or
+ not vocals_out.exists() or
+ not inst_out.exists()
+ ):
+ raise HTTPException(500, "Isolation failed")
+
+ print("✅ Vocals file created")
+ print("Vocals size:", vocals_out.stat().st_size)
+ print("✅ Instrumental file created")
+ print("Instrumental size:", inst_out.stat().st_size)
+
+ print("====== ISOLATE AUDIO END ======\n")
+
+ # ---------------------------
+ # IMPORTANT: JSON RESPONSE
+ # ---------------------------
+ return {
+ "vocals_url": f"/static/output/{vocals_out.name}",
+ "instrumental_url": f"/static/output/{inst_out.name}",
+ "format": ext,
+ }
+
+
+
+@router.post("/bpm")
+async def analyze_audio(audio: UploadFile = File(...)):
+ if not audio.content_type.startswith("audio/"):
+ raise HTTPException(status_code=400, detail="Invalid audio file")
+
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(audio.filename)[1]) as tmp:
+ tmp.write(await audio.read())
+ input_path = tmp.name
+
+ try:
+ # -----------------------------
+ # FFmpeg metadata
+ # -----------------------------
+ ffprobe_cmd = [
+ "ffprobe", "-v", "error",
+ "-show_entries",
+ "format=duration,bit_rate,size,format_name",
+ "-show_streams",
+ "-of", "json",
+ input_path
+ ]
+ probe = subprocess.run(ffprobe_cmd, capture_output=True, text=True)
+ meta = json.loads(probe.stdout)
+
+ format_info = meta["format"]
+ stream = meta["streams"][0]
+
+ # -----------------------------
+ # Load audio (mono for analysis)
+ # -----------------------------
+ y, sr = librosa.load(input_path, mono=True)
+
+ duration = librosa.get_duration(y=y, sr=sr)
+
+ # -----------------------------
+ # BPM / Tempo
+ # -----------------------------
+ tempo, beats = librosa.beat.beat_track(y=y, sr=sr)
+
+ # -----------------------------
+ # Loudness (LUFS)
+ # -----------------------------
+ meter = pyln.Meter(sr)
+ loudness = meter.integrated_loudness(y)
+
+ # -----------------------------
+ # Signal metrics
+ # -----------------------------
+ rms = float(np.mean(librosa.feature.rms(y=y)))
+ peak = float(np.max(np.abs(y)))
+ zcr = float(np.mean(librosa.feature.zero_crossing_rate(y)))
+ spectral_centroid = float(np.mean(librosa.feature.spectral_centroid(y=y, sr=sr)))
+ spectral_rolloff = float(np.mean(librosa.feature.spectral_rolloff(y=y, sr=sr)))
+
+ # -----------------------------
+ # Silence detection
+ # -----------------------------
+ intervals = librosa.effects.split(y, top_db=40)
+ non_silent_duration = sum((end - start) for start, end in intervals) / sr
+ silence_percentage = round(100 - (non_silent_duration / duration * 100), 2)
+
+ # -----------------------------
+ # Heuristics
+ # -----------------------------
+ is_music = tempo > 40
+ channels = stream.get("channels", 1)
+
+ return {
+ "file": {
+ "name": audio.filename,
+ "size_bytes": int(format_info.get("size", 0)),
+ "duration_sec": float(round(duration, 2)),
+ "sample_rate": int(sr),
+ "channels": int(stream.get("channels", 1)),
+ "bitrate": int(format_info.get("bit_rate", 0)),
+ "format": str(format_info.get("format_name")),
+ },
+ "music_analysis": {
+ "bpm": float(round(float(tempo), 2)),
+ "beat_count": int(len(beats)),
+ "is_music": bool(tempo > 40),
+ },
+ "loudness": {
+ "lufs": float(round(loudness, 2)),
+ "rms": float(rms),
+ "peak": float(peak),
+ "dynamic_range": float(
+ round(20 * np.log10(peak / rms), 2)
+ ) if rms > 0 else 0.0,
+ },
+ "spectral": {
+ "centroid": float(spectral_centroid),
+ "rolloff": float(spectral_rolloff),
+ "zero_crossing_rate": float(zcr),
+ },
+ "silence": {
+ "silence_percent": float(silence_percentage),
+ },
+ }
+
+ finally:
+ os.remove(input_path)
+
+
+@router.post("/reverse")
+async def reverse_audio(
+ files: UploadFile = File(...),
+ startTime: float = Form(0),
+ endTime: float | None = Form(None),
+ reverseChannels: bool = Form(False),
+ mixOriginal: bool = Form(False),
+):
+ src = save_upload(files)
+
+ ext = Path(files.filename).suffix.lower().strip(".") or "mp3"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ # Probe duration if endTime not provided
+ if endTime is None:
+ probe = subprocess.run(
+ [
+ "ffprobe", "-v", "error",
+ "-show_entries", "format=duration",
+ "-of", "default=noprint_wrappers=1:nokey=1",
+ str(src)
+ ],
+ capture_output=True, text=True
+ )
+ endTime = float(probe.stdout.strip())
+
+ filters = [
+ f"atrim=start={startTime}:end={endTime}",
+ "asetpts=PTS-STARTPTS",
+ "aformat=sample_fmts=s16:channel_layouts=stereo",
+ "aresample=44100",
+ "areverse",
+ ]
+
+ if reverseChannels:
+ filters.append("pan=stereo|c0=c1|c1=c0")
+
+ # NOTE: mixOriginal is intentionally skipped here
+ # because real mixing requires a second stream
+
+ filter_chain = ",".join(filters) # ✅ THIS FIXES EVERYTHING
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-filter_complex", f"[0:a]{filter_chain}[rev]",
+ "-map", "[rev]",
+ "-vn",
+ *CODEC_MAP[ext],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("\n===== FFMPEG ERROR =====")
+ print(result.stderr)
+ print("========================")
+ raise HTTPException(500, "Audio reverse failed")
+
+ return FileResponse(
+ out,
+ media_type={
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(ext, "application/octet-stream"),
+ filename=f"reversed.{ext}",
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Length": str(out.stat().st_size),
+ }
+ )
+
+@router.post("/speed")
+async def change_audio_speed(
+ audio: UploadFile = File(...),
+ speed: float = Form(...),
+):
+ if speed <= 0:
+ raise HTTPException(400, "Speed must be > 0")
+
+ # ---------------------------
+ # Save input
+ # ---------------------------
+ src = save_upload(audio)
+
+ # Detect original format
+ ext = Path(audio.filename).suffix.lower().strip(".") or "mp3"
+
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ # ---------------------------
+ # Build SAFE atempo chain
+ # FFmpeg atempo supports only 0.5–2.0
+ # ---------------------------
+ def build_atempo_chain(speed: float) -> str:
+ filters = []
+ while speed > 2.0:
+ filters.append("atempo=2.0")
+ speed /= 2.0
+ while speed < 0.5:
+ filters.append("atempo=0.5")
+ speed /= 0.5
+ filters.append(f"atempo={speed}")
+ return ",".join(filters)
+
+ atempo_filter = build_atempo_chain(speed)
+
+ # ---------------------------
+ # FFmpeg command
+ # ---------------------------
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-af", atempo_filter,
+ *CODEC_MAP[ext],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("\n===== FFMPEG ERROR =====")
+ print(result.stderr)
+ print("========================")
+ raise HTTPException(500, "Speed change failed")
+
+ # ---------------------------
+ # Return file (same format)
+ # ---------------------------
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(ext, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"speed.{ext}",
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Length": str(out.stat().st_size),
+ }
+ )
+
+@router.post("/render-pitch")
+async def render_pitch(
+ audio: UploadFile = File(...),
+ points: str = Form(...),
+):
+ # ---------------------------
+ # Save input
+ # ---------------------------
+ src = save_upload(audio)
+
+ ext = Path(audio.filename).suffix.lower().strip(".") or "wav"
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ # ---------------------------
+ # Parse automation points
+ # ---------------------------
+ try:
+ points = json.loads(points)
+ except Exception:
+ raise HTTPException(400, "Invalid automation points")
+
+ if not isinstance(points, list) or len(points) < 2:
+ raise HTTPException(400, "At least 2 automation points required")
+
+ points = sorted(points, key=lambda p: float(p["time"]))
+
+ # Clamp safety
+ for p in points:
+ p["time"] = max(0.0, min(1.0, float(p["time"])))
+ p["pitch"] = max(-12.0, min(12.0, float(p["pitch"])))
+
+ # ---------------------------
+ # Get duration
+ # ---------------------------
+ probe = subprocess.run(
+ [
+ "ffprobe", "-v", "error",
+ "-show_entries", "format=duration",
+ "-of", "default=noprint_wrappers=1:nokey=1",
+ str(src)
+ ],
+ capture_output=True, text=True
+ )
+
+ if not probe.stdout.strip():
+ raise HTTPException(500, "Failed to detect duration")
+
+ duration = float(probe.stdout.strip())
+
+ # ---------------------------
+ # Build FILTER_COMPLEX
+ # ---------------------------
+ filters = []
+ concat_inputs = []
+
+ def semitone_to_ratio(st):
+ return pow(2, st / 12.0)
+
+ for i in range(len(points) - 1):
+ start = points[i]["time"] * duration
+ end = points[i + 1]["time"] * duration
+ seg_dur = end - start
+
+ if seg_dur <= 0:
+ continue
+
+ ratio = semitone_to_ratio(points[i]["pitch"])
+
+ filters.append(
+ f"[0:a]"
+ f"atrim=start={start}:end={end},"
+ f"asetpts=PTS-STARTPTS,"
+ f"rubberband=pitch={ratio}:window=short"
+ f"[s{i}]"
+ )
+
+ concat_inputs.append(f"[s{i}]")
+
+ if not concat_inputs:
+ raise HTTPException(400, "Invalid automation segments")
+
+ filters.append(
+ f"{''.join(concat_inputs)}"
+ f"concat=n={len(concat_inputs)}:v=0:a=1[out]"
+ )
+
+ # ---------------------------
+ # FFmpeg command
+ # ---------------------------
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-filter_complex", ";".join(filters),
+ "-map", "[out]",
+ "-vn",
+ *CODEC_MAP[ext],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("\n===== FFMPEG ERROR =====")
+ print(result.stderr)
+ print("========================")
+ raise HTTPException(500, "Pitch render failed")
+
+ # ---------------------------
+ # Return file
+ # ---------------------------
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(ext, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"pitch.{ext}",
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Length": str(out.stat().st_size),
+ }
+ )
+
+
+# routers/audio.py
+
+import uuid
+import subprocess
+from pathlib import Path
+import os
+import json
+import tempfile
+import numpy as np
+import librosa
+import pyloudnorm as pyln
+from fastapi import APIRouter, UploadFile, File, Form, HTTPException, Query
+from fastapi.responses import FileResponse
+
+router = APIRouter(tags=["Audio"])
+
+UPLOAD_DIR = Path("temp/uploads")
+OUTPUT_DIR = Path("temp/output")
+
+UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
+OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
+
+
+def save_upload(file: UploadFile) -> Path:
+ ext = Path(file.filename).suffix or ".bin"
+ path = UPLOAD_DIR / f"{uuid.uuid4().hex}{ext}"
+ with open(path, "wb") as f:
+ f.write(file.file.read())
+ return path
+
+
+# Supported output formats + ffmpeg codecs
+CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+}
+
+
+@router.post("/compress")
+async def compress_audio(
+ audio: UploadFile = File(...),
+ bitrate: int = Form(128),
+ format: str = Form("mp3"),
+):
+ format = format.lower().strip(".")
+
+ if format not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported output format: {format}")
+
+ if bitrate < 32 or bitrate > 320:
+ raise HTTPException(400, "Bitrate must be 32–320 kbps")
+
+ src = save_upload(audio)
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{format}"
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ *CODEC_MAP[format],
+ ]
+
+ # bitrate only applies to lossy formats
+ if format not in ("wav", "flac"):
+ cmd += ["-b:a", f"{bitrate}k"]
+
+ # iOS / Safari compatibility
+ if format in ("mp3", "m4a"):
+ cmd += ["-ar", "44100", "-ac", "2"]
+
+ cmd.append(str(out))
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("\n===== FFMPEG ERROR =====")
+ print(result.stderr)
+ print("========================")
+ raise HTTPException(500, "Audio processing failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(format, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"compressed.{format}",
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Length": str(out.stat().st_size)
+ }
+ )
+
+@router.post("/cut")
+async def cut_audio(
+ audio: UploadFile = File(...),
+ start: float = Form(...),
+ end: float = Form(...),
+ fade: float = Form(0),
+):
+ if start < 0 or end <= start:
+ raise HTTPException(400, "Invalid cut range")
+
+ src = save_upload(audio)
+
+ ext = Path(audio.filename).suffix.lower().strip(".") or "mp3"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ duration = end - start
+
+ # codec per format (SAFE)
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ afilter = []
+ if fade > 0:
+ fade_out_start = max(0, duration - fade)
+ afilter = [
+ "-af",
+ f"afade=t=in:d={fade},afade=t=out:st={fade_out_start}:d={fade}"
+ ]
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-ss", str(start), # ⚠️ seek BEFORE input for accuracy
+ "-i", str(src),
+ "-t", str(duration),
+ "-vn",
+ *afilter,
+ *CODEC_MAP[ext], # ✅ MATCH container
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:", result.stderr)
+ raise HTTPException(500, "Audio cut failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(ext, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"cut.{ext}",
+ headers={"Content-Length": str(out.stat().st_size)}
+ )
+
+@router.post("/convert")
+async def convert_audio(
+ audio: UploadFile = File(...),
+ format: str = Form(...),
+ sample_rate: int = Form(44100),
+ channels: str = Form("stereo"),
+ quality: str = Form("medium"),
+):
+ format = format.lower().strip(".")
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if format not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported output format: {format}")
+
+ src = save_upload(audio)
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{format}"
+
+ bitrate_map = {
+ "low": "96k",
+ "medium": "128k",
+ "high": "192k",
+ }
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-ar", str(sample_rate),
+ "-ac", "1" if channels == "mono" else "2",
+ *CODEC_MAP[format],
+ ]
+
+ if format not in ("wav", "flac"):
+ cmd += ["-b:a", bitrate_map.get(quality, "128k")]
+
+ cmd.append(str(out))
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:", result.stderr)
+ raise HTTPException(500, "Audio conversion failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(format, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"converted.{format}",
+ headers={"Content-Length": str(out.stat().st_size)}
+ )
+
+
+@router.post("/merge")
+async def merge_audio(
+ files: list[UploadFile] = File(...),
+ silenceGap: float = Form(0),
+ format: str = Form("mp3"),
+):
+ if len(files) < 2:
+ raise HTTPException(400, "At least two audio files required")
+
+ format = format.lower().strip(".")
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if format not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {format}")
+
+ inputs = [save_upload(f) for f in files]
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{format}"
+
+ cmd = ["ffmpeg", "-y"]
+ for inp in inputs:
+ cmd += ["-i", str(inp)]
+
+ filter_graph = []
+ concat_inputs = []
+
+ # 🔒 Normalize EVERYTHING first
+ for i in range(len(inputs)):
+ filter_graph.append(
+ f"[{i}:a]"
+ f"aresample=44100,"
+ f"aformat=sample_fmts=s16:channel_layouts=stereo"
+ f"[a{i}]"
+ )
+ concat_inputs.append(f"[a{i}]")
+
+ # Insert silence BETWEEN tracks
+ if silenceGap > 0 and i < len(inputs) - 1:
+ filter_graph.append(
+ f"aevalsrc=0:d={silenceGap}:s=44100, "
+ f"aformat=sample_fmts=s16:channel_layouts=stereo"
+ f"[sil{i}]"
+ )
+ concat_inputs.append(f"[sil{i}]")
+
+ filter_graph.append(
+ f"{''.join(concat_inputs)}"
+ f"concat=n={len(concat_inputs)}:v=0:a=1[out]"
+ )
+
+ cmd += [
+ "-filter_complex", ";".join(filter_graph),
+ "-map", "[out]",
+ "-vn",
+ *CODEC_MAP[format],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:\n", result.stderr)
+ raise HTTPException(500, "Audio merge failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(format, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"merged.{format}",
+ headers={"Content-Length": str(out.stat().st_size)}
+ )
+
+
+@router.post("/denoise")
+async def denoise_audio(
+ audio: UploadFile = File(...),
+ type: str = Form("lowpass"),
+ frequency: int = Form(3000),
+ format: str = Form(None), # optional output format
+):
+ src = save_upload(audio)
+
+ # detect input format
+ input_ext = Path(audio.filename).suffix.lower().strip(".") or "mp3"
+ out_format = (format or input_ext).lower()
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if out_format not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {out_format}")
+
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{out_format}"
+
+ # build filter
+ if type == "lowpass":
+ afilter = f"lowpass=f={frequency}"
+ elif type == "highpass":
+ afilter = f"highpass=f={frequency}"
+ else:
+ raise HTTPException(400, "Invalid filter type")
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-af", afilter,
+ "-vn",
+ *CODEC_MAP[out_format],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:", result.stderr)
+ raise HTTPException(500, "Noise reduction failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(out_format, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"denoised.{out_format}",
+)
+
+
+@router.post("/eq")
+async def audio_eq(
+ audio: UploadFile = File(...),
+ preamp: float = Form(0),
+ bass: float = Form(0),
+ mid: float = Form(0),
+ treble: float = Form(0),
+):
+ src = save_upload(audio)
+
+ # Preserve original format
+ ext = Path(audio.filename).suffix.lower().strip(".") or "wav"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ # Build EQ filter chain
+ filters = []
+
+ if preamp != 0:
+ filters.append(f"volume={preamp}dB")
+
+ if bass != 0:
+ filters.append(f"lowshelf=f=200:g={bass}")
+
+ if mid != 0:
+ filters.append(f"equalizer=f=1000:t=q:w=1:g={mid}")
+
+ if treble != 0:
+ filters.append(f"highshelf=f=3000:g={treble}")
+
+ filter_chain = ",".join(filters) if filters else "anull"
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-af", filter_chain,
+ *CODEC_MAP[ext],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:", result.stderr)
+ raise HTTPException(500, "EQ processing failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(ext, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"eq.{ext}",
+ headers={
+ "Content-Length": str(out.stat().st_size),
+ "Accept-Ranges": "bytes",
+ }
+ )
+
+
+@router.post("/fade")
+async def fade_audio(
+ audio: UploadFile = File(...),
+ fade_in: float = Form(0),
+ fade_out: float = Form(0),
+ curve: str = Form("linear"),
+):
+ src = save_upload(audio)
+
+ ext = Path(audio.filename).suffix.lower().strip(".") or "wav"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ if fade_in < 0 or fade_out < 0:
+ raise HTTPException(400, "Fade values must be >= 0")
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ curve_map = {
+ "linear": "linear",
+ "exponential": "exp"
+ }
+
+ if curve not in curve_map:
+ raise HTTPException(400, "Invalid fade curve")
+
+ # get duration
+ probe = subprocess.run(
+ [
+ "ffprobe", "-v", "error",
+ "-show_entries", "format=duration",
+ "-of", "default=noprint_wrappers=1:nokey=1",
+ str(src)
+ ],
+ capture_output=True, text=True
+ )
+
+ duration = float(probe.stdout.strip())
+ fade_out_start = max(0, duration - fade_out)
+
+ afilters = []
+ if fade_in > 0:
+ afilters.append(
+ f"afade=t=in:st=0:d={fade_in}:curve={curve_map[curve]}"
+ )
+ if fade_out > 0:
+ afilters.append(
+ f"afade=t=out:st={fade_out_start}:d={fade_out}:curve={curve_map[curve]}"
+ )
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-af", ",".join(afilters),
+ *CODEC_MAP[ext],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:", result.stderr)
+ raise HTTPException(500, "Fade processing failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(ext, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"fade.{ext}",
+ headers={"Content-Length": str(out.stat().st_size)}
+ )
+
+
+
+@router.post("/channel-merge")
+async def merge_audio(
+ files: list[UploadFile] = File(...),
+ silenceGap: float = Form(0),
+ format: str | None = Form(None),
+):
+ if len(files) < 2:
+ raise HTTPException(400, "At least two audio files required")
+
+ # Detect output format
+ input_ext = Path(files[0].filename).suffix.lower().strip(".") or "mp3"
+ out_format = (format or input_ext).lower()
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if out_format not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {out_format}")
+
+ # Save inputs
+ inputs = [save_upload(f) for f in files]
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{out_format}"
+
+ cmd = ["ffmpeg", "-y"]
+ for inp in inputs:
+ cmd += ["-i", str(inp)]
+
+ filter_graph = []
+ concat_inputs = []
+
+ for i in range(len(inputs)):
+ # Normalize each track
+ filter_graph.append(
+ f"[{i}:a]"
+ f"aresample=44100,"
+ f"aformat=sample_fmts=s16:channel_layouts=stereo"
+ f"[a{i}]"
+ )
+ concat_inputs.append(f"[a{i}]")
+
+ # Optional silence gap
+ if silenceGap > 0 and i < len(inputs) - 1:
+ filter_graph.append(
+ f"aevalsrc=0:d={silenceGap}:s=44100,"
+ f"aformat=sample_fmts=s16:channel_layouts=stereo"
+ f"[sil{i}]"
+ )
+ concat_inputs.append(f"[sil{i}]")
+
+ filter_graph.append(
+ f"{''.join(concat_inputs)}"
+ f"concat=n={len(concat_inputs)}:v=0:a=1[out]"
+ )
+
+ cmd += [
+ "-filter_complex", ";".join(filter_graph),
+ "-map", "[out]",
+ "-vn",
+ *CODEC_MAP[out_format],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:\n", result.stderr)
+ raise HTTPException(500, "Audio merge failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(out_format, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"merged.{out_format}",
+ headers={
+ "Content-Length": str(out.stat().st_size),
+ "Accept-Ranges": "bytes",
+ }
+ )
+
+@router.post("/trim-advanced")
+async def trim_audio_advanced(
+ audio: UploadFile = File(...),
+ start: float = Form(...),
+ end: float = Form(...),
+ fadeIn: float = Form(0),
+ fadeOut: float = Form(0),
+ curve: str = Form("linear"),
+ gain: float = Form(1.0),
+ normalize: bool = Form(False),
+):
+ if end <= start:
+ raise HTTPException(400, "Invalid trim range")
+
+ # Detect original format
+ input_ext = Path(audio.filename).suffix.lower().strip(".") or "wav"
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if input_ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {input_ext}")
+
+ inp = save_upload(audio)
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{input_ext}"
+
+ duration = end - start
+
+ # 🔥 FIXED FILTER CHAIN (THIS IS THE KEY)
+ filters = [
+ f"atrim=start={start}:end={end}",
+ "asetpts=PTS-STARTPTS", # ✅ REQUIRED
+ f"afade=t=in:st=0:d={fadeIn}" if fadeIn > 0 else None,
+ f"afade=t=out:st={max(0, duration - fadeOut)}:d={fadeOut}" if fadeOut > 0 else None,
+ f"volume={gain}" if gain != 1 else None,
+ "loudnorm" if normalize else None,
+ ]
+
+ filter_chain = ",".join(f for f in filters if f)
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(inp),
+ "-vn",
+ "-af", filter_chain,
+ *CODEC_MAP[input_ext],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:\n", result.stderr)
+ raise HTTPException(500, "Trim failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(input_ext, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"trimmed.{input_ext}",
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Length": str(out.stat().st_size),
+ }
+ )
+
+
+@router.post("/render-eq")
+async def render_eq_audio(
+ audio: UploadFile = File(...),
+ preamp: float = Form(0),
+ bass: float = Form(0),
+ mid: float = Form(0),
+ treble: float = Form(0),
+ format: str | None = Form(None), # optional output format
+):
+ # Save input
+ src = save_upload(audio)
+
+ # Detect original format
+ input_ext = Path(audio.filename).suffix.lower().strip(".") or "wav"
+ out_format = (format or input_ext).lower()
+
+ CODEC_MAP = {
+ "mp3": ["-c:a", "libmp3lame"],
+ "wav": ["-c:a", "pcm_s16le"],
+ "aac": ["-c:a", "aac"],
+ "m4a": ["-c:a", "aac"],
+ "ogg": ["-c:a", "libvorbis"],
+ "opus": ["-c:a", "libopus"],
+ "flac": ["-c:a", "flac"],
+ }
+
+ if out_format not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported output format: {out_format}")
+
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{out_format}"
+
+ # 🔥 EQ FILTER CHAIN (ORDER MATTERS)
+ filters = []
+
+ if preamp != 0:
+ filters.append(f"volume={preamp}dB")
+
+ if bass != 0:
+ filters.append(f"lowshelf=f=200:g={bass}")
+
+ if mid != 0:
+ filters.append(f"equalizer=f=1000:t=q:w=1:g={mid}")
+
+ if treble != 0:
+ filters.append(f"highshelf=f=3000:g={treble}")
+
+ filter_chain = ",".join(filters) if filters else "anull"
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-af", filter_chain,
+ *CODEC_MAP[out_format],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("FFMPEG ERROR:\n", result.stderr)
+ raise HTTPException(500, "EQ processing failed")
+
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(out_format, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"eq.{out_format}",
+ headers={
+ "Content-Length": str(out.stat().st_size),
+ "Accept-Ranges": "bytes",
+ }
+ )
+
+@router.post("/isolate")
+async def isolate_audio(
+ audio: UploadFile = File(...),
+ vocalBoost: float = Form(1.0),
+ removeReverb: bool = Form(False),
+ mode: str = Form("full"),
+ start: float | None = Form(None),
+ end: float | None = Form(None),
+):
+ print("\n====== ISOLATE AUDIO START ======")
+
+ # ---------------------------
+ # Save input
+ # ---------------------------
+ src = save_upload(audio)
+ input_size = src.stat().st_size
+ ext = Path(audio.filename).suffix.lower().strip(".") or "mp3"
+
+ print("Input file saved:", src)
+ print("Input size:", input_size)
+ print("Detected format:", ext)
+
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ uid = uuid.uuid4().hex
+ vocals_out = OUTPUT_DIR / f"{uid}_vocals.{ext}"
+ inst_out = OUTPUT_DIR / f"{uid}_instrumental.{ext}"
+
+ print("Vocals output path:", vocals_out)
+ print("Instrumental output path:", inst_out)
+ print("Mode:", mode.upper())
+
+ # ---------------------------
+ # Trim logic
+ # ---------------------------
+ trim_filter = ""
+ if mode == "selection":
+ if start is None or end is None or end <= start:
+ raise HTTPException(400, "Invalid trim range")
+
+ trim_filter = f",atrim=start={start}:end={end},asetpts=PTS-STARTPTS"
+ print("Trim start:", start, "Trim end:", end)
+
+ # ---------------------------
+ # Build filters
+ # ---------------------------
+ vocal_filter = (
+ f"pan=stereo|c0=0.5*c0+0.5*c1|c1=0.5*c0+0.5*c1"
+ f"{trim_filter},volume={vocalBoost}"
+ )
+
+ inst_filter = (
+ f"pan=stereo|c0=0.5*c0-0.5*c1|c1=0.5*c1-0.5*c0"
+ f"{trim_filter}"
+ )
+
+ print("Vocal filter:", vocal_filter)
+ print("Instrumental filter:", inst_filter)
+
+ # ---------------------------
+ # FFmpeg commands
+ # ---------------------------
+ cmd_vocals = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-af", vocal_filter,
+ "-ar", "44100",
+ "-ac", "2",
+ *CODEC_MAP[ext],
+ str(vocals_out)
+ ]
+
+ cmd_inst = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-af", inst_filter,
+ "-ar", "44100",
+ "-ac", "2",
+ *CODEC_MAP[ext],
+ str(inst_out)
+ ]
+
+ # ---------------------------
+ # Run FFmpeg (VOCALS)
+ # ---------------------------
+ print("\nRunning FFmpeg for VOCALS:")
+ print(" ".join(cmd_vocals))
+
+ res_v = subprocess.run(cmd_vocals, capture_output=True, text=True)
+ print("VOCALS return code:", res_v.returncode)
+ print("VOCALS stderr:\n", res_v.stderr)
+
+ # ---------------------------
+ # Run FFmpeg (INSTRUMENTAL)
+ # ---------------------------
+ print("\nRunning FFmpeg for INSTRUMENTAL:")
+ print(" ".join(cmd_inst))
+
+ res_i = subprocess.run(cmd_inst, capture_output=True, text=True)
+ print("INSTRUMENTAL return code:", res_i.returncode)
+ print("INSTRUMENTAL stderr:\n", res_i.stderr)
+
+ # ---------------------------
+ # Validate output
+ # ---------------------------
+ if (
+ res_v.returncode != 0 or
+ res_i.returncode != 0 or
+ not vocals_out.exists() or
+ not inst_out.exists()
+ ):
+ raise HTTPException(500, "Isolation failed")
+
+ print("✅ Vocals file created")
+ print("Vocals size:", vocals_out.stat().st_size)
+ print("✅ Instrumental file created")
+ print("Instrumental size:", inst_out.stat().st_size)
+
+ print("====== ISOLATE AUDIO END ======\n")
+
+ # ---------------------------
+ # IMPORTANT: JSON RESPONSE
+ # ---------------------------
+ return {
+ "vocals_url": f"/static/output/{vocals_out.name}",
+ "instrumental_url": f"/static/output/{inst_out.name}",
+ "format": ext,
+ }
+
+
+
+@router.post("/bpm")
+async def analyze_audio(audio: UploadFile = File(...)):
+ if not audio.content_type.startswith("audio/"):
+ raise HTTPException(status_code=400, detail="Invalid audio file")
+
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(audio.filename)[1]) as tmp:
+ tmp.write(await audio.read())
+ input_path = tmp.name
+
+ try:
+ # -----------------------------
+ # FFmpeg metadata
+ # -----------------------------
+ ffprobe_cmd = [
+ "ffprobe", "-v", "error",
+ "-show_entries",
+ "format=duration,bit_rate,size,format_name",
+ "-show_streams",
+ "-of", "json",
+ input_path
+ ]
+ probe = subprocess.run(ffprobe_cmd, capture_output=True, text=True)
+ meta = json.loads(probe.stdout)
+
+ format_info = meta["format"]
+ stream = meta["streams"][0]
+
+ # -----------------------------
+ # Load audio (mono for analysis)
+ # -----------------------------
+ y, sr = librosa.load(input_path, mono=True)
+
+ duration = librosa.get_duration(y=y, sr=sr)
+
+ # -----------------------------
+ # BPM / Tempo
+ # -----------------------------
+ tempo, beats = librosa.beat.beat_track(y=y, sr=sr)
+
+ # -----------------------------
+ # Loudness (LUFS)
+ # -----------------------------
+ meter = pyln.Meter(sr)
+ loudness = meter.integrated_loudness(y)
+
+ # -----------------------------
+ # Signal metrics
+ # -----------------------------
+ rms = float(np.mean(librosa.feature.rms(y=y)))
+ peak = float(np.max(np.abs(y)))
+ zcr = float(np.mean(librosa.feature.zero_crossing_rate(y)))
+ spectral_centroid = float(np.mean(librosa.feature.spectral_centroid(y=y, sr=sr)))
+ spectral_rolloff = float(np.mean(librosa.feature.spectral_rolloff(y=y, sr=sr)))
+
+ # -----------------------------
+ # Silence detection
+ # -----------------------------
+ intervals = librosa.effects.split(y, top_db=40)
+ non_silent_duration = sum((end - start) for start, end in intervals) / sr
+ silence_percentage = round(100 - (non_silent_duration / duration * 100), 2)
+
+ # -----------------------------
+ # Heuristics
+ # -----------------------------
+ is_music = tempo > 40
+ channels = stream.get("channels", 1)
+
+ return {
+ "file": {
+ "name": audio.filename,
+ "size_bytes": int(format_info.get("size", 0)),
+ "duration_sec": float(round(duration, 2)),
+ "sample_rate": int(sr),
+ "channels": int(stream.get("channels", 1)),
+ "bitrate": int(format_info.get("bit_rate", 0)),
+ "format": str(format_info.get("format_name")),
+ },
+ "music_analysis": {
+ "bpm": float(round(float(tempo), 2)),
+ "beat_count": int(len(beats)),
+ "is_music": bool(tempo > 40),
+ },
+ "loudness": {
+ "lufs": float(round(loudness, 2)),
+ "rms": float(rms),
+ "peak": float(peak),
+ "dynamic_range": float(
+ round(20 * np.log10(peak / rms), 2)
+ ) if rms > 0 else 0.0,
+ },
+ "spectral": {
+ "centroid": float(spectral_centroid),
+ "rolloff": float(spectral_rolloff),
+ "zero_crossing_rate": float(zcr),
+ },
+ "silence": {
+ "silence_percent": float(silence_percentage),
+ },
+ }
+
+ finally:
+ os.remove(input_path)
+
+
+@router.post("/reverse")
+async def reverse_audio(
+ files: UploadFile = File(...),
+ startTime: float = Form(0),
+ endTime: float | None = Form(None),
+ reverseChannels: bool = Form(False),
+ mixOriginal: bool = Form(False),
+):
+ src = save_upload(files)
+
+ ext = Path(files.filename).suffix.lower().strip(".") or "mp3"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ # Probe duration if endTime not provided
+ if endTime is None:
+ probe = subprocess.run(
+ [
+ "ffprobe", "-v", "error",
+ "-show_entries", "format=duration",
+ "-of", "default=noprint_wrappers=1:nokey=1",
+ str(src)
+ ],
+ capture_output=True, text=True
+ )
+ endTime = float(probe.stdout.strip())
+
+ filters = [
+ f"atrim=start={startTime}:end={endTime}",
+ "asetpts=PTS-STARTPTS",
+ "aformat=sample_fmts=s16:channel_layouts=stereo",
+ "aresample=44100",
+ "areverse",
+ ]
+
+ if reverseChannels:
+ filters.append("pan=stereo|c0=c1|c1=c0")
+
+ # NOTE: mixOriginal is intentionally skipped here
+ # because real mixing requires a second stream
+
+ filter_chain = ",".join(filters) # ✅ THIS FIXES EVERYTHING
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-filter_complex", f"[0:a]{filter_chain}[rev]",
+ "-map", "[rev]",
+ "-vn",
+ *CODEC_MAP[ext],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("\n===== FFMPEG ERROR =====")
+ print(result.stderr)
+ print("========================")
+ raise HTTPException(500, "Audio reverse failed")
+
+ return FileResponse(
+ out,
+ media_type={
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(ext, "application/octet-stream"),
+ filename=f"reversed.{ext}",
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Length": str(out.stat().st_size),
+ }
+ )
+
+@router.post("/speed")
+async def change_audio_speed(
+ audio: UploadFile = File(...),
+ speed: float = Form(...),
+):
+ if speed <= 0:
+ raise HTTPException(400, "Speed must be > 0")
+
+ # ---------------------------
+ # Save input
+ # ---------------------------
+ src = save_upload(audio)
+
+ # Detect original format
+ ext = Path(audio.filename).suffix.lower().strip(".") or "mp3"
+
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ # ---------------------------
+ # Build SAFE atempo chain
+ # FFmpeg atempo supports only 0.5–2.0
+ # ---------------------------
+ def build_atempo_chain(speed: float) -> str:
+ filters = []
+ while speed > 2.0:
+ filters.append("atempo=2.0")
+ speed /= 2.0
+ while speed < 0.5:
+ filters.append("atempo=0.5")
+ speed /= 0.5
+ filters.append(f"atempo={speed}")
+ return ",".join(filters)
+
+ atempo_filter = build_atempo_chain(speed)
+
+ # ---------------------------
+ # FFmpeg command
+ # ---------------------------
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-af", atempo_filter,
+ *CODEC_MAP[ext],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("\n===== FFMPEG ERROR =====")
+ print(result.stderr)
+ print("========================")
+ raise HTTPException(500, "Speed change failed")
+
+ # ---------------------------
+ # Return file (same format)
+ # ---------------------------
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(ext, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"speed.{ext}",
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Length": str(out.stat().st_size),
+ }
+ )
+
+@router.post("/render-pitch")
+async def render_pitch(
+ audio: UploadFile = File(...),
+ points: str = Form(...),
+):
+ # ---------------------------
+ # Save input
+ # ---------------------------
+ src = save_upload(audio)
+
+ ext = Path(audio.filename).suffix.lower().strip(".") or "wav"
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ # ---------------------------
+ # Parse automation points
+ # ---------------------------
+ try:
+ points = json.loads(points)
+ except Exception:
+ raise HTTPException(400, "Invalid automation points")
+
+ if not isinstance(points, list) or len(points) < 2:
+ raise HTTPException(400, "At least 2 automation points required")
+
+ points = sorted(points, key=lambda p: float(p["time"]))
+
+ # Clamp safety
+ for p in points:
+ p["time"] = max(0.0, min(1.0, float(p["time"])))
+ p["pitch"] = max(-12.0, min(12.0, float(p["pitch"])))
+
+ # ---------------------------
+ # Get duration
+ # ---------------------------
+ probe = subprocess.run(
+ [
+ "ffprobe", "-v", "error",
+ "-show_entries", "format=duration",
+ "-of", "default=noprint_wrappers=1:nokey=1",
+ str(src)
+ ],
+ capture_output=True, text=True
+ )
+
+ if not probe.stdout.strip():
+ raise HTTPException(500, "Failed to detect duration")
+
+ duration = float(probe.stdout.strip())
+
+ # ---------------------------
+ # Build FILTER_COMPLEX
+ # ---------------------------
+ filters = []
+ concat_inputs = []
+
+ def semitone_to_ratio(st):
+ return pow(2, st / 12.0)
+
+ for i in range(len(points) - 1):
+ start = points[i]["time"] * duration
+ end = points[i + 1]["time"] * duration
+ seg_dur = end - start
+
+ if seg_dur <= 0:
+ continue
+
+ ratio = semitone_to_ratio(points[i]["pitch"])
+
+ filters.append(
+ f"[0:a]"
+ f"atrim=start={start}:end={end},"
+ f"asetpts=PTS-STARTPTS,"
+ f"rubberband=pitch={ratio}:window=short"
+ f"[s{i}]"
+ )
+
+ concat_inputs.append(f"[s{i}]")
+
+ if not concat_inputs:
+ raise HTTPException(400, "Invalid automation segments")
+
+ filters.append(
+ f"{''.join(concat_inputs)}"
+ f"concat=n={len(concat_inputs)}:v=0:a=1[out]"
+ )
+
+ # ---------------------------
+ # FFmpeg command
+ # ---------------------------
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-filter_complex", ";".join(filters),
+ "-map", "[out]",
+ "-vn",
+ *CODEC_MAP[ext],
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print("\n===== FFMPEG ERROR =====")
+ print(result.stderr)
+ print("========================")
+ raise HTTPException(500, "Pitch render failed")
+
+ # ---------------------------
+ # Return file
+ # ---------------------------
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(ext, "application/octet-stream")
+
+ return FileResponse(
+ out,
+ media_type=media_type,
+ filename=f"pitch.{ext}",
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Length": str(out.stat().st_size),
+ }
+ )
+
+
+@router.post("/normalize-multi")
+async def normalize_multi(
+ audio: UploadFile = File(...),
+ regions: str = Form(...),
+ target: float = Form(-1.0),
+ mode: str = Form("peak"), # peak | loudness
+):
+ src = save_upload(audio)
+
+ ext = Path(audio.filename).suffix.lower().strip(".") or "wav"
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ # ---------------------------
+ # Parse regions
+ # ---------------------------
+ try:
+ regions = sorted(json.loads(regions), key=lambda r: r["start"])
+ except Exception:
+ raise HTTPException(400, "Invalid regions")
+
+ if not regions:
+ raise HTTPException(400, "No regions provided")
+
+ # ---------------------------
+ # Get duration
+ # ---------------------------
+ probe = subprocess.run(
+ [
+ "ffprobe", "-v", "error",
+ "-show_entries", "format=duration",
+ "-of", "default=noprint_wrappers=1:nokey=1",
+ str(src),
+ ],
+ capture_output=True,
+ text=True,
+ )
+
+ if not probe.stdout.strip():
+ raise HTTPException(500, "Failed to read duration")
+
+ duration = float(probe.stdout.strip())
+
+ # ---------------------------
+ # Build filter_complex
+ # ---------------------------
+ filters = []
+ segments = []
+ last_end = 0.0
+
+ for i, r in enumerate(regions):
+ start = max(0.0, float(r["start"]))
+ end = min(duration, float(r["end"]))
+
+ if end <= start:
+ continue
+
+ # untouched BEFORE
+ if start > last_end:
+ filters.append(
+ f"[0:a]atrim={last_end}:{start},asetpts=PTS-STARTPTS[u{i}]"
+ )
+ segments.append(f"[u{i}]")
+
+ # normalized region
+ norm = (
+ f"loudnorm=I={target}:TP=-1.5:LRA=11"
+ if mode == "loudness"
+ else f"volume={target}dB"
+ )
+
+ filters.append(
+ f"[0:a]atrim={start}:{end},asetpts=PTS-STARTPTS,{norm}[n{i}]"
+ )
+ segments.append(f"[n{i}]")
+
+ last_end = end
+
+ # untouched AFTER
+ if last_end < duration:
+ filters.append(
+ f"[0:a]atrim={last_end}:{duration},asetpts=PTS-STARTPTS[u_tail]"
+ )
+ segments.append("[u_tail]")
+
+ filters.append(
+ f"{''.join(segments)}concat=n={len(segments)}:v=0:a=1[out]"
+ )
+
+ # ---------------------------
+ # FFmpeg command
+ # ---------------------------
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-filter_complex", ";".join(filters),
+ "-map", "[out]",
+ "-vn",
+ "-map_metadata", "-1",
+ *CODEC_MAP[ext],
+ str(out),
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print(result.stderr)
+ raise HTTPException(500, "Normalization failed")
+
+ # ---------------------------
+ # RETURN SAME FORMAT
+ # ---------------------------
+ return FileResponse(
+ out,
+ media_type={
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(ext, "application/octet-stream"),
+ filename=f"normalized.{ext}",
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Length": str(out.stat().st_size),
+ }
+ )
+
+@router.post("/normalize-multi")
+async def normalize_multi(
+ audio: UploadFile = File(...),
+ regions: str = Form(...), # [{start: number, end: number}]
+ target: float = Form(-1.0),
+ mode: str = Form("peak"), # peak | loudness
+):
+ # ---------------------------
+ # Save upload
+ # ---------------------------
+ src = save_upload(audio)
+
+ ext = Path(audio.filename).suffix.lower().lstrip(".") or "wav"
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ # ---------------------------
+ # Parse regions
+ # ---------------------------
+ try:
+ regions = sorted(json.loads(regions), key=lambda r: r["start"])
+ except Exception:
+ raise HTTPException(400, "Invalid regions JSON")
+
+ if not regions:
+ raise HTTPException(400, "No regions provided")
+
+ # ---------------------------
+ # Duration via ffprobe
+ # ---------------------------
+ probe = subprocess.run(
+ [
+ "ffprobe", "-v", "error",
+ "-show_entries", "format=duration",
+ "-of", "default=noprint_wrappers=1:nokey=1",
+ str(src)
+ ],
+ capture_output=True, text=True
+ )
+
+ if not probe.stdout.strip():
+ raise HTTPException(500, "Failed to read duration")
+
+ duration = float(probe.stdout.strip())
+
+ # ---------------------------
+ # Build filter_complex
+ # ---------------------------
+ filters = []
+ concat_inputs = []
+ last_end = 0.0
+
+ for i, r in enumerate(regions):
+ start = max(0.0, float(r["start"]))
+ end = min(duration, float(r["end"]))
+
+ if end <= start:
+ continue
+
+ # untouched BEFORE region
+ if start > last_end:
+ filters.append(
+ f"[0:a]atrim={last_end}:{start},asetpts=PTS-STARTPTS[u{i}]"
+ )
+ concat_inputs.append(f"[u{i}]")
+
+ # normalize ONLY region
+ norm = (
+ f"loudnorm=I={target}:TP=-1.5:LRA=11"
+ if mode == "loudness"
+ else f"volume={target}dB"
+ )
+
+ filters.append(
+ f"[0:a]atrim={start}:{end},asetpts=PTS-STARTPTS,{norm}[n{i}]"
+ )
+ concat_inputs.append(f"[n{i}]")
+
+ last_end = end
+
+ # untouched tail
+ if last_end < duration:
+ filters.append(
+ f"[0:a]atrim={last_end}:{duration},asetpts=PTS-STARTPTS[u_tail]"
+ )
+ concat_inputs.append("[u_tail]")
+
+ filters.append(
+ f"{''.join(concat_inputs)}concat=n={len(concat_inputs)}:v=0:a=1[out]"
+ )
+
+ # ---------------------------
+ # FFmpeg
+ # ---------------------------
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-filter_complex", ";".join(filters),
+ "-map", "[out]",
+ "-vn",
+ "-map_metadata", "-1",
+ *CODEC_MAP[ext],
+ str(out),
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print(result.stderr)
+ raise HTTPException(500, "Normalization failed")
+
+ # ---------------------------
+ # Return SAME FORMAT
+ # ---------------------------
+ return FileResponse(
+ out,
+ media_type={
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ "aiff": "audio/aiff",
+ }.get(ext, "application/octet-stream"),
+ filename=audio.filename.replace(".", "_normalized."),
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Length": str(out.stat().st_size),
+ }
+ )
+
+
+@router.api_route(
+ "/stream/{filename}",
+ methods=["GET", "HEAD"],
+)
+async def stream_audio(filename: str):
+ file_path = OUTPUT_DIR / filename
+
+ if not file_path.exists():
+ raise HTTPException(404, "File not found")
+
+ ext = file_path.suffix.lower().lstrip(".")
+ media_type = {
+ "mp3": "audio/mpeg",
+ "wav": "audio/wav",
+ "aac": "audio/aac",
+ "m4a": "audio/mp4",
+ "ogg": "audio/ogg",
+ "opus": "audio/opus",
+ "flac": "audio/flac",
+ }.get(ext, "application/octet-stream")
+
+ return FileResponse(
+ file_path,
+ media_type=media_type,
+ filename=filename,
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Disposition": f'inline; filename="{filename}"', # 🔥 FIX
+ }
+ )
+
+@router.post("/split-channels")
+async def split_channels(
+ audio: UploadFile = File(...),
+ mode: str = Form("standard"), # standard | mid-side
+ invertPhase: bool = Form(False),
+):
+ # ---------------------------
+ # Save input
+ # ---------------------------
+ src = save_upload(audio)
+
+ ext = Path(audio.filename).suffix.lower().strip(".") or "wav"
+ if ext not in CODEC_MAP:
+ raise HTTPException(400, f"Unsupported format: {ext}")
+
+ uid = uuid.uuid4().hex
+ out_a = OUTPUT_DIR / f"{uid}_A.{ext}"
+ out_b = OUTPUT_DIR / f"{uid}_B.{ext}"
+
+ # ---------------------------
+ # Build filters
+ # ---------------------------
+ if mode == "standard":
+ # Left / Right
+ filter_a = "pan=mono|c0=c0"
+ filter_b = "pan=mono|c0=c1"
+
+ if invertPhase:
+ filter_b += ",volume=-1"
+
+ elif mode == "mid-side":
+ # Mid / Side
+ filter_a = "pan=mono|c0=0.5*c0+0.5*c1"
+ filter_b = "pan=mono|c0=0.5*c0-0.5*c1"
+
+ else:
+ raise HTTPException(400, "Invalid split mode")
+
+ # ---------------------------
+ # FFmpeg commands
+ # ---------------------------
+ cmd_a = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-af", filter_a,
+ "-ar", "44100",
+ "-ac", "1",
+ *CODEC_MAP[ext],
+ str(out_a)
+ ]
+
+ cmd_b = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vn",
+ "-af", filter_b,
+ "-ar", "44100",
+ "-ac", "1",
+ *CODEC_MAP[ext],
+ str(out_b)
+ ]
+
+ res_a = subprocess.run(cmd_a, capture_output=True, text=True)
+ res_b = subprocess.run(cmd_b, capture_output=True, text=True)
+
+ # ---------------------------
+ # Validation
+ # ---------------------------
+ if (
+ res_a.returncode != 0 or
+ res_b.returncode != 0 or
+ not out_a.exists() or
+ not out_b.exists() or
+ out_a.stat().st_size == 0 or
+ out_b.stat().st_size == 0
+ ):
+ print("A ERROR:", res_a.stderr)
+ print("B ERROR:", res_b.stderr)
+ raise HTTPException(500, "Channel split failed")
+
+ # ---------------------------
+ # JSON response (frontend SAFE)
+ # ---------------------------
+ return {
+ "leftUrl": f"/audio/stream/{out_a.name}",
+ "rightUrl": f"/audio/stream/{out_b.name}",
+ "mode": mode,
+ "format": ext,
+ }
diff --git a/routers/business.py b/routers/business.py
new file mode 100644
index 0000000000000000000000000000000000000000..efafeece9a0c69e326193be719ac79db528b4514
--- /dev/null
+++ b/routers/business.py
@@ -0,0 +1,78 @@
+# backend/routers/business.py
+from fastapi import APIRouter, UploadFile, File, Form, Depends
+from sqlalchemy.orm import Session
+import json, os
+
+from core.database import get_db
+# 🔑 IMPORT THE NEW DEPENDENCY (Fixed U+00A0 issue here)
+from core.dependencies import LogToolUsage
+from services.business_service import (
+ generate_qr, generate_barcode, generate_invoice
+)
+from utils.file_utils import save_upload_file
+from utils.response_utils import send_file
+
+# ❌ REMOVED: No longer needed, as the dependency handles the call
+# from services.stats_service import increment_tool_usage
+
+
+router = APIRouter()
+
+# ---------------- QR ----------------
+
+# ✅ ADDED DEPENDENCY: LogToolUsage("qr_generator")
+@router.post("/qr", dependencies=[Depends(LogToolUsage("qr_generator"))])
+async def api_qr(
+ data: str = Form(...),
+ box_size: int = Form(10),
+ border: int = Form(4),
+ fmt: str = Form("png"),
+ db: Session = Depends(get_db)
+):
+ out = generate_qr(data, box_size, border, fmt)
+ # ❌ REMOVED MANUAL CALL: increment_tool_usage(db, "qr_generator")
+ return send_file(out)
+
+# ---------------- BARCODE ----------------
+
+# ✅ ADDED DEPENDENCY: LogToolUsage("barcode_generator")
+@router.post("/barcode", dependencies=[Depends(LogToolUsage("barcode_generator"))])
+async def api_barcode(
+ data: str = Form(...),
+ barcode_type: str = Form("code128"),
+ fmt: str = Form("png"),
+ db: Session = Depends(get_db)
+):
+ out = generate_barcode(data, barcode_type, fmt)
+ # ❌ REMOVED MANUAL CALL: increment_tool_usage(db, "barcode_generator")
+ return send_file(out)
+
+# ---------------- INVOICE ----------------
+
+# ✅ ADDED DEPENDENCY: LogToolUsage("invoice_generator")
+@router.post("/invoice", dependencies=[Depends(LogToolUsage("invoice_generator"))])
+async def api_invoice(
+ invoice_number: str = Form(...),
+ seller: str = Form(...),
+ buyer: str = Form(...),
+ items_json: str = Form(...),
+ logo: UploadFile = File(None),
+ currency: str = Form("USD"),
+ db: Session = Depends(get_db)
+):
+ logo_path = None
+
+ try:
+ if logo:
+ logo_path = save_upload_file(logo)
+
+ items = json.loads(items_json)
+ out = generate_invoice(invoice_number, seller, buyer, items, logo_path, currency)
+ # ❌ REMOVED MANUAL CALL: increment_tool_usage(db, "invoice_generator")
+
+ finally:
+ if logo_path:
+ try: os.remove(logo_path)
+ except: pass
+
+ return send_file(out)
diff --git a/routers/converter_tools.py b/routers/converter_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..69d7339e70127248eac1e04dea3fd9687a003f6c
--- /dev/null
+++ b/routers/converter_tools.py
@@ -0,0 +1,9961 @@
+# backend/routers/converter_tools.py
+from fastapi import APIRouter, UploadFile, File, Form, Depends, HTTPException, Request
+from sqlalchemy.orm import Session
+import os
+import pdfplumber
+from xml.sax.saxutils import escape
+import traceback
+from typing import List
+from fastapi.responses import JSONResponse
+from fastapi.staticfiles import StaticFiles
+from starlette.concurrency import run_in_threadpool
+import fitz # PyMuPDF
+import markdown
+import bleach
+import uuid
+import subprocess
+from core.database import get_db
+from utils.file_utils import save_upload_file
+from utils.response_utils import send_file
+# 🔑 IMPORT THE AUTOMATIC LOGGING DEPENDENCY
+from core.dependencies import LogToolUsage
+from services.converter_tools_service import (
+ image_to_webp,
+ image_to_svg_embed,
+ pdf_to_text,
+ markdown_to_html
+)
+from fastapi.concurrency import run_in_threadpool
+from PIL import Image
+import pillow_heif
+pillow_heif.register_heif_opener()
+
+# ❌ REMOVED: No longer needed, as the dependency handles the call
+# from services.stats_service import increment_tool_usage
+
+router = APIRouter()
+OUTPUT_DIR = "static/output"
+os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+
+# ---------------- IMAGE → WEBP ----------------
+# ✅ ADDED DEPENDENCY: LogToolUsage("image_to_webp")
+@router.post("/webp")
+async def api_image_to_webp(
+ file: UploadFile = File(...),
+ quality: float = Form(0.8),
+ lossless: bool = Form(False),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved input:", input_path)
+
+ # ✅ SAFE converter call (NO keyword args)
+ def _convert(path, q):
+ return image_to_webp(path, q)
+
+ output_path = await run_in_threadpool(_convert, input_path, quality)
+ print("📤 Output:", output_path)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "WebP conversion failed: No output produced.")
+
+ OUTPUT_DIR = "static/output"
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+ file_url = f"https://api.cloudaipdf.com/static/output/{filename}"
+
+ return {
+ "url": file_url,
+ "size": size
+ }
+
+ except Exception as e:
+ print("🔥 IMAGE → WEBP FAILED")
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+
+# ---------------- IMAGE → SVG ----------------
+# ✅ ADDED DEPENDENCY: LogToolUsage("image_to_svg_embed")
+@router.post("/svg-embed")
+async def api_image_to_svg_embed(
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+
+ input_path = None
+ output_path = None
+
+ try:
+ # ---------------------------------------------------
+ # 1️⃣ SAVE INPUT FILE
+ # ---------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 SVG INPUT:", input_path)
+
+ # ---------------------------------------------------
+ # 2️⃣ RUN CONVERTER
+ # ---------------------------------------------------
+ def _convert():
+ return image_to_svg_embed(input_path)
+
+ output_path = await run_in_threadpool(_convert)
+ print("📤 SVG OUTPUT:", output_path)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "SVG conversion failed (no output file).")
+
+ # ---------------------------------------------------
+ # 3️⃣ MOVE TO /static/output/
+ # ---------------------------------------------------
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+
+ os.replace(output_path, final_path)
+
+ # Compute SVG file size
+ size = os.path.getsize(final_path)
+
+ # ---------------------------------------------------
+ # 4️⃣ RETURN URL + SIZE
+ # ---------------------------------------------------
+ file_url = f"https://api.cloudaipdf.com/static/output/{filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ print("🔥 IMAGE → SVG FAILED")
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=f"SVG embed failed: {str(e)}")
+
+ finally:
+ # ---------------------------------------------------
+ # 5️⃣ CLEAN UP INPUT FILE
+ # ---------------------------------------------------
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+# ---------------- PDF → TEXT ----------------
+# ✅ ADDED DEPENDENCY: LogToolUsage("pdf_to_text")
+def extract_text_from_pdf(path: str) -> str:
+ """Extract plain text from PDF using PyMuPDF."""
+ text = []
+ with fitz.open(path) as doc:
+ for page in doc:
+ text.append(page.get_text())
+ return "\n".join(text)
+
+
+@router.post("/pdf-text")
+async def api_pdf_to_text(
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Save uploaded PDF
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PDF:", input_path)
+
+ # ----------------------------------------------------
+ # 2️⃣ Extract text (threadpool)
+ # ----------------------------------------------------
+ text = await run_in_threadpool(extract_text_from_pdf, input_path)
+
+ if text is None:
+ raise HTTPException(500, "PDF text extraction failed: No text returned.")
+
+ # ----------------------------------------------------
+ # 3️⃣ Save output .txt file
+ # ----------------------------------------------------
+ output_filename = os.path.basename(input_path).rsplit(".", 1)[0] + ".txt"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ with open(output_path, "w", encoding="utf-8") as f:
+ f.write(text)
+
+ file_url = f"https://api.cloudaipdf.com/static/output/{output_filename}"
+
+ print("📤 Extracted text saved:", output_path)
+
+ return {
+ "url": file_url,
+ "size": os.path.getsize(output_path)
+ }
+
+ except Exception as e:
+ print("🔥 PDF → TEXT FAILED")
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # ----------------------------------------------------
+ # 4️⃣ Clean input PDF safely
+ # ----------------------------------------------------
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+
+# ---------------- AAC → MP3 ----------------
+
+@router.post("/aac-to-mp3")
+async def api_aac_to_mp3(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Save uploaded file
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved audio:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.mp3"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # ----------------------------------------------------
+ # 2️⃣ Convert using ffmpeg
+ # ----------------------------------------------------
+ def _convert():
+ cmd = [
+ "ffmpeg",
+ "-y",
+ "-loglevel", "error",
+ "-i", input_path,
+ "-map", "0:a:0",
+ "-vn",
+ "-acodec", "libmp3lame",
+ "-b:a", "192k",
+ output_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "AAC to MP3 conversion failed.")
+
+ # ----------------------------------------------------
+ # 3️⃣ Move to /static/output/
+ # ----------------------------------------------------
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 4️⃣ Build dynamic URL (auto localhost / production)
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 AAC → MP3 output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ print("🔥 AAC → MP3 FAILED")
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- AUDIO → MP3 ----------------
+@router.post("/audio-to-mp3")
+async def api_audio_to_mp3(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved audio:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.mp3"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert using ffmpeg (auto-detect input format)
+ def _convert():
+ cmd = [
+ "ffmpeg",
+ "-y",
+ "-loglevel", "error",
+ "-i", input_path,
+ "-map", "0:a:0",
+ "-vn",
+ "-acodec", "libmp3lame",
+ "-b:a", "192k",
+ output_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "Audio to MP3 conversion failed.")
+
+ # 3️⃣ Move to static output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+# ---------------- AVIF → JPG ----------------
+@router.post("/avif-to-jpg")
+async def api_avif_to_jpg(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved AVIF:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.jpg"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert AVIF → JPG
+ def _convert():
+ with Image.open(input_path) as img:
+ rgb = img.convert("RGB")
+ rgb.save(output_path, "JPEG", quality=95)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "AVIF to JPG conversion failed.")
+
+ # 3️⃣ Move to static output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+# ---------------- AVIF → PNG ----------------
+@router.post("/avif-to-png")
+async def api_avif_to_png(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved AVIF:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.png"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert AVIF → PNG
+ def _convert():
+ with Image.open(input_path) as img:
+ img.save(output_path, "PNG")
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "AVIF to PNG conversion failed.")
+
+ # 3️⃣ Move to static output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+
+# ---------------- AVIF → WEBP ----------------
+@router.post("/avif-to-webp")
+async def api_avif_to_webp(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved AVIF:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.webp"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert AVIF → WEBP
+ def _convert():
+ with Image.open(input_path) as img:
+ img.save(output_path, "WEBP", quality=95)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "AVIF to WEBP conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- AVI → MP4 ----------------
+@router.post("/avi-to-mp4")
+async def api_avi_to_mp4(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved AVI:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.mp4"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert AVI → MP4 using ffmpeg
+ def _convert():
+ cmd = [
+ "ffmpeg",
+ "-y",
+ "-loglevel", "error",
+ "-i", input_path,
+ "-vcodec", "libx264",
+ "-acodec", "aac",
+ output_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "AVI to MP4 conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+
+# ---------------- BINARY → HEX ----------------
+@router.post("/binary-to-hex")
+async def api_binary_to_hex(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved binary file:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.txt"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert Binary → Hex safely
+ def _convert():
+ with open(input_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Remove whitespace/newlines
+ cleaned = "".join(content.split())
+
+ # Validate binary
+ if not cleaned:
+ raise ValueError("File is empty.")
+
+ if not all(c in "01" for c in cleaned):
+ raise ValueError("File contains non-binary characters.")
+
+ # Pad to multiple of 4 bits (safe nibble conversion)
+ if len(cleaned) % 4 != 0:
+ padding = 4 - (len(cleaned) % 4)
+ cleaned = cleaned + ("0" * padding)
+
+ # Convert nibble by nibble (safe for large files)
+ hex_chunks = []
+ for i in range(0, len(cleaned), 4):
+ nibble = cleaned[i:i+4]
+ hex_chunks.append(hex(int(nibble, 2))[2:].upper())
+
+ hex_result = "".join(hex_chunks)
+
+ with open(output_path, "w", encoding="utf-8") as out:
+ out.write(hex_result)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "Binary to Hex conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL (localhost + production safe)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 Binary → Hex output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except ValueError as ve:
+ raise HTTPException(status_code=400, detail=str(ve))
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Clean input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- BMP → JPG ----------------
+@router.post("/bmp-to-jpg")
+async def api_bmp_to_jpg(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded BMP
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved BMP:", input_path)
+
+ # Validate extension (extra safety)
+ if not input_path.lower().endswith(".bmp"):
+ raise HTTPException(status_code=400, detail="Invalid BMP file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.jpg"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert BMP → JPG
+ def _convert():
+ with Image.open(input_path) as img:
+ rgb = img.convert("RGB") # Important for JPG
+ rgb.save(output_path, "JPEG", quality=95)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "BMP to JPG conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL (works for localhost + production)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 BMP → JPG output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- BMP → PNG ----------------
+@router.post("/bmp-to-png")
+async def api_bmp_to_png(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded BMP
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved BMP:", input_path)
+
+ # Extra validation (backend safety)
+ if not input_path.lower().endswith(".bmp"):
+ raise HTTPException(status_code=400, detail="Invalid BMP file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.png"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert BMP → PNG
+ def _convert():
+ with Image.open(input_path) as img:
+ img.save(output_path, "PNG")
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "BMP to PNG conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Build dynamic URL (localhost + production safe)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 BMP → PNG output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Clean up input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- CONVERT IMAGE DPI ----------------
+@router.post("/convert-image-dpi")
+async def api_convert_image_dpi(
+ request: Request,
+ file: UploadFile = File(...),
+ dpi: int = Form(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate DPI
+ if dpi not in [72, 96, 150, 300, 600]:
+ raise HTTPException(status_code=400, detail="Invalid DPI value.")
+
+ # 2️⃣ Save uploaded image
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved Image:", input_path)
+
+ uid = str(uuid.uuid4())
+ ext = os.path.splitext(input_path)[1].lower()
+
+ if not ext:
+ raise HTTPException(status_code=400, detail="Invalid image format.")
+
+ output_filename = f"{uid}{ext}"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 3️⃣ Change DPI (metadata only)
+ def _convert():
+ with Image.open(input_path) as img:
+ img.save(output_path, dpi=(dpi, dpi))
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "DPI conversion failed.")
+
+ # 4️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 5️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 DPI changed:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size,
+ "dpi": dpi
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 6️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- CREATE ZIP ----------------
+import zipfile
+
+@router.post("/create-zip")
+async def api_create_zip(
+ request: Request,
+ files: list[UploadFile] = File(...),
+ db: Session = Depends(get_db)
+):
+ saved_paths = []
+ output_path = None
+
+ try:
+ if not files or len(files) == 0:
+ raise HTTPException(status_code=400, detail="No files uploaded.")
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # 1️⃣ Save all uploaded files
+ for file in files:
+ path = await run_in_threadpool(save_upload_file, file)
+ saved_paths.append(path)
+
+ print(f"📥 Saved {len(saved_paths)} files")
+
+ # 2️⃣ Create ZIP
+ uid = str(uuid.uuid4())
+ zip_filename = f"{uid}.zip"
+ output_path = os.path.join(TMP_DIR, zip_filename)
+
+ def _zip_files():
+ with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as zipf:
+ for path in saved_paths:
+ arcname = os.path.basename(path) # keep original filename
+ zipf.write(path, arcname)
+
+ await run_in_threadpool(_zip_files)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="ZIP creation failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📦 ZIP created:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size,
+ "files_count": len(saved_paths)
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup uploaded temp files
+ for path in saved_paths:
+ try:
+ await run_in_threadpool(os.remove, path)
+ except:
+ pass
+
+# ---------------- CSV → HTML TABLE ----------------
+import csv
+import html
+
+@router.post("/csv-table-to-html")
+async def api_csv_table_to_html(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded CSV
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved CSV:", input_path)
+
+ if not input_path.lower().endswith(".csv"):
+ raise HTTPException(status_code=400, detail="Invalid CSV file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.html"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert CSV → HTML Table
+ def _convert():
+ with open(input_path, newline='', encoding="utf-8") as csvfile:
+ reader = csv.reader(csvfile)
+
+ rows = list(reader)
+ if not rows:
+ raise ValueError("CSV file is empty.")
+
+ html_content = [
+ "",
+ "",
+ "
",
+ " ",
+ "CSV to HTML Table ",
+ "",
+ "",
+ "",
+ ""
+ ]
+
+ # Header row
+ headers = rows[0]
+ html_content.append("")
+ for header in headers:
+ html_content.append(f"{html.escape(header)} ")
+ html_content.append(" ")
+
+ # Data rows
+ html_content.append("")
+ for row in rows[1:]:
+ html_content.append("")
+ for cell in row:
+ html_content.append(f"{html.escape(cell)} ")
+ html_content.append(" ")
+ html_content.append(" ")
+
+ html_content.extend([
+ "
",
+ "",
+ ""
+ ])
+
+ with open(output_path, "w", encoding="utf-8") as out:
+ out.write("\n".join(html_content))
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="CSV to HTML conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 CSV → HTML output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input CSV
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- CSV → PDF ----------------
+import csv
+import fitz # PyMuPDF
+
+@router.post("/csv-to-pdf")
+async def api_csv_to_pdf(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded CSV
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved CSV:", input_path)
+
+ if not input_path.lower().endswith(".csv"):
+ raise HTTPException(status_code=400, detail="Invalid CSV file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.pdf"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert CSV → PDF
+ def _convert():
+ with open(input_path, newline='', encoding="utf-8") as csvfile:
+ reader = list(csv.reader(csvfile))
+ if not reader:
+ raise ValueError("CSV is empty.")
+
+ doc = fitz.open()
+ page = doc.new_page()
+
+ font_size = 10
+ margin = 40
+ y = margin
+ line_height = 14
+
+ max_width = page.rect.width - 2 * margin
+ col_count = len(reader[0])
+ col_width = max_width / col_count
+
+ for row in reader:
+ if y > page.rect.height - margin:
+ page = doc.new_page()
+ y = margin
+
+ for i, cell in enumerate(row):
+ x = margin + i * col_width
+ text = str(cell)
+
+ page.insert_textbox(
+ fitz.Rect(x, y, x + col_width, y + line_height),
+ text,
+ fontsize=font_size,
+ fontname="helv",
+ align=0
+ )
+
+ y += line_height
+
+ doc.save(output_path)
+ doc.close()
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="CSV to PDF conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📄 CSV → PDF output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input CSV
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- CSV → XLSX ----------------
+import csv
+from openpyxl import Workbook
+
+@router.post("/csv-to-xlsx")
+async def api_csv_to_xlsx(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded CSV
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved CSV:", input_path)
+
+ if not input_path.lower().endswith(".csv"):
+ raise HTTPException(status_code=400, detail="Invalid CSV file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.xlsx"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert CSV → XLSX
+ def _convert():
+ wb = Workbook()
+ ws = wb.active
+ ws.title = "Sheet1"
+
+ with open(input_path, newline='', encoding="utf-8") as csvfile:
+ reader = csv.reader(csvfile)
+ for row in reader:
+ ws.append(row)
+
+ wb.save(output_path)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="CSV to XLSX conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📊 CSV → XLSX output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input CSV
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- CSV → XML ----------------
+import csv
+import xml.etree.ElementTree as ET
+
+@router.post("/csv-to-xml")
+async def api_csv_to_xml(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded CSV
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved CSV:", input_path)
+
+ if not input_path.lower().endswith(".csv"):
+ raise HTTPException(status_code=400, detail="Invalid CSV file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.xml"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert CSV → XML
+ def _convert():
+ with open(input_path, newline='', encoding="utf-8") as csvfile:
+ reader = list(csv.reader(csvfile))
+
+ if not reader:
+ raise ValueError("CSV file is empty.")
+
+ headers = reader[0]
+
+ root = ET.Element("table")
+
+ for row in reader[1:]:
+ row_element = ET.SubElement(root, "row")
+
+ for i, cell in enumerate(row):
+ tag = headers[i].strip().replace(" ", "_")
+
+ # Ensure valid XML tag name
+ if not tag.isidentifier():
+ tag = f"column_{i+1}"
+
+ cell_element = ET.SubElement(row_element, tag)
+ cell_element.text = str(cell)
+
+ tree = ET.ElementTree(root)
+ tree.write(output_path, encoding="utf-8", xml_declaration=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="CSV to XML conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📄 CSV → XML output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input CSV
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- DOC → DOCX ----------------
+@router.post("/doc-to-docx")
+async def api_doc_to_docx(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded DOC
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved DOC:", input_path)
+
+ if not input_path.lower().endswith(".doc"):
+ raise HTTPException(status_code=400, detail="Invalid DOC file.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # LibreOffice will auto-name output
+ def _convert():
+ cmd = [
+ "soffice",
+ "--headless",
+ "--convert-to", "docx",
+ "--outdir", TMP_DIR,
+ input_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ # Find converted file
+ base_name = os.path.splitext(os.path.basename(input_path))[0]
+ converted_name = base_name + ".docx"
+ output_path = os.path.join(TMP_DIR, converted_name)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="DOC to DOCX conversion failed.")
+
+ # 3️⃣ Rename to unique filename
+ final_filename = f"{uid}.docx"
+ final_path = os.path.join(OUTPUT_DIR, final_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{final_filename}"
+
+ print("📄 DOC → DOCX output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="LibreOffice conversion failed.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- DOCX → DOC ----------------
+@router.post("/docx-to-doc")
+async def api_docx_to_doc(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded DOCX
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved DOCX:", input_path)
+
+ if not input_path.lower().endswith(".docx"):
+ raise HTTPException(status_code=400, detail="Invalid DOCX file.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # 2️⃣ Convert using LibreOffice
+ def _convert():
+ cmd = [
+ "soffice",
+ "--headless",
+ "--convert-to", "doc",
+ "--outdir", TMP_DIR,
+ input_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ # LibreOffice auto-generates filename
+ base_name = os.path.splitext(os.path.basename(input_path))[0]
+ converted_name = base_name + ".doc"
+ output_path = os.path.join(TMP_DIR, converted_name)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="DOCX to DOC conversion failed.")
+
+ # 3️⃣ Rename to unique filename
+ final_filename = f"{uid}.doc"
+ final_path = os.path.join(OUTPUT_DIR, final_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{final_filename}"
+
+ print("📄 DOCX → DOC output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="LibreOffice conversion failed.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- DOCX → HTML ----------------
+@router.post("/docx-to-html")
+async def api_docx_to_html(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded DOCX
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved DOCX:", input_path)
+
+ if not input_path.lower().endswith(".docx"):
+ raise HTTPException(status_code=400, detail="Invalid DOCX file.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # 2️⃣ Convert DOCX → HTML using LibreOffice
+ def _convert():
+ cmd = [
+ "soffice",
+ "--headless",
+ "--convert-to", "html",
+ "--outdir", TMP_DIR,
+ input_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ # LibreOffice auto-generates output filename
+ base_name = os.path.splitext(os.path.basename(input_path))[0]
+ converted_name = base_name + ".html"
+ output_path = os.path.join(TMP_DIR, converted_name)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="DOCX to HTML conversion failed.")
+
+ # 3️⃣ Rename to unique filename
+ final_filename = f"{uid}.html"
+ final_path = os.path.join(OUTPUT_DIR, final_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{final_filename}"
+
+ print("🌐 DOCX → HTML output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="LibreOffice conversion failed.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- DOCX → MARKDOWN ----------------
+@router.post("/docx-to-markdown")
+async def api_docx_to_markdown(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded DOCX
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved DOCX:", input_path)
+
+ if not input_path.lower().endswith(".docx"):
+ raise HTTPException(status_code=400, detail="Invalid DOCX file.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_filename = f"{uid}.md"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert using Pandoc
+ def _convert():
+ cmd = [
+ "pandoc",
+ input_path,
+ "-f", "docx",
+ "-t", "markdown",
+ "-o", output_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="DOCX to Markdown conversion failed.")
+
+ # 3️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("📝 DOCX → Markdown output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="Pandoc conversion failed.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input DOCX
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- DOCX → ODT ----------------
+@router.post("/docx-to-odt")
+async def api_docx_to_odt(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded DOCX
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved DOCX:", input_path)
+
+ if not input_path.lower().endswith(".docx"):
+ raise HTTPException(status_code=400, detail="Invalid DOCX file.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # 2️⃣ Convert using LibreOffice
+ def _convert():
+ cmd = [
+ "soffice",
+ "--headless",
+ "--convert-to", "odt",
+ "--outdir", TMP_DIR,
+ input_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ # LibreOffice auto-generates output filename
+ base_name = os.path.splitext(os.path.basename(input_path))[0]
+ converted_name = base_name + ".odt"
+ output_path = os.path.join(TMP_DIR, converted_name)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="DOCX to ODT conversion failed.")
+
+ # 3️⃣ Rename to unique filename
+ final_filename = f"{uid}.odt"
+ final_path = os.path.join(OUTPUT_DIR, final_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{final_filename}"
+
+ print("📄 DOCX → ODT output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="LibreOffice conversion failed.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- DOCX → RTF ----------------
+@router.post("/docx-to-rtf")
+async def api_docx_to_rtf(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded DOCX
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved DOCX:", input_path)
+
+ if not input_path.lower().endswith(".docx"):
+ raise HTTPException(status_code=400, detail="Invalid DOCX file.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # 2️⃣ Convert using LibreOffice (more stable than pandoc for RTF)
+ def _convert():
+ cmd = [
+ "soffice",
+ "--headless",
+ "--convert-to", "rtf",
+ "--outdir", TMP_DIR,
+ input_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ # LibreOffice auto-generates filename
+ base_name = os.path.splitext(os.path.basename(input_path))[0]
+ converted_name = base_name + ".rtf"
+ output_path = os.path.join(TMP_DIR, converted_name)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="DOCX to RTF conversion failed.")
+
+ # 3️⃣ Rename to unique filename
+ final_filename = f"{uid}.rtf"
+ final_path = os.path.join(OUTPUT_DIR, final_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL (localhost + production safe)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{final_filename}"
+
+ print("📄 DOCX → RTF output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="LibreOffice conversion failed.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- DOCX → TXT ----------------
+@router.post("/docx-to-txt")
+async def api_docx_to_txt(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded DOCX
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved DOCX:", input_path)
+
+ if not input_path.lower().endswith(".docx"):
+ raise HTTPException(status_code=400, detail="Invalid DOCX file.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # 2️⃣ Convert using LibreOffice
+ def _convert():
+ cmd = [
+ "soffice",
+ "--headless",
+ "--convert-to", "txt:Text",
+ "--outdir", TMP_DIR,
+ input_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ # LibreOffice auto-generates filename
+ base_name = os.path.splitext(os.path.basename(input_path))[0]
+ converted_name = base_name + ".txt"
+ output_path = os.path.join(TMP_DIR, converted_name)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="DOCX to TXT conversion failed.")
+
+ # 3️⃣ Rename to unique filename
+ final_filename = f"{uid}.txt"
+ final_path = os.path.join(OUTPUT_DIR, final_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL (localhost + production safe)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{final_filename}"
+
+ print("📄 DOCX → TXT output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="LibreOffice conversion failed.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- EPUB → DOCX ----------------
+@router.post("/epub-to-docx")
+async def api_epub_to_docx(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ import os
+ import uuid
+ import subprocess
+ import traceback
+
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded EPUB
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved EPUB:", input_path)
+
+ if not input_path.lower().endswith(".epub"):
+ raise HTTPException(status_code=400, detail="Invalid EPUB file.")
+
+ uid = str(uuid.uuid4())
+
+ TMP_DIR = "temp" # keep consistent with your system
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # ✅ Absolute paths (important)
+ input_path = os.path.abspath(input_path)
+ output_path = os.path.abspath(os.path.join(TMP_DIR, f"{uid}.docx"))
+
+ print("DEBUG input:", input_path)
+ print("DEBUG output:", output_path)
+
+ # 2️⃣ Convert using Pandoc (BEST)
+ def _convert():
+ subprocess.run([
+ "pandoc",
+ input_path,
+ "-o",
+ output_path
+ ], check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="EPUB to DOCX conversion failed.")
+
+ # 3️⃣ Move to final output
+ final_filename = f"{uid}.docx"
+ final_path = os.path.join(OUTPUT_DIR, final_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{final_filename}"
+
+ print("📘 EPUB → DOCX output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError as e:
+ print("❌ Pandoc error:", e)
+ raise HTTPException(status_code=500, detail="Pandoc conversion failed.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # Cleanup
+ if input_path and os.path.exists(input_path):
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- EPUB → PDF ----------------
+@router.post("/epub-to-pdf")
+async def api_epub_to_pdf(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ import os
+ import uuid
+ import subprocess
+ import traceback
+
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save EPUB
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved EPUB:", input_path)
+
+ if not input_path.lower().endswith(".epub"):
+ raise HTTPException(status_code=400, detail="Invalid EPUB file.")
+
+ uid = str(uuid.uuid4())
+
+ TMP_DIR = "temp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # ✅ Absolute paths
+ input_path = os.path.abspath(input_path)
+ output_path = os.path.abspath(os.path.join(TMP_DIR, f"{uid}.pdf"))
+
+ print("DEBUG input:", input_path)
+ print("DEBUG output:", output_path)
+
+ # 2️⃣ Convert using Pandoc
+ def _convert():
+ subprocess.run([
+ "pandoc",
+ input_path,
+ "-o",
+ output_path
+ ], check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="EPUB to PDF conversion failed.")
+
+ # 3️⃣ Move to output
+ final_filename = f"{uid}.pdf"
+ final_path = os.path.join(OUTPUT_DIR, final_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{final_filename}"
+
+ print("📘 EPUB → PDF output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError as e:
+ print("❌ Pandoc error:", e)
+ raise HTTPException(status_code=500, detail="Pandoc conversion failed.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- EXCEL → PDF ----------------
+@router.post("/excel-to-pdf")
+async def api_excel_to_pdf(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded Excel file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved Excel:", input_path)
+
+ if not input_path.lower().endswith((".xls", ".xlsx")):
+ raise HTTPException(status_code=400, detail="Invalid Excel file.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # 2️⃣ Convert using LibreOffice
+ def _convert():
+ cmd = [
+ "soffice",
+ "--headless",
+ "--convert-to", "pdf",
+ "--outdir", TMP_DIR,
+ input_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ # LibreOffice auto-generates filename
+ base_name = os.path.splitext(os.path.basename(input_path))[0]
+ converted_name = base_name + ".pdf"
+ output_path = os.path.join(TMP_DIR, converted_name)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="Excel to PDF conversion failed.")
+
+ # 3️⃣ Rename to unique filename
+ final_filename = f"{uid}.pdf"
+ final_path = os.path.join(OUTPUT_DIR, final_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL (works localhost + production)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{final_filename}"
+
+ print("📊 Excel → PDF output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="LibreOffice conversion failed.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- FLAC → MP3 ----------------
+@router.post("/flac-to-mp3")
+async def api_flac_to_mp3(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded FLAC
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved FLAC:", input_path)
+
+ if not input_path.lower().endswith(".flac"):
+ raise HTTPException(status_code=400, detail="Invalid FLAC file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.mp3"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert using FFmpeg
+ def _convert():
+ cmd = [
+ "ffmpeg",
+ "-y",
+ "-loglevel", "error",
+ "-i", input_path,
+ "-map", "0:a:0",
+ "-vn",
+ "-acodec", "libmp3lame",
+ "-b:a", "192k",
+ output_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "FLAC to MP3 conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("🎵 FLAC → MP3 output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="FFmpeg conversion failed.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- FLATTEN PDF ----------------
+@router.post("/flatten-pdf")
+async def api_flatten_pdf(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded PDF
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PDF for flattening:", input_path)
+
+ if not input_path.lower().endswith(".pdf"):
+ raise HTTPException(status_code=400, detail="Invalid PDF file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.pdf"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Flatten PDF
+ def _flatten():
+ doc = fitz.open(input_path)
+
+ for page in doc:
+ # Flatten annotations (forms, comments, etc.)
+ annot = page.first_annot
+ while annot:
+ annot.set_flags(fitz.PDF_ANNOT_IS_PRINT)
+ annot.update()
+ annot = annot.next
+
+ # Remove form fields completely
+ if doc.is_form_pdf:
+ doc.delete_pages(range(0)) # force rebuild
+ doc = fitz.open(input_path)
+
+ # Save flattened version
+ doc.save(output_path, garbage=4, deflate=True)
+ doc.close()
+
+ await run_in_threadpool(_flatten)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="PDF flattening failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📄 Flattened PDF:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- GIF → JPG (MULTI FRAME → ZIP) ----------------
+@router.post("/gif-to-jpg")
+async def api_gif_to_jpg(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ frame_paths = []
+ zip_path = None
+
+ try:
+ # 1️⃣ Save uploaded GIF
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved GIF:", input_path)
+
+ if not input_path.lower().endswith(".gif"):
+ raise HTTPException(status_code=400, detail="Invalid GIF file.")
+
+ uid = str(uuid.uuid4())
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # 2️⃣ Extract frames and convert to JPG
+ def _extract_frames():
+ with Image.open(input_path) as img:
+ frame_count = getattr(img, "n_frames", 1)
+
+ for i in range(frame_count):
+ img.seek(i)
+ frame = img.convert("RGB")
+
+ frame_filename = f"{uid}_frame_{i+1}.jpg"
+ frame_path = os.path.join(TMP_DIR, frame_filename)
+
+ frame.save(frame_path, "JPEG", quality=95)
+ frame_paths.append(frame_path)
+
+ await run_in_threadpool(_extract_frames)
+
+ if not frame_paths:
+ raise HTTPException(status_code=500, detail="GIF frame extraction failed.")
+
+ # 3️⃣ Create ZIP of JPG frames
+ zip_filename = f"{uid}.zip"
+ zip_path = os.path.join(TMP_DIR, zip_filename)
+
+ def _zip_frames():
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
+ for path in frame_paths:
+ zipf.write(path, os.path.basename(path))
+
+ await run_in_threadpool(_zip_frames)
+
+ if not os.path.exists(zip_path):
+ raise HTTPException(status_code=500, detail="ZIP creation failed.")
+
+ # 4️⃣ Move ZIP to static/output
+ final_path = os.path.join(OUTPUT_DIR, zip_filename)
+ os.replace(zip_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 5️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{zip_filename}"
+
+ print("🖼️ GIF → JPG ZIP:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size,
+ "frames": len(frame_paths)
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+ # Cleanup frame temp files
+ for path in frame_paths:
+ try:
+ await run_in_threadpool(os.remove, path)
+ except:
+ pass
+
+# ---------------- GIF → MP4 ----------------
+@router.post("/gif-to-mp4")
+async def api_gif_to_mp4(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded GIF
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved GIF:", input_path)
+
+ if not input_path.lower().endswith(".gif"):
+ raise HTTPException(status_code=400, detail="Invalid GIF file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.mp4"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert GIF → MP4 using ffmpeg
+ def _convert():
+ cmd = [
+ "ffmpeg",
+ "-y",
+ "-loglevel", "error",
+ "-i", input_path,
+ "-movflags", "+faststart",
+ "-pix_fmt", "yuv420p",
+ "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2",
+ "-c:v", "libx264",
+ "-profile:v", "baseline",
+ "-level", "3.0",
+ output_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "GIF to MP4 conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL (localhost + production safe)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("🎬 GIF → MP4 output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="FFmpeg conversion failed.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- HEIC → JPG ----------------
+@router.post("/heic-to-jpg")
+async def api_heic_to_jpg(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded HEIC
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved HEIC:", input_path)
+
+ if not input_path.lower().endswith(".heic"):
+ raise HTTPException(status_code=400, detail="Invalid HEIC file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.jpg"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert HEIC → JPG
+ def _convert():
+ with Image.open(input_path) as img:
+ rgb = img.convert("RGB") # JPG requires RGB
+ rgb.save(output_path, "JPEG", quality=95)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "HEIC to JPG conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("🖼 HEIC → JPG output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- HEX → BINARY ----------------
+@router.post("/hex-to-binary")
+async def api_hex_to_binary(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved HEX file:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.txt"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert HEX → Binary safely
+ def _convert():
+ with open(input_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Remove whitespace/newlines
+ cleaned = "".join(content.split())
+
+ if not cleaned:
+ raise ValueError("File is empty.")
+
+ # Validate HEX characters
+ if not all(c in "0123456789abcdefABCDEF" for c in cleaned):
+ raise ValueError("File contains non-hexadecimal characters.")
+
+ # If odd length, pad safely
+ if len(cleaned) % 2 != 0:
+ cleaned = "0" + cleaned
+
+ binary_chunks = []
+ for i in range(0, len(cleaned), 2):
+ byte = cleaned[i:i+2]
+ binary_chunks.append(format(int(byte, 16), "08b"))
+
+ binary_result = "".join(binary_chunks)
+
+ with open(output_path, "w", encoding="utf-8") as out:
+ out.write(binary_result)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "Hex to Binary conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 HEX → Binary output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except ValueError as ve:
+ raise HTTPException(status_code=400, detail=str(ve))
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- HTML TABLE → CSV ----------------
+from bs4 import BeautifulSoup
+import csv
+
+@router.post("/html-table-to-csv")
+async def api_html_table_to_csv(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded HTML
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved HTML:", input_path)
+
+ if not input_path.lower().endswith((".html", ".htm")):
+ raise HTTPException(status_code=400, detail="Invalid HTML file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.csv"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Extract first HTML table → CSV
+ def _convert():
+ with open(input_path, "r", encoding="utf-8") as f:
+ soup = BeautifulSoup(f, "html.parser")
+
+ table = soup.find("table")
+ if not table:
+ raise ValueError("No found in HTML.")
+
+ rows = table.find_all("tr")
+
+ with open(output_path, "w", newline="", encoding="utf-8") as csvfile:
+ writer = csv.writer(csvfile)
+
+ for row in rows:
+ cols = row.find_all(["td", "th"])
+ writer.writerow([col.get_text(strip=True) for col in cols])
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="HTML to CSV conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 HTML → CSV output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except ValueError as ve:
+ raise HTTPException(status_code=400, detail=str(ve))
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- HTML → DOCX ----------------
+# ---------------- HTML → DOCX (PANDOC) ----------------
+@router.post("/html-to-docx")
+async def api_html_to_docx(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate file type
+ if not file.filename.lower().endswith((".html", ".htm")):
+ raise HTTPException(status_code=400, detail="Invalid HTML file.")
+
+ # 2️⃣ Save uploaded file (your existing utility)
+ input_path = await run_in_threadpool(save_upload_file, file)
+ input_path = os.path.abspath(input_path)
+ print("📥 Saved HTML:", input_path)
+
+ # 3️⃣ Prepare temp output
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.docx"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 4️⃣ Convert using Pandoc
+ def _convert():
+ cmd = [
+ "pandoc",
+ input_path,
+ "-o",
+ output_path
+ ]
+ subprocess.run(cmd, check=True, timeout=60)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="HTML to DOCX conversion failed.")
+
+ # 5️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 6️⃣ Build dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("📄 HTML → DOCX output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # Cleanup input file
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- HTML → PDF ----------------
+@router.post("/html-to-pdf")
+async def api_html_to_pdf(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded HTML
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved HTML:", input_path)
+
+ if not input_path.lower().endswith((".html", ".htm")):
+ raise HTTPException(status_code=400, detail="Invalid HTML file.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # 2️⃣ Convert using LibreOffice
+ def _convert():
+ cmd = [
+ "soffice",
+ "--headless",
+ "--convert-to", "pdf",
+ "--outdir", TMP_DIR,
+ input_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ # LibreOffice auto-names file
+ base_name = os.path.splitext(os.path.basename(input_path))[0]
+ converted_name = base_name + ".pdf"
+ output_path = os.path.join(TMP_DIR, converted_name)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="HTML to PDF conversion failed.")
+
+ # 3️⃣ Rename to unique filename
+ final_filename = f"{uid}.pdf"
+ final_path = os.path.join(OUTPUT_DIR, final_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL (localhost + production safe)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{final_filename}"
+
+ print("📄 HTML → PDF output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="LibreOffice conversion failed.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- HTML → PPT ----------------
+from pptx import Presentation
+from bs4 import BeautifulSoup
+from pptx.util import Inches
+
+def html_to_pptx(input_path, output_path):
+ prs = Presentation()
+
+ with open(input_path, "r", encoding="utf-8") as f:
+ soup = BeautifulSoup(f, "html.parser")
+
+ # Find sections (headings = slides)
+ sections = soup.find_all(["h1", "h2"])
+
+ # fallback if no headings
+ if not sections:
+ sections = [soup]
+
+ for section in sections:
+ slide_layout = prs.slide_layouts[1]
+ slide = prs.slides.add_slide(slide_layout)
+
+ # 🟢 Title
+ title_text = section.get_text(strip=True) if section.name in ["h1", "h2"] else "Slide"
+ slide.shapes.title.text = title_text
+
+ # 🟢 Content collector
+ content = []
+
+ # collect siblings until next heading
+ if section.name in ["h1", "h2"]:
+ siblings = section.find_next_siblings()
+ else:
+ siblings = section.find_all(["p", "li"])
+
+ for sib in siblings:
+ if sib.name in ["h1", "h2"]:
+ break
+
+ text = sib.get_text(strip=True)
+ if text:
+ content.append(text)
+
+ # limit text (avoid overflow)
+ content_text = "\n".join(content[:10])
+ slide.placeholders[1].text = content_text
+
+ prs.save(output_path)
+
+@router.post("/html-to-ppt")
+async def api_html_to_ppt(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ import os
+ import uuid
+ import traceback
+
+ input_path = None
+
+ try:
+ # 1️⃣ Save file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved HTML:", input_path)
+
+ if not input_path.lower().endswith((".html", ".htm")):
+ raise HTTPException(status_code=400, detail="Invalid HTML file.")
+
+ uid = str(uuid.uuid4())
+
+ TMP_DIR = "temp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ input_path = os.path.abspath(input_path)
+
+ # 2️⃣ Output path
+ output_path = os.path.join(TMP_DIR, f"{uid}.pptx")
+
+ # 3️⃣ Convert using python-pptx
+ await run_in_threadpool(
+ html_to_pptx,
+ input_path,
+ output_path
+ )
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="Conversion failed.")
+
+ # 4️⃣ Move to final output
+ final_filename = f"{uid}.pptx"
+ final_path = os.path.join(OUTPUT_DIR, final_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 5️⃣ URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{final_filename}"
+
+ print("✅ PPTX created:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+# ---------------- HTML → XLSX ----------------
+# ---------------- HTML → XLSX (PANDAS VERSION) ----------------
+from bs4 import BeautifulSoup
+import pandas as pd
+from openpyxl import Workbook
+
+@router.post("/html-to-xlsx")
+async def api_html_to_xlsx(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate extension
+ if not file.filename.lower().endswith((".html", ".htm")):
+ raise HTTPException(status_code=400, detail="Invalid HTML file.")
+
+ # 2️⃣ Save file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ input_path = os.path.abspath(input_path)
+
+ print("📥 Saved HTML:", input_path)
+
+ # 3️⃣ Prepare output
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.xlsx"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 4️⃣ Convert
+ def _convert():
+ import pandas as pd
+
+ try:
+ dfs = pd.read_html(input_path, flavor="lxml")
+ except ValueError:
+ raise HTTPException(
+ status_code=400,
+ detail="No readable HTML tables found in file."
+ )
+
+ if not dfs:
+ raise HTTPException(
+ status_code=400,
+ detail="No elements detected in uploaded HTML."
+ )
+
+ with pd.ExcelWriter(output_path, engine="openpyxl") as writer:
+ for i, df in enumerate(dfs):
+ df.to_excel(writer, sheet_name=f"Table_{i+1}", index=False)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="HTML to XLSX conversion failed.")
+
+ # 5️⃣ Move to output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("📊 HTML → XLSX output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except HTTPException:
+ raise
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+# ---------------- ICO → PNG ----------------
+@router.post("/ico-to-png")
+async def api_ico_to_png(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded ICO
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved ICO:", input_path)
+
+ if not input_path.lower().endswith(".ico"):
+ raise HTTPException(status_code=400, detail="Invalid ICO file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.png"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert ICO → PNG
+ def _convert():
+ with Image.open(input_path) as img:
+ # ICO may contain multiple sizes → use largest
+ try:
+ img = img.convert("RGBA")
+ except:
+ pass
+ img.save(output_path, "PNG")
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="ICO to PNG conversion failed.")
+
+ # 3️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("🖼️ ICO → PNG output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- IMAGE → AVIF ----------------
+@router.post("/image-to-avif")
+async def api_image_to_avif(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded image
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved Image:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.avif"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert Image → AVIF
+ def _convert():
+ with Image.open(input_path) as img:
+ # Convert to RGBA to preserve transparency
+ if img.mode not in ("RGB", "RGBA"):
+ img = img.convert("RGBA")
+
+ img.save(
+ output_path,
+ "AVIF",
+ quality=80, # You can tweak (0–100)
+ speed=6 # 0 = best compression, 10 = fastest
+ )
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "Image to AVIF conversion failed.")
+
+ # 3️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL (localhost + production safe)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("🖼️ Image → AVIF output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- IMAGE → BMP ----------------
+@router.post("/image-to-bmp")
+async def api_image_to_bmp(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved Image:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.bmp"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert Image → BMP
+ def _convert():
+ with Image.open(input_path) as img:
+ # BMP does not support transparency properly
+ if img.mode in ("RGBA", "LA"):
+ img = img.convert("RGB")
+ elif img.mode != "RGB":
+ img = img.convert("RGB")
+
+ img.save(output_path, "BMP")
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "Image to BMP conversion failed.")
+
+ # 3️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Generate public URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("🖼️ Image → BMP output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- IMAGE → ICO ----------------
+@router.post("/image-to-ico")
+async def api_image_to_ico(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded image
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved Image:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.ico"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert image → ICO (multi-size favicon)
+ def _convert():
+ with Image.open(input_path) as img:
+ img = img.convert("RGBA")
+
+ # Resize to multiple favicon sizes
+ sizes = [
+ (16, 16),
+ (32, 32),
+ (48, 48),
+ (64, 64),
+ (128, 128),
+ (256, 256),
+ ]
+
+ img.save(output_path, format="ICO", sizes=sizes)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "Image to ICO conversion failed.")
+
+ # 3️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Public URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("🟡 Image → ICO output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- IMAGE → PDF ----------------
+from reportlab.platypus import SimpleDocTemplate, Image as RLImage, Spacer
+from reportlab.lib.pagesizes import A4
+from reportlab.lib.units import inch
+from reportlab.lib import utils
+
+@router.post("/image-to-pdf")
+async def api_image_to_pdf(
+ request: Request,
+ files: List[UploadFile] = File(...),
+ db: Session = Depends(get_db)
+):
+ input_paths = []
+ output_path = None
+
+ try:
+ if not files:
+ raise HTTPException(status_code=400, detail="No images uploaded.")
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ OUTPUT_DIR = "static/output"
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # 1️⃣ Save uploaded images
+ for f in files:
+ path = await run_in_threadpool(save_upload_file, f)
+ input_paths.append(path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.pdf"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Build PDF
+ def _build_pdf():
+ doc = SimpleDocTemplate(output_path, pagesize=A4)
+ elements = []
+
+ page_width, page_height = A4
+
+ for img_path in input_paths:
+ img = utils.ImageReader(img_path)
+ img_width, img_height = img.getSize()
+
+ # Fit image to A4 while preserving aspect ratio
+ ratio = min(page_width / img_width, page_height / img_height)
+ new_width = img_width * ratio
+ new_height = img_height * ratio
+
+ elements.append(RLImage(img_path, width=new_width, height=new_height))
+ elements.append(Spacer(1, 0.5 * inch))
+
+ doc.build(elements)
+
+ await run_in_threadpool(_build_pdf)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "PDF generation failed.")
+
+ # 3️⃣ Move to static folder
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # cleanup uploaded temp images
+ for path in input_paths:
+ try:
+ await run_in_threadpool(os.remove, path)
+ except:
+ pass
+
+# ---------------- JPG → GIF ----------------
+from PIL import Image
+
+@router.post("/jpg-to-gif")
+async def api_jpg_to_gif(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ if not file.filename.lower().endswith((".jpg", ".jpeg")):
+ raise HTTPException(status_code=400, detail="Invalid JPG file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # 1️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.gif"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert JPG → GIF
+ def _convert():
+ with Image.open(input_path) as img:
+ rgb_img = img.convert("RGB")
+ rgb_img.save(output_path, format="GIF")
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="Conversion failed.")
+
+ # 3️⃣ Move to static folder
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- JPG → HEIC ----------------
+from PIL import Image
+import pillow_heif
+
+pillow_heif.register_heif_opener()
+
+@router.post("/jpg-to-heic")
+async def api_jpg_to_heic(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ if not file.filename.lower().endswith((".jpg", ".jpeg")):
+ raise HTTPException(status_code=400, detail="Invalid JPG file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.heic"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # Convert JPG → HEIC
+ def _convert():
+ with Image.open(input_path) as img:
+ img = img.convert("RGB")
+ img.save(output_path, format="HEIC", quality=90)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="Conversion failed.")
+
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- JPG → PDF ----------------
+from PIL import Image
+from fastapi import UploadFile, File
+from typing import List
+
+@router.post("/jpg-to-pdf")
+async def api_jpg_to_pdf(
+ request: Request,
+ files: List[UploadFile] = File(...),
+ db: Session = Depends(get_db)
+):
+ input_paths = []
+ output_path = None
+
+ try:
+ if not files:
+ raise HTTPException(status_code=400, detail="No JPG files uploaded.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # Save all uploaded images
+ for file in files:
+ if not file.filename.lower().endswith((".jpg", ".jpeg")):
+ raise HTTPException(status_code=400, detail="Invalid JPG file detected.")
+
+ path = await run_in_threadpool(save_upload_file, file)
+ input_paths.append(path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.pdf"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # Convert & merge images to PDF
+ def _convert():
+ images = []
+ for path in input_paths:
+ img = Image.open(path).convert("RGB")
+ images.append(img)
+
+ if not images:
+ raise Exception("No images to convert.")
+
+ images[0].save(
+ output_path,
+ save_all=True,
+ append_images=images[1:]
+ )
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="PDF generation failed.")
+
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # Clean up input temp files
+ for path in input_paths:
+ if os.path.exists(path):
+ try:
+ await run_in_threadpool(os.remove, path)
+ except:
+ pass
+
+# ---------------- JPG → PNG ----------------
+from PIL import Image
+
+@router.post("/jpg-to-png")
+async def api_jpg_to_png(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ if not file.filename.lower().endswith((".jpg", ".jpeg")):
+ raise HTTPException(status_code=400, detail="Invalid JPG file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.png"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # Convert JPG → PNG
+ def _convert():
+ img = Image.open(input_path)
+ img = img.convert("RGBA") # ensures transparency support
+ img.save(output_path, "PNG")
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="Conversion failed.")
+
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- JPG → WEBP ----------------
+from PIL import Image
+
+@router.post("/jpg-to-webp")
+async def api_jpg_to_webp(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ if not file.filename.lower().endswith((".jpg", ".jpeg")):
+ raise HTTPException(status_code=400, detail="Invalid JPG file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # Save upload
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.webp"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # Convert
+ def _convert():
+ img = Image.open(input_path)
+ img = img.convert("RGB")
+ img.save(output_path, "WEBP", quality=85, method=6)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="Conversion failed.")
+
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- JSON → XLSX ----------------
+import json
+from openpyxl import Workbook
+
+@router.post("/json-to-xlsx")
+async def api_json_to_xlsx(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ print(f"📥 Received file: {file.filename} | content_type: {file.content_type}")
+
+ if not file.filename.lower().endswith(".json"):
+ print("❌ Failed extension check")
+ raise HTTPException(status_code=400, detail="Invalid JSON file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ input_path = await run_in_threadpool(save_upload_file, file)
+ saved_size = os.path.getsize(input_path)
+ print(f"💾 Saved to: {input_path} | size: {saved_size} bytes")
+
+ # Preview first 200 chars of file
+ with open(input_path, "r", encoding="utf-8", errors="replace") as f:
+ preview = f.read(200)
+ print(f"🔍 File preview: {repr(preview)}")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.xlsx"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ def _convert():
+ with open(input_path, "r", encoding="utf-8") as f:
+ raw = f.read().strip()
+
+ print(f"📄 Raw JSON length: {len(raw)} | starts with: {repr(raw[:50])}")
+
+ # Handle JSONL
+ if raw.startswith("{") and "\n" in raw:
+ try:
+ data = [json.loads(line) for line in raw.splitlines() if line.strip()]
+ print(f"📋 Parsed as JSONL: {len(data)} lines")
+ except json.JSONDecodeError:
+ data = json.loads(raw)
+ print("📋 Parsed as single JSON object")
+ else:
+ data = json.loads(raw)
+ print(f"📋 Parsed JSON type: {type(data).__name__} | len: {len(data) if isinstance(data, (list, dict)) else 'N/A'}")
+
+ # Normalize to rows
+ if isinstance(data, list):
+ if len(data) == 0:
+ raise ValueError("JSON array is empty.")
+ if isinstance(data[0], dict):
+ headers = list(dict.fromkeys(k for item in data for k in (item.keys() if isinstance(item, dict) else [])))
+ rows = [[item.get(h, "") if isinstance(item, dict) else "" for h in headers] for item in data]
+ else:
+ headers = ["value"]
+ rows = [[item] for item in data]
+ elif isinstance(data, dict):
+ headers = list(data.keys())
+ rows = [list(data.values())]
+ else:
+ headers = ["value"]
+ rows = [[data]]
+
+ print(f"📊 Headers ({len(headers)}): {headers[:5]}")
+ print(f"📊 Row count: {len(rows)}")
+
+ wb = Workbook()
+ ws = wb.active
+ ws.title = "Sheet1"
+ ws.append(headers)
+ for row in rows:
+ ws.append(row)
+ wb.save(output_path)
+ print(f"✅ Saved XLSX: {output_path}")
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="Conversion failed.")
+
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print(f"✅ Done: {file_url} | {size} bytes")
+ return JSONResponse({"url": file_url, "size": size})
+
+ except json.JSONDecodeError as je:
+ print(f"❌ JSON decode error: {je}")
+ raise HTTPException(status_code=400, detail=f"Invalid JSON format: {str(je)}")
+
+ except ValueError as ve:
+ print(f"❌ ValueError: {ve}")
+ raise HTTPException(status_code=400, detail=str(ve))
+
+ except Exception as e:
+ print(f"❌ Exception: {e}")
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+# ---------------- JSON → YAML ----------------
+import json
+import yaml
+
+@router.post("/json-to-yaml")
+async def api_json_to_yaml(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ if not file.filename.lower().endswith(".json"):
+ raise HTTPException(status_code=400, detail="Invalid JSON file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.yaml"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ def _convert():
+ with open(input_path, "r", encoding="utf-8") as f:
+ data = json.load(f)
+
+ with open(output_path, "w", encoding="utf-8") as f:
+ yaml.safe_dump(
+ data,
+ f,
+ sort_keys=False,
+ allow_unicode=True,
+ default_flow_style=False
+ )
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="Conversion failed.")
+
+ # Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except json.JSONDecodeError:
+ raise HTTPException(status_code=400, detail="Invalid JSON format.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- LaTeX → PDF ----------------
+import subprocess
+
+@router.post("/latex-to-pdf")
+async def api_latex_to_pdf(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ work_dir = None
+
+ try:
+ if not file.filename.lower().endswith(".tex"):
+ raise HTTPException(status_code=400, detail="Invalid LaTeX file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ uid = str(uuid.uuid4())
+ work_dir = os.path.join(TMP_DIR, uid)
+ os.makedirs(work_dir, exist_ok=True)
+
+ tex_filename = "document.tex"
+ tex_path = os.path.join(work_dir, tex_filename)
+
+ os.replace(input_path, tex_path)
+
+ # Compile using pdflatex
+ def _compile():
+ subprocess.run(
+ [
+ "pdflatex",
+ "-interaction=nonstopmode",
+ tex_filename
+ ],
+ cwd=work_dir,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ timeout=60
+ )
+
+ await run_in_threadpool(_compile)
+
+ pdf_path = os.path.join(work_dir, "document.pdf")
+
+ if not os.path.exists(pdf_path):
+ raise HTTPException(status_code=400, detail="LaTeX compilation failed.")
+
+ # Move final PDF
+ output_filename = f"{uid}.pdf"
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(pdf_path, final_path)
+
+ size = os.path.getsize(final_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.TimeoutExpired:
+ raise HTTPException(status_code=408, detail="Compilation timed out.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # Cleanup working directory
+ if work_dir and os.path.exists(work_dir):
+ try:
+ shutil.rmtree(work_dir)
+ except:
+ pass
+
+# ---------------- Markdown → DOCX ----------------
+import subprocess
+
+@router.post("/markdown-to-docx")
+async def api_markdown_to_docx(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ if not file.filename.lower().endswith((".md", ".markdown")):
+ raise HTTPException(status_code=400, detail="Invalid Markdown file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # Save upload
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.docx"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ # Convert using pandoc
+ result = subprocess.run(
+ ["pandoc", input_path, "-o", output_path],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True
+ )
+
+ if result.returncode != 0:
+ raise HTTPException(
+ status_code=400,
+ detail="Markdown conversion failed."
+ )
+
+ size = os.path.getsize(output_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- Markdown → HTML ----------------
+import subprocess
+
+@router.post("/markdown-to-html")
+async def api_markdown_to_html(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ if not file.filename.lower().endswith((".md", ".markdown")):
+ raise HTTPException(status_code=400, detail="Invalid Markdown file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.html"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ # Convert using pandoc
+ result = subprocess.run(
+ [
+ "pandoc",
+ "--sandbox",
+ input_path,
+ "-f", "markdown",
+ "-t", "html",
+ "-s", # standalone HTML
+ "-o", output_path
+ ],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True
+ )
+
+ if result.returncode != 0:
+ raise HTTPException(
+ status_code=400,
+ detail="Markdown to HTML conversion failed."
+ )
+
+ size = os.path.getsize(output_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- MKV → MP4 ----------------
+import subprocess
+
+@router.post("/mkv-to-mp4")
+async def api_mkv_to_mp4(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ if not file.filename.lower().endswith(".mkv"):
+ raise HTTPException(status_code=400, detail="Invalid MKV file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ # Optional size limit (VERY important for video)
+ if os.path.getsize(input_path) > 500 * 1024 * 1024: # 500MB
+ raise HTTPException(status_code=413, detail="File too large.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.mp4"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ # Convert using ffmpeg
+ result = subprocess.run(
+ [
+ "ffmpeg",
+ "-y",
+ "-i", input_path,
+ "-c:v", "libx264",
+ "-preset", "fast",
+ "-crf", "23",
+ "-c:a", "aac",
+ "-movflags", "+faststart",
+ output_path
+ ],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True
+ )
+
+ if result.returncode != 0:
+ raise HTTPException(
+ status_code=400,
+ detail="MKV to MP4 conversion failed."
+ )
+
+ size = os.path.getsize(output_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- MOV → MP4 ----------------
+import subprocess
+
+@router.post("/mov-to-mp4")
+async def api_mov_to_mp4(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ if not file.filename.lower().endswith(".mov"):
+ raise HTTPException(status_code=400, detail="Invalid MOV file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # Save file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ # Size limit (IMPORTANT for video)
+ if os.path.getsize(input_path) > 500 * 1024 * 1024: # 500MB
+ raise HTTPException(status_code=413, detail="File too large.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.mp4"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ # Smart conversion (fast when possible)
+ convert_cmd = [
+ "ffmpeg",
+ "-y",
+ "-i", input_path,
+ "-c:v", "libx264",
+ "-preset", "fast",
+ "-crf", "23",
+ "-c:a", "aac",
+ "-movflags", "+faststart",
+ output_path
+ ]
+
+ result = subprocess.run(
+ convert_cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True
+ )
+
+ if result.returncode != 0:
+ raise HTTPException(
+ status_code=400,
+ detail="MOV to MP4 conversion failed."
+ )
+
+ size = os.path.getsize(output_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- MP3 → AAC ----------------
+
+
+@router.post("/mp3-to-aac")
+async def api_mp3_to_aac(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ if not file.filename.lower().endswith(".mp3"):
+ raise HTTPException(status_code=400, detail="Invalid MP3 file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ # Optional size limit (example: 200MB)
+ if os.path.getsize(input_path) > 200 * 1024 * 1024:
+ raise HTTPException(status_code=413, detail="File too large.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.aac"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ # Convert using FFmpeg
+ convert_cmd = [
+ "ffmpeg",
+ "-y",
+ "-i", input_path,
+ "-c:a", "aac",
+ "-b:a", "192k",
+ output_path
+ ]
+
+ result = subprocess.run(
+ convert_cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True
+ )
+
+ if result.returncode != 0:
+ raise HTTPException(status_code=400, detail="MP3 to AAC conversion failed.")
+
+ size = os.path.getsize(output_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- MP3 → FLAC ----------------
+
+
+@router.post("/mp3-to-flac")
+async def api_mp3_to_flac(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ if not file.filename.lower().endswith(".mp3"):
+ raise HTTPException(status_code=400, detail="Invalid MP3 file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ # Optional file size limit (200MB)
+ if os.path.getsize(input_path) > 200 * 1024 * 1024:
+ raise HTTPException(status_code=413, detail="File too large.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.flac"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ # Convert using FFmpeg
+ convert_cmd = [
+ "ffmpeg",
+ "-y",
+ "-i", input_path,
+ "-c:a", "flac",
+ output_path
+ ]
+
+ result = subprocess.run(
+ convert_cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True
+ )
+
+ if result.returncode != 0:
+ raise HTTPException(status_code=400, detail="MP3 to FLAC conversion failed.")
+
+ size = os.path.getsize(output_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- MP3 → WAV ----------------
+
+
+@router.post("/mp3-to-wav")
+async def api_mp3_to_wav(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ if not file.filename.lower().endswith(".mp3"):
+ raise HTTPException(status_code=400, detail="Invalid MP3 file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ # Optional file size limit (200MB)
+ if os.path.getsize(input_path) > 200 * 1024 * 1024:
+ raise HTTPException(status_code=413, detail="File too large.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.wav"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ # Convert using FFmpeg
+ convert_cmd = [
+ "ffmpeg",
+ "-y",
+ "-i", input_path,
+ "-acodec", "pcm_s16le", # standard WAV codec
+ "-ar", "44100", # sample rate
+ "-ac", "2", # stereo
+ output_path
+ ]
+
+ result = subprocess.run(
+ convert_cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True
+ )
+
+ if result.returncode != 0:
+ raise HTTPException(status_code=400, detail="MP3 to WAV conversion failed.")
+
+ size = os.path.getsize(output_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- MP4 → AVI ----------------
+
+@router.post("/mp4-to-avi")
+async def api_mp4_to_avi(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ if not file.filename.lower().endswith(".mp4"):
+ raise HTTPException(status_code=400, detail="Invalid MP4 file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ # Optional file size limit (500MB)
+ if os.path.getsize(input_path) > 500 * 1024 * 1024:
+ raise HTTPException(status_code=413, detail="File too large.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.avi"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ # Convert using FFmpeg
+ convert_cmd = [
+ "ffmpeg",
+ "-y",
+ "-i", input_path,
+ "-c:v", "mpeg4", # AVI compatible video codec
+ "-qscale:v", "3", # Good quality
+ "-c:a", "mp3", # Audio codec
+ output_path
+ ]
+
+ result = subprocess.run(
+ convert_cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True
+ )
+
+ if result.returncode != 0:
+ raise HTTPException(status_code=400, detail="MP4 to AVI conversion failed.")
+
+ size = os.path.getsize(output_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- MP4 → MOV ----------------
+@router.post("/mp4-to-mov")
+async def api_mp4_to_mov(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate extension
+ if not file.filename.lower().endswith(".mp4"):
+ raise HTTPException(status_code=400, detail="Invalid MP4 file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # 2️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ # 3️⃣ File size limit (IMPORTANT for video)
+ if os.path.getsize(input_path) > 500 * 1024 * 1024: # 500MB
+ raise HTTPException(status_code=413, detail="File too large.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.mov"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ # 4️⃣ Convert using FFmpeg
+ convert_cmd = [
+ "ffmpeg",
+ "-y",
+ "-i", input_path,
+ "-c:v", "libx264", # compatible video codec
+ "-preset", "fast",
+ "-crf", "23",
+ "-c:a", "aac",
+ "-movflags", "+faststart",
+ output_path
+ ]
+
+ result = subprocess.run(
+ convert_cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ timeout=300 # 5 min safety timeout
+ )
+
+ if result.returncode != 0:
+ raise HTTPException(status_code=400, detail="MP4 to MOV conversion failed.")
+
+ size = os.path.getsize(output_path)
+
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.TimeoutExpired:
+ raise HTTPException(status_code=408, detail="Conversion timed out.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- MP4 → WAV ----------------
+@router.post("/mp4-to-wav")
+async def api_mp4_to_wav(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate file
+ if not file.filename.lower().endswith(".mp4"):
+ raise HTTPException(status_code=400, detail="Invalid MP4 file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # 2️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ # 3️⃣ File size limit (important for videos)
+ if os.path.getsize(input_path) > 500 * 1024 * 1024: # 500MB
+ raise HTTPException(status_code=413, detail="File too large.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.wav"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ # 4️⃣ Extract audio using FFmpeg
+ convert_cmd = [
+ "ffmpeg",
+ "-y",
+ "-i", input_path,
+ "-vn", # no video
+ "-acodec", "pcm_s16le", # WAV format
+ "-ar", "44100", # sample rate
+ "-ac", "2", # stereo
+ output_path
+ ]
+
+ result = subprocess.run(
+ convert_cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ timeout=300 # 5 minutes safety
+ )
+
+ if result.returncode != 0:
+ raise HTTPException(status_code=400, detail="MP4 to WAV conversion failed.")
+
+ size = os.path.getsize(output_path)
+
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.TimeoutExpired:
+ raise HTTPException(status_code=408, detail="Conversion timed out.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- MP4 → WebM ----------------
+@router.post("/mp4-to-webm")
+async def api_mp4_to_webm(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate
+ if not file.filename.lower().endswith(".mp4"):
+ raise HTTPException(status_code=400, detail="Invalid MP4 file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # 2️⃣ Save upload
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ # 3️⃣ Size protection (500MB limit)
+ if os.path.getsize(input_path) > 500 * 1024 * 1024:
+ raise HTTPException(status_code=413, detail="File too large.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.webm"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ # 4️⃣ Convert using FFmpeg (VP9 + Opus)
+ convert_cmd = [
+ "ffmpeg",
+ "-y",
+ "-i", input_path,
+ "-c:v", "libvpx-vp9",
+ "-crf", "30", # quality (lower = better)
+ "-b:v", "0", # constant quality mode
+ "-c:a", "libopus",
+ output_path
+ ]
+
+ result = subprocess.run(
+ convert_cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ timeout=600 # 10 min max
+ )
+
+ if result.returncode != 0:
+ raise HTTPException(status_code=400, detail="MP4 to WebM conversion failed.")
+
+ size = os.path.getsize(output_path)
+
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.TimeoutExpired:
+ raise HTTPException(status_code=408, detail="Conversion timed out.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+
+# ---------------- ODT → DOCX ----------------
+@router.post("/odt-to-docx")
+async def api_odt_to_docx(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate file
+ if not file.filename.lower().endswith(".odt"):
+ raise HTTPException(status_code=400, detail="Invalid ODT file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # 2️⃣ Save upload
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ # 3️⃣ Size protection (100MB)
+ if os.path.getsize(input_path) > 100 * 1024 * 1024:
+ raise HTTPException(status_code=413, detail="File too large.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.docx"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ # 4️⃣ Convert using LibreOffice headless
+ convert_cmd = [
+ "libreoffice",
+ "--headless",
+ "--convert-to", "docx",
+ "--outdir", OUTPUT_DIR,
+ input_path
+ ]
+
+ result = subprocess.run(
+ convert_cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ timeout=120
+ )
+
+ if result.returncode != 0:
+ raise HTTPException(status_code=400, detail="ODT to DOCX conversion failed.")
+
+ # LibreOffice keeps original filename — rename it
+ generated_file = os.path.join(
+ OUTPUT_DIR,
+ os.path.splitext(os.path.basename(input_path))[0] + ".docx"
+ )
+
+ if os.path.exists(generated_file):
+ os.rename(generated_file, output_path)
+ else:
+ raise HTTPException(status_code=500, detail="Output file not found.")
+
+ size = os.path.getsize(output_path)
+
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.TimeoutExpired:
+ raise HTTPException(status_code=408, detail="Conversion timed out.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+
+
+# ---------------- OGG → MP3 ----------------
+@router.post("/ogg-to-mp3")
+async def api_ogg_to_mp3(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate file
+ if not file.filename.lower().endswith(".ogg"):
+ raise HTTPException(status_code=400, detail="Invalid OGG file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # 2️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ # 3️⃣ Size limit (200MB)
+ if os.path.getsize(input_path) > 200 * 1024 * 1024:
+ raise HTTPException(status_code=413, detail="File too large.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.mp3"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ # 4️⃣ Convert using FFmpeg
+ convert_cmd = [
+ "ffmpeg",
+ "-y",
+ "-i", input_path,
+ "-map", "0:a:0",
+ "-vn",
+ "-acodec", "libmp3lame",
+ "-b:a", "192k",
+ output_path
+ ]
+
+ result = subprocess.run(
+ convert_cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ timeout=180
+ )
+
+ if result.returncode != 0:
+ raise HTTPException(status_code=400, detail="OGG to MP3 conversion failed.")
+
+ size = os.path.getsize(output_path)
+
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.TimeoutExpired:
+ raise HTTPException(status_code=408, detail="Conversion timed out.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- PDF → CSV ----------------
+@router.post("/pdf-to-csv")
+async def api_pdf_to_csv(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ import os
+ import uuid
+ import traceback
+ import pandas as pd
+ import pdfplumber
+
+ input_path = None
+
+ try:
+ # 1️⃣ Validate file
+ if not file.filename.lower().endswith(".pdf"):
+ raise HTTPException(status_code=400, detail="Invalid PDF file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # 2️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ if os.path.getsize(input_path) > 200 * 1024 * 1024:
+ raise HTTPException(status_code=413, detail="File too large.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.csv"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ all_tables = []
+
+ # ===============================
+ # 🔹 STEP 1: Try pdfplumber
+ # ===============================
+ with pdfplumber.open(input_path) as pdf:
+ for page in pdf.pages:
+ # Try line-based detection
+ tables = page.extract_tables({
+ "vertical_strategy": "lines",
+ "horizontal_strategy": "lines",
+ })
+
+ # Fallback → text-based detection
+ if not tables:
+ tables = page.extract_tables({
+ "vertical_strategy": "text",
+ "horizontal_strategy": "text",
+ })
+
+ for table in tables:
+ if table:
+ df = pd.DataFrame(table)
+ all_tables.append(df)
+
+ # ===============================
+ # 🔹 STEP 2: Fallback → Camelot
+ # ===============================
+ if not all_tables:
+ try:
+ import camelot
+
+ # Try lattice (for bordered tables)
+ tables = camelot.read_pdf(input_path, pages='all', flavor='lattice')
+
+ # Fallback → stream (for text tables)
+ if tables.n == 0:
+ tables = camelot.read_pdf(input_path, pages='all', flavor='stream')
+
+ for table in tables:
+ all_tables.append(table.df)
+
+ except Exception as e:
+ print("Camelot failed:", e)
+
+ # ===============================
+ # 🔹 STEP 3: Final check
+ # ===============================
+ if not all_tables:
+ raise HTTPException(status_code=400, detail="No tables found in PDF.")
+
+ # ===============================
+ # 🔹 STEP 4: Merge tables
+ # ===============================
+ final_df = pd.concat(all_tables, ignore_index=True)
+
+ # Optional cleanup (header fix)
+ try:
+ final_df.columns = final_df.iloc[0]
+ final_df = final_df[1:]
+ except:
+ pass
+
+ # ===============================
+ # 🔹 STEP 5: Save CSV
+ # ===============================
+ final_df.to_csv(output_path, index=False)
+
+ size = os.path.getsize(output_path)
+
+ # ===============================
+ # 🔹 STEP 6: Return URL
+ # ===============================
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("📊 PDF → CSV:", output_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except HTTPException:
+ raise
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # Cleanup input file
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+# ---------------- PDF → EPUB ----------------
+@router.post("/pdf-to-epub")
+async def api_pdf_to_epub(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ import os
+ import uuid
+ import subprocess
+ import traceback
+
+ input_path = None
+ output_path = None
+
+ try:
+ if not file.filename.lower().endswith(".pdf"):
+ raise HTTPException(status_code=400, detail="Invalid PDF file.")
+
+ TMP_DIR = "temp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # Save file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ input_path = os.path.abspath(input_path)
+
+ if os.path.getsize(input_path) > 200 * 1024 * 1024:
+ raise HTTPException(status_code=413, detail="File too large.")
+
+ uid = str(uuid.uuid4())
+ output_path = os.path.abspath(os.path.join(TMP_DIR, f"{uid}.epub"))
+
+ print("DEBUG PDF:", input_path)
+ print("DEBUG EPUB:", output_path)
+
+ # ✅ Use Calibre
+ def _convert():
+ subprocess.run([
+ "ebook-convert",
+ input_path,
+ output_path
+ ], check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="PDF to EPUB conversion failed.")
+
+ # Move to output
+ final_filename = f"{uid}.epub"
+ final_path = os.path.join(OUTPUT_DIR, final_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{final_filename}"
+
+ print("📕 PDF → EPUB:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError as e:
+ print("❌ Calibre error:", e)
+ raise HTTPException(status_code=500, detail="Calibre conversion failed.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+# ---------------- PDF → EXCEL ----------------
+@router.post("/pdf-to-excel")
+async def api_pdf_to_excel(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ import os
+ import uuid
+ import traceback
+ import pandas as pd
+ import pdfplumber
+
+ input_path = None
+
+ try:
+ # 1️⃣ Validate
+ if not file.filename.lower().endswith(".pdf"):
+ raise HTTPException(status_code=400, detail="Invalid PDF file.")
+
+ TMP_DIR = "tmp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # 2️⃣ Save file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ if os.path.getsize(input_path) > 200 * 1024 * 1024:
+ raise HTTPException(status_code=413, detail="File too large.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.xlsx"
+ output_path = os.path.join(OUTPUT_DIR, output_filename)
+
+ all_tables = []
+
+ # ===============================
+ # 🔹 STEP 1: pdfplumber (improved)
+ # ===============================
+ with pdfplumber.open(input_path) as pdf:
+ for page in pdf.pages:
+ tables = page.extract_tables({
+ "vertical_strategy": "lines",
+ "horizontal_strategy": "lines",
+ })
+
+ if not tables:
+ tables = page.extract_tables({
+ "vertical_strategy": "text",
+ "horizontal_strategy": "text",
+ })
+
+ for table in tables:
+ if table:
+ df = pd.DataFrame(table)
+ all_tables.append(df)
+
+ # ===============================
+ # 🔹 STEP 2: Camelot fallback
+ # ===============================
+ if not all_tables:
+ try:
+ import camelot
+
+ tables = camelot.read_pdf(input_path, pages="all", flavor="lattice")
+
+ if tables.n == 0:
+ tables = camelot.read_pdf(input_path, pages="all", flavor="stream")
+
+ for table in tables:
+ all_tables.append(table.df)
+
+ except Exception as e:
+ print("Camelot failed:", e)
+
+ # ===============================
+ # 🔹 STEP 3: FINAL FALLBACK (text → Excel)
+ # ===============================
+ if not all_tables:
+ with pdfplumber.open(input_path) as pdf:
+ all_text = []
+ for page in pdf.pages:
+ text = page.extract_text()
+ if text:
+ lines = text.split("\n")
+ rows = [line.split() for line in lines if line.strip()]
+ if rows:
+ df = pd.DataFrame(rows)
+ all_tables.append(df)
+
+ # ===============================
+ # 🔹 FINAL CHECK
+ # ===============================
+ if not all_tables:
+ raise HTTPException(
+ status_code=400,
+ detail="No tables or structured data found in PDF."
+ )
+
+ # ===============================
+ # 🔹 WRITE EXCEL
+ # ===============================
+ with pd.ExcelWriter(output_path, engine="openpyxl") as writer:
+ for idx, df in enumerate(all_tables):
+ try:
+ df.columns = df.iloc[0]
+ df = df[1:]
+ except:
+ pass
+
+ df.to_excel(writer, sheet_name=f"Table_{idx+1}", index=False)
+
+ size = os.path.getsize(output_path)
+
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("📊 PDF → Excel:", output_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+@router.post("/pdf-to-html")
+async def api_pdf_to_html(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ import os
+ import uuid
+ import traceback
+ from io import BytesIO
+ from pdfminer.high_level import extract_text_to_fp
+ from pdfminer.layout import LAParams
+
+ input_path = None
+
+ try:
+ if not file.filename.lower().endswith(".pdf"):
+ raise HTTPException(status_code=400, detail="Invalid PDF file.")
+
+ TMP_DIR = "temp"
+ OUTPUT_DIR = "static/output"
+
+ os.makedirs(TMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ # Save file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ input_path = os.path.abspath(input_path)
+
+ if os.path.getsize(input_path) > 200 * 1024 * 1024:
+ raise HTTPException(status_code=413, detail="File too large.")
+
+ uid = str(uuid.uuid4())
+ output_path = os.path.join(OUTPUT_DIR, f"{uid}.html")
+
+ # ✅ FIXED conversion (BytesIO)
+ with open(input_path, "rb") as pdf_file:
+ buffer = BytesIO()
+
+ extract_text_to_fp(
+ pdf_file,
+ buffer,
+ laparams=LAParams(),
+ output_type="html",
+ codec="utf-8"
+ )
+
+ with open(output_path, "wb") as f:
+ f.write(buffer.getvalue())
+
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{uid}.html"
+
+ return JSONResponse({
+ "url": file_url
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- PDF → JPG ----------------
+@router.post("/pdf-to-jpg")
+async def api_pdf_to_jpg(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ temp_image_paths = []
+ zip_output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Save uploaded PDF
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PDF:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ zip_filename = f"{uid}.zip"
+ zip_output_path = os.path.join(TMP_DIR, zip_filename)
+
+ # ----------------------------------------------------
+ # 2️⃣ Convert PDF pages → JPG images
+ # ----------------------------------------------------
+ def _convert_pdf():
+ with fitz.open(input_path) as doc:
+ for page_number in range(len(doc)):
+ page = doc.load_page(page_number)
+
+ # Render page at 2x resolution (better quality)
+ matrix = fitz.Matrix(2, 2)
+ pix = page.get_pixmap(matrix=matrix)
+
+ img_filename = f"{uid}_page_{page_number + 1}.jpg"
+ img_path = os.path.join(TMP_DIR, img_filename)
+
+ pix.save(img_path)
+ temp_image_paths.append(img_path)
+
+ await run_in_threadpool(_convert_pdf)
+
+ if not temp_image_paths:
+ raise HTTPException(500, "PDF to JPG conversion failed.")
+
+ # ----------------------------------------------------
+ # 3️⃣ Create ZIP of all images
+ # ----------------------------------------------------
+ def _create_zip():
+ with zipfile.ZipFile(zip_output_path, "w", zipfile.ZIP_DEFLATED) as zipf:
+ for img_path in temp_image_paths:
+ zipf.write(img_path, os.path.basename(img_path))
+
+ await run_in_threadpool(_create_zip)
+
+ if not os.path.exists(zip_output_path):
+ raise HTTPException(500, "ZIP creation failed.")
+
+ # ----------------------------------------------------
+ # 4️⃣ Move ZIP → static/output
+ # ----------------------------------------------------
+ filename = os.path.basename(zip_output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(zip_output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 5️⃣ Build dynamic URL
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 PDF → JPG ZIP:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # ----------------------------------------------------
+ # 6️⃣ Cleanup temp files
+ # ----------------------------------------------------
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+ for img_path in temp_image_paths:
+ try:
+ await run_in_threadpool(os.remove, img_path)
+ except:
+ pass
+
+# ---------------- PDF → LaTeX ----------------
+@router.post("/pdf-to-latex")
+async def api_pdf_to_latex(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Save uploaded PDF
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PDF:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.tex"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # ----------------------------------------------------
+ # 2️⃣ Extract text safely
+ # ----------------------------------------------------
+ def _extract_text():
+ text_parts = []
+ with fitz.open(input_path) as doc:
+ for page in doc:
+ text_parts.append(page.get_text("text"))
+ return "\n\n".join(text_parts)
+
+ raw_text = await run_in_threadpool(_extract_text)
+
+ if not raw_text.strip():
+ raise HTTPException(400, "No extractable text found in PDF.")
+
+ # ----------------------------------------------------
+ # 3️⃣ Escape LaTeX special characters
+ # ----------------------------------------------------
+ def escape_latex(text: str) -> str:
+ replacements = {
+ "&": r"\&",
+ "%": r"\%",
+ "$": r"\$",
+ "#": r"\#",
+ "_": r"\_",
+ "{": r"\{",
+ "}": r"\}",
+ "~": r"\textasciitilde{}",
+ "^": r"\textasciicircum{}",
+ "\\": r"\textbackslash{}",
+ }
+ for key, value in replacements.items():
+ text = text.replace(key, value)
+ return text
+
+ safe_text = escape_latex(raw_text)
+
+ # ----------------------------------------------------
+ # 4️⃣ Wrap into full LaTeX document
+ # ----------------------------------------------------
+ latex_content = f"""
+\\documentclass{{article}}
+\\usepackage[utf8]{{inputenc}}
+\\usepackage{{amsmath}}
+\\usepackage{{graphicx}}
+\\usepackage{{geometry}}
+\\geometry{{margin=1in}}
+
+\\title{{Converted PDF Document}}
+\\author{{CloudAiPDF}}
+\\date{{}}
+
+\\begin{{document}}
+\\maketitle
+
+{safe_text}
+
+\\end{{document}}
+"""
+
+ # ----------------------------------------------------
+ # 5️⃣ Save .tex file
+ # ----------------------------------------------------
+ with open(output_path, "w", encoding="utf-8") as f:
+ f.write(latex_content)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "LaTeX generation failed.")
+
+ # ----------------------------------------------------
+ # 6️⃣ Move to static/output
+ # ----------------------------------------------------
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 7️⃣ Dynamic URL
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 PDF → LaTeX:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- PDF → PNG ----------------
+@router.post("/pdf-to-png")
+async def api_pdf_to_png(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ temp_image_paths = []
+ zip_output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Save uploaded PDF
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PDF:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ zip_filename = f"{uid}.zip"
+ zip_output_path = os.path.join(TMP_DIR, zip_filename)
+
+ # ----------------------------------------------------
+ # 2️⃣ Convert PDF pages → PNG
+ # ----------------------------------------------------
+ def _convert_pdf():
+ with fitz.open(input_path) as doc:
+ for page_number in range(len(doc)):
+ page = doc.load_page(page_number)
+
+ # 2x resolution (good balance quality/size)
+ matrix = fitz.Matrix(2, 2)
+ pix = page.get_pixmap(matrix=matrix)
+
+ img_filename = f"{uid}_page_{page_number + 1}.png"
+ img_path = os.path.join(TMP_DIR, img_filename)
+
+ pix.save(img_path)
+ temp_image_paths.append(img_path)
+
+ await run_in_threadpool(_convert_pdf)
+
+ if not temp_image_paths:
+ raise HTTPException(500, "PDF to PNG conversion failed.")
+
+ # ----------------------------------------------------
+ # 3️⃣ Create ZIP of all PNGs
+ # ----------------------------------------------------
+ def _create_zip():
+ with zipfile.ZipFile(zip_output_path, "w", zipfile.ZIP_DEFLATED) as zipf:
+ for img_path in temp_image_paths:
+ zipf.write(img_path, os.path.basename(img_path))
+
+ await run_in_threadpool(_create_zip)
+
+ if not os.path.exists(zip_output_path):
+ raise HTTPException(500, "ZIP creation failed.")
+
+ # ----------------------------------------------------
+ # 4️⃣ Move ZIP → static/output
+ # ----------------------------------------------------
+ filename = os.path.basename(zip_output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(zip_output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 5️⃣ Build dynamic URL
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 PDF → PNG ZIP:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # ----------------------------------------------------
+ # 6️⃣ Cleanup temp files
+ # ----------------------------------------------------
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+ for img_path in temp_image_paths:
+ try:
+ await run_in_threadpool(os.remove, img_path)
+ except:
+ pass
+
+# ---------------- PDF → POWERPOINT ----------------
+@router.post("/pdf-to-powerpoint")
+async def api_pdf_to_powerpoint(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ temp_image_paths = []
+ output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Save uploaded PDF
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PDF:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.pptx"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # ----------------------------------------------------
+ # 2️⃣ Convert each PDF page → image
+ # ----------------------------------------------------
+ def _render_pdf_pages():
+ with fitz.open(input_path) as doc:
+ for page_number in range(len(doc)):
+ page = doc.load_page(page_number)
+
+ # High quality render
+ matrix = fitz.Matrix(2, 2)
+ pix = page.get_pixmap(matrix=matrix)
+
+ img_filename = f"{uid}_page_{page_number + 1}.png"
+ img_path = os.path.join(TMP_DIR, img_filename)
+
+ pix.save(img_path)
+ temp_image_paths.append(img_path)
+
+ await run_in_threadpool(_render_pdf_pages)
+
+ if not temp_image_paths:
+ raise HTTPException(500, "PDF rendering failed.")
+
+ # ----------------------------------------------------
+ # 3️⃣ Create PowerPoint
+ # ----------------------------------------------------
+ def _create_ppt():
+ from pptx import Presentation
+ from pptx.util import Inches
+
+ prs = Presentation()
+ blank_layout = prs.slide_layouts[6]
+
+ for img_path in temp_image_paths:
+ slide = prs.slides.add_slide(blank_layout)
+
+ # Full slide image
+ slide.shapes.add_picture(
+ img_path,
+ 0,
+ 0,
+ width=prs.slide_width,
+ height=prs.slide_height
+ )
+
+ prs.save(output_path)
+
+ await run_in_threadpool(_create_ppt)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "PowerPoint generation failed.")
+
+ # ----------------------------------------------------
+ # 4️⃣ Move to static/output
+ # ----------------------------------------------------
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 5️⃣ Dynamic URL
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 PDF → PPTX:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # ----------------------------------------------------
+ # 6️⃣ Cleanup temp files
+ # ----------------------------------------------------
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+ for img_path in temp_image_paths:
+ try:
+ await run_in_threadpool(os.remove, img_path)
+ except:
+ pass
+
+
+# ---------------- PDF → SVG ----------------
+@router.post("/pdf-to-svg")
+async def api_pdf_to_svg(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ temp_svg_paths = []
+ zip_output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Save uploaded PDF
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PDF:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ zip_filename = f"{uid}.zip"
+ zip_output_path = os.path.join(TMP_DIR, zip_filename)
+
+ # ----------------------------------------------------
+ # 2️⃣ Convert PDF pages → SVG (vector)
+ # ----------------------------------------------------
+ def _convert_pdf():
+ with fitz.open(input_path) as doc:
+ for page_number in range(len(doc)):
+ page = doc.load_page(page_number)
+
+ svg_content = page.get_svg_image()
+
+ svg_filename = f"{uid}_page_{page_number + 1}.svg"
+ svg_path = os.path.join(TMP_DIR, svg_filename)
+
+ with open(svg_path, "w", encoding="utf-8") as f:
+ f.write(svg_content)
+
+ temp_svg_paths.append(svg_path)
+
+ await run_in_threadpool(_convert_pdf)
+
+ if not temp_svg_paths:
+ raise HTTPException(500, "PDF to SVG conversion failed.")
+
+ # ----------------------------------------------------
+ # 3️⃣ Create ZIP of all SVGs
+ # ----------------------------------------------------
+ def _create_zip():
+ with zipfile.ZipFile(zip_output_path, "w", zipfile.ZIP_DEFLATED) as zipf:
+ for svg_path in temp_svg_paths:
+ zipf.write(svg_path, os.path.basename(svg_path))
+
+ await run_in_threadpool(_create_zip)
+
+ if not os.path.exists(zip_output_path):
+ raise HTTPException(500, "ZIP creation failed.")
+
+ # ----------------------------------------------------
+ # 4️⃣ Move ZIP → static/output
+ # ----------------------------------------------------
+ filename = os.path.basename(zip_output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(zip_output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 5️⃣ Dynamic URL
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 PDF → SVG ZIP:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # ----------------------------------------------------
+ # 6️⃣ Cleanup temp files
+ # ----------------------------------------------------
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+ for svg_path in temp_svg_paths:
+ try:
+ await run_in_threadpool(os.remove, svg_path)
+ except:
+ pass
+
+# ---------------- PDF → TEXT ----------------
+@router.post("/pdf-text")
+async def api_pdf_to_text(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Validate file
+ # ----------------------------------------------------
+ if file.content_type != "application/pdf":
+ raise HTTPException(status_code=400, detail="Invalid PDF file.")
+
+ # ----------------------------------------------------
+ # 2️⃣ Save uploaded PDF
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PDF:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.txt"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # ----------------------------------------------------
+ # 3️⃣ Extract text safely (threadpool)
+ # ----------------------------------------------------
+ def _extract_text():
+ text_parts = []
+ with fitz.open(input_path) as doc:
+ for page in doc:
+ text_parts.append(page.get_text("text"))
+ return "\n\n".join(text_parts)
+
+ extracted_text = await run_in_threadpool(_extract_text)
+
+ if not extracted_text.strip():
+ raise HTTPException(
+ status_code=400,
+ detail="No extractable text found (scanned PDF may require OCR)."
+ )
+
+ # ----------------------------------------------------
+ # 4️⃣ Save TXT file
+ # ----------------------------------------------------
+ with open(output_path, "w", encoding="utf-8") as f:
+ f.write(extracted_text)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "Text extraction failed.")
+
+ # ----------------------------------------------------
+ # 5️⃣ Move to static/output
+ # ----------------------------------------------------
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 6️⃣ Dynamic URL (localhost + production safe)
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 PDF → TEXT:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # ----------------------------------------------------
+ # 7️⃣ Cleanup uploaded PDF
+ # ----------------------------------------------------
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- PDF → TIFF (Multi-page) ----------------
+@router.post("/pdf-to-tiff")
+async def api_pdf_to_tiff(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Validate
+ # ----------------------------------------------------
+ if file.content_type != "application/pdf":
+ raise HTTPException(status_code=400, detail="Invalid PDF file.")
+
+ # ----------------------------------------------------
+ # 2️⃣ Save uploaded PDF
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PDF:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.tiff"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # ----------------------------------------------------
+ # 3️⃣ Convert PDF → multi-page TIFF
+ # ----------------------------------------------------
+ def _convert_pdf():
+ images = []
+
+ with fitz.open(input_path) as doc:
+ for page in doc:
+ # 2x resolution (adjust if needed)
+ matrix = fitz.Matrix(2, 2)
+ pix = page.get_pixmap(matrix=matrix)
+
+ # Convert pixmap → PIL Image
+ img = Image.frombytes(
+ "RGB",
+ [pix.width, pix.height],
+ pix.samples
+ )
+ images.append(img)
+
+ if not images:
+ raise ValueError("No pages rendered.")
+
+ # Save multi-page TIFF with compression
+ images[0].save(
+ output_path,
+ save_all=True,
+ append_images=images[1:],
+ compression="tiff_lzw"
+ )
+
+ await run_in_threadpool(_convert_pdf)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "TIFF conversion failed.")
+
+ # ----------------------------------------------------
+ # 4️⃣ Move to static/output
+ # ----------------------------------------------------
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 5️⃣ Dynamic URL
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 PDF → TIFF:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # ----------------------------------------------------
+ # 6️⃣ Cleanup uploaded PDF
+ # ----------------------------------------------------
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- PDF → WORD (DOCX) ----------------
+@router.post("/pdf-to-word")
+async def api_pdf_to_word(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Validate file
+ # ----------------------------------------------------
+ if file.content_type != "application/pdf":
+ raise HTTPException(status_code=400, detail="Invalid PDF file.")
+
+ # ----------------------------------------------------
+ # 2️⃣ Save uploaded PDF
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PDF:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.docx"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # ----------------------------------------------------
+ # 3️⃣ Convert PDF → DOCX
+ # ----------------------------------------------------
+ def _convert_pdf_to_docx():
+ from docx import Document
+
+ document = Document()
+
+ with fitz.open(input_path) as pdf:
+ for page_index, page in enumerate(pdf):
+ text = page.get_text("text")
+
+ if text.strip():
+ paragraphs = text.split("\n")
+
+ for para in paragraphs:
+ document.add_paragraph(para)
+
+ # Add page break except last page
+ if page_index < len(pdf) - 1:
+ document.add_page_break()
+
+ document.save(output_path)
+
+ await run_in_threadpool(_convert_pdf_to_docx)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "Word conversion failed.")
+
+ # ----------------------------------------------------
+ # 4️⃣ Move to static/output
+ # ----------------------------------------------------
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 5️⃣ Dynamic URL
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 PDF → WORD:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # ----------------------------------------------------
+ # 6️⃣ Cleanup uploaded PDF
+ # ----------------------------------------------------
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- PDF → XML ----------------
+@router.post("/pdf-to-xml")
+async def api_pdf_to_xml(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Validate file
+ # ----------------------------------------------------
+ if file.content_type != "application/pdf":
+ raise HTTPException(status_code=400, detail="Invalid PDF file.")
+
+ # ----------------------------------------------------
+ # 2️⃣ Save uploaded PDF
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PDF:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.xml"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # ----------------------------------------------------
+ # 3️⃣ Convert PDF → Structured XML
+ # ----------------------------------------------------
+ def _convert_pdf_to_xml():
+ import xml.etree.ElementTree as ET
+
+ root = ET.Element("pdf")
+
+ with fitz.open(input_path) as doc:
+ for page_number, page in enumerate(doc, start=1):
+ page_elem = ET.SubElement(root, "page", number=str(page_number))
+
+ blocks = page.get_text("blocks")
+
+ for block in blocks:
+ # block format: (x0, y0, x1, y1, "text", block_no, block_type)
+ text = block[4].strip()
+ if not text:
+ continue
+
+ block_elem = ET.SubElement(page_elem, "block")
+
+ lines = text.split("\n")
+ for line in lines:
+ line = line.strip()
+ if line:
+ line_elem = ET.SubElement(block_elem, "line")
+ line_elem.text = line
+
+ tree = ET.ElementTree(root)
+ tree.write(output_path, encoding="utf-8", xml_declaration=True)
+
+ await run_in_threadpool(_convert_pdf_to_xml)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "XML conversion failed.")
+
+ # ----------------------------------------------------
+ # 4️⃣ Move to static/output
+ # ----------------------------------------------------
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 5️⃣ Dynamic URL
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 PDF → XML:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # ----------------------------------------------------
+ # 6️⃣ Cleanup uploaded PDF
+ # ----------------------------------------------------
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- PNG → AVIF ----------------
+@router.post("/png-to-avif")
+async def api_png_to_avif(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Validate file type
+ # ----------------------------------------------------
+ if file.content_type != "image/png":
+ raise HTTPException(status_code=400, detail="Invalid PNG file.")
+
+ # ----------------------------------------------------
+ # 2️⃣ Save uploaded file
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PNG:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.avif"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # ----------------------------------------------------
+ # 3️⃣ Convert PNG → AVIF
+ # ----------------------------------------------------
+ def _convert():
+ with Image.open(input_path) as img:
+ # Preserve transparency if exists
+ if img.mode not in ("RGB", "RGBA"):
+ img = img.convert("RGBA")
+
+ img.save(
+ output_path,
+ format="AVIF",
+ quality=50 # adjust quality if needed (0-100)
+ )
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "PNG to AVIF conversion failed.")
+
+ # ----------------------------------------------------
+ # 4️⃣ Move to static/output
+ # ----------------------------------------------------
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 5️⃣ Dynamic URL
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 PNG → AVIF:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # ----------------------------------------------------
+ # 6️⃣ Cleanup input file
+ # ----------------------------------------------------
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- PNG → JPG ----------------
+@router.post("/png-to-jpg")
+async def api_png_to_jpg(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Validate file
+ # ----------------------------------------------------
+ if file.content_type != "image/png":
+ raise HTTPException(status_code=400, detail="Invalid PNG file.")
+
+ # ----------------------------------------------------
+ # 2️⃣ Save uploaded file
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PNG:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.jpg"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # ----------------------------------------------------
+ # 3️⃣ Convert PNG → JPG
+ # ----------------------------------------------------
+ def _convert():
+ with Image.open(input_path) as img:
+
+ # Handle transparency
+ if img.mode in ("RGBA", "LA"):
+ background = Image.new("RGB", img.size, (255, 255, 255))
+ background.paste(img, mask=img.split()[-1])
+ img = background
+ else:
+ img = img.convert("RGB")
+
+ img.save(
+ output_path,
+ "JPEG",
+ quality=95,
+ optimize=True
+ )
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "PNG to JPG conversion failed.")
+
+ # ----------------------------------------------------
+ # 4️⃣ Move to static/output
+ # ----------------------------------------------------
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 5️⃣ Build dynamic URL
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 PNG → JPG:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # ----------------------------------------------------
+ # 6️⃣ Cleanup input file
+ # ----------------------------------------------------
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- PNG → PDF (Multi Image Merge) ----------------
+@router.post("/png-to-pdf")
+async def api_png_to_pdf(
+ request: Request,
+ files: list[UploadFile] = File(...),
+ db: Session = Depends(get_db)
+):
+ saved_paths = []
+ output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Validate input
+ # ----------------------------------------------------
+ if not files or len(files) == 0:
+ raise HTTPException(status_code=400, detail="No PNG files uploaded.")
+
+ for file in files:
+ if file.content_type != "image/png":
+ raise HTTPException(status_code=400, detail="Only PNG files are allowed.")
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # ----------------------------------------------------
+ # 2️⃣ Save uploaded PNG files
+ # ----------------------------------------------------
+ for file in files:
+ path = await run_in_threadpool(save_upload_file, file)
+ saved_paths.append(path)
+
+ print(f"📥 Saved {len(saved_paths)} PNG files")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.pdf"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # ----------------------------------------------------
+ # 3️⃣ Merge PNGs → Single PDF
+ # ----------------------------------------------------
+ def _merge_images():
+ images = []
+
+ for path in saved_paths:
+ img = Image.open(path)
+
+ # Remove transparency (PDF does not support alpha)
+ if img.mode in ("RGBA", "LA"):
+ background = Image.new("RGB", img.size, (255, 255, 255))
+ background.paste(img, mask=img.split()[-1])
+ img = background
+ else:
+ img = img.convert("RGB")
+
+ images.append(img)
+
+ if not images:
+ raise ValueError("No images processed.")
+
+ # Save multi-page PDF
+ images[0].save(
+ output_path,
+ save_all=True,
+ append_images=images[1:]
+ )
+
+ await run_in_threadpool(_merge_images)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "PNG to PDF conversion failed.")
+
+ # ----------------------------------------------------
+ # 4️⃣ Move to static/output
+ # ----------------------------------------------------
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 5️⃣ Dynamic URL
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 PNG → PDF:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size,
+ "pages": len(saved_paths)
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # ----------------------------------------------------
+ # 6️⃣ Cleanup uploaded PNG files
+ # ----------------------------------------------------
+ for path in saved_paths:
+ try:
+ await run_in_threadpool(os.remove, path)
+ except:
+ pass
+
+# ---------------- PNG → SVG (Vectorize using Potrace) ----------------
+@router.post("/png-to-svg")
+async def api_png_to_svg(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ bmp_path = None
+ output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Validate
+ # ----------------------------------------------------
+ if file.content_type != "image/png":
+ raise HTTPException(status_code=400, detail="Invalid PNG file.")
+
+ # ----------------------------------------------------
+ # 2️⃣ Save PNG
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PNG:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ bmp_path = os.path.join(TMP_DIR, f"{uid}.bmp")
+ output_path = os.path.join(TMP_DIR, f"{uid}.svg")
+
+ # ----------------------------------------------------
+ # 3️⃣ Convert PNG → BMP (grayscale for tracing)
+ # ----------------------------------------------------
+ def _prepare_bitmap():
+ with Image.open(input_path) as img:
+ img = img.convert("L") # grayscale
+ img.save(bmp_path)
+
+ await run_in_threadpool(_prepare_bitmap)
+
+ # ----------------------------------------------------
+ # 4️⃣ Run Potrace (BMP → SVG)
+ # ----------------------------------------------------
+ def _run_potrace():
+ cmd = [
+ "potrace",
+ bmp_path,
+ "-s", # output SVG
+ "-o", output_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_run_potrace)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "Vectorization failed.")
+
+ # ----------------------------------------------------
+ # 5️⃣ Move to static/output
+ # ----------------------------------------------------
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 6️⃣ Dynamic URL
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 PNG → SVG:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="Potrace execution failed.")
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # Cleanup
+ for path in [input_path, bmp_path]:
+ if path and os.path.exists(path):
+ try:
+ await run_in_threadpool(os.remove, path)
+ except:
+ pass
+
+# ---------------- PNG → WEBP ----------------
+@router.post("/png-to-webp")
+async def api_png_to_webp(
+ request: Request,
+ file: UploadFile = File(...),
+ quality: int = Form(90),
+ lossless: bool = Form(False),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Validate
+ # ----------------------------------------------------
+ if file.content_type != "image/png":
+ raise HTTPException(status_code=400, detail="Invalid PNG file.")
+
+ if quality < 1 or quality > 100:
+ raise HTTPException(status_code=400, detail="Quality must be between 1–100.")
+
+ # ----------------------------------------------------
+ # 2️⃣ Save uploaded PNG
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PNG:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.webp"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # ----------------------------------------------------
+ # 3️⃣ Convert PNG → WEBP
+ # ----------------------------------------------------
+ def _convert():
+ with Image.open(input_path) as img:
+ img.save(
+ output_path,
+ "WEBP",
+ quality=quality,
+ lossless=lossless,
+ method=6 # best compression effort
+ )
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "PNG to WEBP conversion failed.")
+
+ # ----------------------------------------------------
+ # 4️⃣ Move to static/output
+ # ----------------------------------------------------
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 5️⃣ Dynamic URL
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 PNG → WEBP:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size,
+ "quality": quality,
+ "lossless": lossless
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # ----------------------------------------------------
+ # 6️⃣ Cleanup input
+ # ----------------------------------------------------
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- PPT → HTML ----------------
+@router.post("/ppt-to-html")
+async def api_ppt_to_html(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_dir = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Validate
+ # ----------------------------------------------------
+ if not file.filename.lower().endswith((".ppt", ".pptx")):
+ raise HTTPException(status_code=400, detail="Invalid PowerPoint file.")
+
+ # ----------------------------------------------------
+ # 2️⃣ Save uploaded PPT
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PPT:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ output_dir = os.path.join(TMP_DIR, uid)
+ os.makedirs(output_dir, exist_ok=True)
+
+ # ----------------------------------------------------
+ # 3️⃣ Convert using LibreOffice headless
+ # ----------------------------------------------------
+ def _convert():
+ cmd = [
+ "soffice",
+ "--headless",
+ "--convert-to", "html",
+ "--outdir", output_dir,
+ input_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ # ----------------------------------------------------
+ # 4️⃣ Find generated HTML file
+ # ----------------------------------------------------
+ generated_files = os.listdir(output_dir)
+ html_files = [f for f in generated_files if f.endswith(".html")]
+
+ if not html_files:
+ raise HTTPException(500, "HTML conversion failed.")
+
+ html_filename = html_files[0]
+ html_path = os.path.join(output_dir, html_filename)
+
+ # ----------------------------------------------------
+ # 5️⃣ Move to static/output
+ # ----------------------------------------------------
+ final_filename = f"{uid}.html"
+ final_path = os.path.join(OUTPUT_DIR, final_filename)
+ os.replace(html_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 6️⃣ Dynamic URL
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{final_filename}"
+
+ print("📤 PPT → HTML:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="LibreOffice conversion failed.")
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # Cleanup input file
+ if input_path and os.path.exists(input_path):
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+ # Cleanup temp directory
+ if output_dir and os.path.exists(output_dir):
+ try:
+ for f in os.listdir(output_dir):
+ os.remove(os.path.join(output_dir, f))
+ os.rmdir(output_dir)
+ except:
+ pass
+
+# ---------------- PPT → PDF ----------------
+@router.post("/ppt-to-pdf")
+async def api_ppt_to_pdf(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate file
+ if not file.filename.lower().endswith((".ppt", ".pptx")):
+ raise HTTPException(status_code=400, detail="Invalid PowerPoint file.")
+
+ # 2️⃣ Save uploaded PPT
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PPT:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.pdf"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 3️⃣ Convert using LibreOffice (Headless)
+ def _convert():
+ abs_input = os.path.abspath(input_path)
+ abs_tmp = os.path.abspath(TMP_DIR)
+
+ cmd = [
+ "soffice",
+ "--headless",
+ "--convert-to", "pdf",
+ "--outdir", abs_tmp,
+ abs_input
+ ]
+ print("🚀 CMD:", " ".join(cmd))
+ result = subprocess.run(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ timeout=120
+ )
+ print("STDOUT:", result.stdout.decode(errors="ignore"))
+ print("STDERR:", result.stderr.decode(errors="ignore"))
+ print("RC:", result.returncode)
+
+ if result.returncode != 0:
+ raise RuntimeError(f"LibreOffice failed rc={result.returncode}")
+
+ await run_in_threadpool(_convert)
+
+ # 4️⃣ Find the generated PDF — LibreOffice names it after the INPUT file
+ abs_tmp = os.path.abspath(TMP_DIR)
+ base_name = os.path.splitext(os.path.basename(input_path))[0]
+ generated_pdf = os.path.join(abs_tmp, base_name + ".pdf")
+
+ print("🔍 Looking for generated PDF:", generated_pdf)
+
+ if not os.path.exists(generated_pdf):
+ # List what's in tmp to debug
+ print("📁 TMP contents:", os.listdir(abs_tmp))
+ raise HTTPException(500, "PDF conversion failed — output not found.")
+
+ # 5️⃣ Rename to UUID
+ os.rename(generated_pdf, output_path)
+
+ # 6️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 7️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("📤 PPT → PDF:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.TimeoutExpired:
+ raise HTTPException(status_code=500, detail="LibreOffice timed out.")
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="LibreOffice conversion failed.")
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+# ---------------- PPT → PPTX ----------------
+@router.post("/ppt-to-pptx")
+async def api_ppt_to_pptx(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # ----------------------------------------------------
+ # 1️⃣ Validate file
+ # ----------------------------------------------------
+ if not file.filename.lower().endswith(".ppt"):
+ raise HTTPException(status_code=400, detail="Invalid PPT file.")
+
+ # ----------------------------------------------------
+ # 2️⃣ Save uploaded PPT
+ # ----------------------------------------------------
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved PPT:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.pptx"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # ----------------------------------------------------
+ # 3️⃣ Convert using LibreOffice
+ # ----------------------------------------------------
+ def _convert():
+ cmd = [
+ "soffice",
+ "--headless",
+ "--invisible",
+ "--norestore",
+ "--nolockcheck",
+ "--nodefault",
+ "--convert-to", "pptx",
+ "--outdir", TMP_DIR,
+ input_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ # LibreOffice generates file with original base name
+ generated_file = os.path.splitext(input_path)[0] + ".pptx"
+
+ if not os.path.exists(generated_file):
+ raise HTTPException(500, "PPTX conversion failed.")
+
+ os.rename(generated_file, output_path)
+
+ # ----------------------------------------------------
+ # 4️⃣ Move to static/output
+ # ----------------------------------------------------
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # ----------------------------------------------------
+ # 5️⃣ Dynamic URL
+ # ----------------------------------------------------
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("📤 PPT → PPTX:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="LibreOffice conversion failed.")
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # Cleanup input
+ if input_path and os.path.exists(input_path):
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- PPTX → PPT ----------------
+@router.post("/pptx-to-ppt")
+async def api_pptx_to_ppt(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+
+ try:
+ # 1️⃣ Validate extension
+ if not file.filename.lower().endswith(".pptx"):
+ raise HTTPException(status_code=400, detail="Invalid PPTX file.")
+
+ BASE_DIR = os.path.abspath(".")
+ TEMP_DIR = os.path.join(BASE_DIR, "temp")
+ OUTPUT_TMP_DIR = os.path.join(BASE_DIR, "tmp")
+ os.makedirs(TEMP_DIR, exist_ok=True)
+ os.makedirs(OUTPUT_TMP_DIR, exist_ok=True)
+
+ # 2️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ input_path = os.path.abspath(input_path)
+
+ print("📥 Saved PPTX:", input_path)
+
+ if not os.path.exists(input_path):
+ raise HTTPException(status_code=500, detail="Uploaded file not found.")
+
+ file_size = os.path.getsize(input_path)
+ print("📦 File size:", file_size)
+
+ if file_size == 0:
+ raise HTTPException(status_code=400, detail="Uploaded file is empty.")
+
+ # Ensure proper permissions
+ os.chmod(input_path, 0o644)
+ os.chmod(OUTPUT_TMP_DIR, 0o755)
+
+ # 3️⃣ Convert using LibreOffice (NO custom profile)
+ def _convert():
+ cmd = [
+ "libreoffice",
+ "--headless",
+ "--nologo",
+ "--nodefault",
+ "--nofirststartwizard",
+ "--nolockcheck",
+ "--convert-to", "ppt:MS PowerPoint 97",
+ "--outdir", OUTPUT_TMP_DIR,
+ input_path
+ ]
+
+ print("🚀 Running:", " ".join(cmd))
+
+ result = subprocess.run(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ timeout=120
+ )
+
+ print("STDOUT:", result.stdout.decode())
+ print("STDERR:", result.stderr.decode())
+
+ if result.returncode != 0:
+ raise RuntimeError("LibreOffice conversion failed.")
+
+ await run_in_threadpool(_convert)
+
+ # 4️⃣ Locate output file
+ base_name = os.path.splitext(os.path.basename(input_path))[0]
+ converted_file = os.path.join(OUTPUT_TMP_DIR, f"{base_name}.ppt")
+
+ if not os.path.exists(converted_file):
+ raise HTTPException(status_code=500, detail="Conversion output file missing.")
+
+ # 5️⃣ Move to static/output
+ uid = str(uuid.uuid4())
+ final_filename = f"{uid}.ppt"
+ final_path = os.path.join(OUTPUT_DIR, final_filename)
+
+ os.replace(converted_file, final_path)
+
+ size = os.path.getsize(final_path)
+
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{final_filename}"
+
+ print("✅ Conversion successful:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except HTTPException:
+ raise
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 6️⃣ Cleanup uploaded file
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- PSD → JPG ----------------
+@router.post("/psd-to-jpg")
+async def api_psd_to_jpg(
+ request: Request,
+ file: UploadFile = File(...),
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # Validate
+ if not file.filename.lower().endswith(".psd"):
+ raise HTTPException(status_code=400, detail="Invalid PSD file.")
+
+ # Save upload
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.jpg"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # Convert using ImageMagick
+ def _convert():
+ cmd = [
+ "convert",
+ input_path,
+ "-flatten", # merge layers
+ "-quality", "90", # good balance
+ output_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "Conversion failed.")
+
+ # Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="ImageMagick conversion failed.")
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- PSD → PNG ----------------
+@router.post("/psd-to-png")
+async def api_psd_to_png(
+ request: Request,
+ file: UploadFile = File(...)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate
+ if not file.filename.lower().endswith(".psd"):
+ raise HTTPException(status_code=400, detail="Invalid PSD file.")
+
+ # 2️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.png"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 3️⃣ Convert using ImageMagick
+ def _convert():
+ cmd = [
+ "convert",
+ input_path,
+ "-flatten", # Merge layers
+ "-background", "none", # Preserve transparency
+ output_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "Conversion failed.")
+
+ # 4️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="ImageMagick conversion failed.")
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ os.remove(input_path)
+ except:
+ pass
+
+# ---------------- RAR → ZIP ----------------
+@router.post("/rar-to-zip")
+async def api_rar_to_zip(
+ request: Request,
+ file: UploadFile = File(...)
+):
+ input_path = None
+ extract_dir = None
+ zip_path = None
+
+ try:
+ # 1️⃣ Validate
+ if not file.filename.lower().endswith(".rar"):
+ raise HTTPException(status_code=400, detail="Invalid RAR file.")
+
+ input_path = await run_in_threadpool(save_upload_file, file)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ extract_dir = os.path.join(TMP_DIR, f"extract_{uid}")
+ os.makedirs(extract_dir, exist_ok=True)
+
+ # 2️⃣ Extract RAR safely
+ def _extract():
+ cmd = ["unrar", "x", "-o+", input_path, extract_dir]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_extract)
+
+ # 3️⃣ Create ZIP
+ output_filename = f"{uid}.zip"
+ zip_path = os.path.join(TMP_DIR, output_filename)
+
+ def _zip():
+ subprocess.run(
+ ["zip", "-r", zip_path, "."],
+ cwd=extract_dir,
+ check=True
+ )
+
+ await run_in_threadpool(_zip)
+
+ if not os.path.exists(zip_path):
+ raise HTTPException(status_code=500, detail="ZIP creation failed.")
+
+ # 4️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(zip_path, final_path)
+
+ size = os.path.getsize(final_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(
+ status_code=400,
+ detail="Extraction failed. Archive may be corrupted or password protected."
+ )
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # Cleanup
+ try:
+ if input_path and os.path.exists(input_path):
+ os.remove(input_path)
+
+ if extract_dir and os.path.exists(extract_dir):
+ shutil.rmtree(extract_dir, ignore_errors=True)
+
+ except:
+ pass
+
+# ---------------- RAW → JPG ----------------
+# ---------------- RAW → JPG ----------------
+import rawpy
+import imageio
+
+@router.post("/raw-to-jpg")
+async def api_raw_to_jpg(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate RAW extension
+ allowed_ext = (
+ ".arw", ".cr2", ".cr3", ".dng",
+ ".nef", ".orf", ".raf", ".rw2", ".srw"
+ )
+
+ if not file.filename.lower().endswith(allowed_ext):
+ raise HTTPException(status_code=400, detail="Invalid RAW file.")
+
+ # 2️⃣ Save uploaded RAW file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved RAW:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.jpg"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 3️⃣ Convert RAW → JPG
+ def _convert():
+ with rawpy.imread(input_path) as raw:
+ rgb = raw.postprocess(
+ use_camera_wb=True,
+ half_size=False,
+ no_auto_bright=False,
+ output_bps=8
+ )
+ imageio.imwrite(output_path, rgb, quality=95)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="RAW to JPG conversion failed.")
+
+ # 4️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 5️⃣ Build dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 RAW → JPG output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 6️⃣ Cleanup input RAW file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+# ---------------- RAW → PNG ----------------
+# ---------------- RAW → PNG ----------------
+import rawpy
+import imageio
+
+@router.post("/raw-to-png")
+async def api_raw_to_png(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate RAW extension
+ allowed_ext = (
+ ".arw", ".cr2", ".cr3", ".dng",
+ ".nef", ".orf", ".raf", ".rw2", ".srw"
+ )
+
+ if not file.filename.lower().endswith(allowed_ext):
+ raise HTTPException(status_code=400, detail="Invalid RAW file.")
+
+ # 2️⃣ Save uploaded RAW file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved RAW:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.png"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 3️⃣ Convert RAW → PNG (High Quality)
+ def _convert():
+ with rawpy.imread(input_path) as raw:
+ rgb = raw.postprocess(
+ use_camera_wb=True,
+ half_size=False,
+ no_auto_bright=False,
+ output_bps=16 # 🔥 16-bit PNG (better than JPG version)
+ )
+ imageio.imwrite(output_path, rgb)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="RAW to PNG conversion failed.")
+
+ # 4️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 5️⃣ Build dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 RAW → PNG output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 6️⃣ Cleanup input RAW file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+# ---------------- RTF → DOCX ----------------
+# ---------------- RTF → DOCX ----------------
+@router.post("/rtf-to-docx")
+async def api_rtf_to_docx(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+
+ try:
+ # 1️⃣ Validate extension
+ if not file.filename.lower().endswith(".rtf"):
+ raise HTTPException(status_code=400, detail="Invalid RTF file.")
+
+ # 2️⃣ Save uploaded RTF
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved RTF:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # 3️⃣ Convert using LibreOffice
+ def _convert():
+ cmd = [
+ "libreoffice",
+ "--headless",
+ "--convert-to", "docx",
+ "--outdir", TMP_DIR,
+ input_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ # LibreOffice keeps same filename but changes extension
+ base_name = os.path.splitext(os.path.basename(input_path))[0]
+ converted_file = os.path.join(TMP_DIR, f"{base_name}.docx")
+
+ if not os.path.exists(converted_file):
+ raise HTTPException(status_code=500, detail="RTF to DOCX conversion failed.")
+
+ # 4️⃣ Rename to UUID for safety
+ uid = str(uuid.uuid4())
+ final_filename = f"{uid}.docx"
+ final_path = os.path.join(OUTPUT_DIR, final_filename)
+
+ os.replace(converted_file, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 5️⃣ Build dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{final_filename}"
+
+ print("📤 RTF → DOCX output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- 7Z → ZIP ----------------
+# ---------------- 7Z → ZIP ----------------
+import shutil
+
+@router.post("/7z-to-zip")
+async def api_7z_to_zip(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ extract_dir = None
+ zip_path = None
+
+ try:
+ # 1️⃣ Validate extension
+ if not file.filename.lower().endswith(".7z"):
+ raise HTTPException(status_code=400, detail="Invalid 7Z file.")
+
+ # 2️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved 7Z:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ extract_dir = os.path.join(TMP_DIR, f"extract_{uid}")
+ os.makedirs(extract_dir, exist_ok=True)
+
+ # 3️⃣ Extract 7Z safely
+ def _extract():
+ cmd = [
+ "7z",
+ "x",
+ input_path,
+ f"-o{extract_dir}",
+ "-y"
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_extract)
+
+ # 4️⃣ Create ZIP from extracted content
+ zip_filename = f"{uid}.zip"
+ zip_path = os.path.join(TMP_DIR, zip_filename)
+
+ def _create_zip():
+ shutil.make_archive(
+ zip_path.replace(".zip", ""),
+ 'zip',
+ extract_dir
+ )
+
+ await run_in_threadpool(_create_zip)
+
+ if not os.path.exists(zip_path):
+ raise HTTPException(status_code=500, detail="ZIP creation failed.")
+
+ # 5️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, zip_filename)
+ os.replace(zip_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 6️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{zip_filename}"
+
+ print("📦 7Z → ZIP output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+ # Cleanup extraction folder
+ if extract_dir and os.path.exists(extract_dir):
+ try:
+ await run_in_threadpool(shutil.rmtree, extract_dir)
+ except:
+ pass
+
+# ---------------- SVG → PDF ----------------
+# ---------------- SVG → PDF ----------------
+import cairosvg
+
+@router.post("/svg-to-pdf")
+async def api_svg_to_pdf(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate file type
+ if not file.filename.lower().endswith(".svg"):
+ raise HTTPException(status_code=400, detail="Invalid SVG file.")
+
+ # 2️⃣ Save uploaded SVG
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved SVG:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.pdf"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 3️⃣ Convert SVG → PDF using CairoSVG
+ def _convert():
+ cairosvg.svg2pdf(
+ url=input_path,
+ write_to=output_path
+ )
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="SVG to PDF conversion failed.")
+
+ # 4️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 5️⃣ Build dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 SVG → PDF output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 6️⃣ Cleanup input SVG
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- SVG → PNG ----------------
+# ---------------- SVG → PNG ----------------
+import cairosvg
+
+@router.post("/svg-to-png")
+async def api_svg_to_png(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate extension
+ if not file.filename.lower().endswith(".svg"):
+ raise HTTPException(status_code=400, detail="Invalid SVG file.")
+
+ # 2️⃣ Save uploaded SVG
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved SVG:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.png"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 3️⃣ Convert SVG → PNG
+ def _convert():
+ cairosvg.svg2png(
+ url=input_path,
+ write_to=output_path,
+ dpi=300 # 🔥 high-quality rendering
+ )
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="SVG to PNG conversion failed.")
+
+ # 4️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 5️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("📤 SVG → PNG output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 6️⃣ Cleanup input SVG
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+# ---------------- TAR → ZIP ----------------
+# ---------------- TAR → ZIP ----------------
+import tarfile
+import shutil
+
+@router.post("/tar-to-zip")
+async def api_tar_to_zip(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ extract_dir = None
+ zip_path = None
+
+ try:
+ # 1️⃣ Validate extension
+ if not file.filename.lower().endswith((".tar", ".tar.gz")):
+ raise HTTPException(status_code=400, detail="Invalid TAR file.")
+
+ # 2️⃣ Save uploaded TAR
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved TAR:", input_path)
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ uid = str(uuid.uuid4())
+ extract_dir = os.path.join(TMP_DIR, f"extract_{uid}")
+ os.makedirs(extract_dir, exist_ok=True)
+
+ # 3️⃣ Extract TAR safely
+ def _extract():
+ with tarfile.open(input_path, "r:*") as tar:
+ for member in tar.getmembers():
+ member_path = os.path.join(extract_dir, member.name)
+
+ # 🔐 Prevent path traversal attack
+ if not os.path.abspath(member_path).startswith(os.path.abspath(extract_dir)):
+ raise Exception("Unsafe archive detected.")
+
+ tar.extractall(path=extract_dir)
+
+ await run_in_threadpool(_extract)
+
+ # 4️⃣ Create ZIP from extracted files
+ zip_filename = f"{uid}.zip"
+ zip_path = os.path.join(TMP_DIR, zip_filename)
+
+ def _create_zip():
+ shutil.make_archive(
+ zip_path.replace(".zip", ""),
+ 'zip',
+ extract_dir
+ )
+
+ await run_in_threadpool(_create_zip)
+
+ if not os.path.exists(zip_path):
+ raise HTTPException(status_code=500, detail="ZIP creation failed.")
+
+ # 5️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, zip_filename)
+ os.replace(zip_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 6️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{zip_filename}"
+
+ print("📦 TAR → ZIP output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # Cleanup input TAR
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+ # Cleanup extracted files
+ if extract_dir and os.path.exists(extract_dir):
+ try:
+ await run_in_threadpool(shutil.rmtree, extract_dir)
+ except:
+ pass
+# ---------------- TEXT → EPUB ----------------
+# ---------------- TEXT → EPUB ----------------
+from ebooklib import epub
+
+@router.post("/text-to-epub")
+async def api_text_to_epub(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate file
+ if not file.filename.lower().endswith(".txt"):
+ raise HTTPException(status_code=400, detail="Invalid TXT file.")
+
+ # 2️⃣ Save uploaded TXT
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved TXT:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.epub"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 3️⃣ Create EPUB
+ def _convert():
+ with open(input_path, "r", encoding="utf-8") as f:
+ text_content = f.read()
+
+ if not text_content.strip():
+ raise ValueError("Text file is empty.")
+
+ book = epub.EpubBook()
+ book.set_identifier(uid)
+ book.set_title(os.path.splitext(file.filename)[0])
+ book.set_language("en")
+
+ # Convert text into HTML paragraphs
+ paragraphs = text_content.split("\n")
+ html_content = "" + book.title + " "
+ for p in paragraphs:
+ if p.strip():
+ html_content += f"{p.strip()}
"
+
+ chapter = epub.EpubHtml(
+ title="Chapter 1",
+ file_name="chapter1.xhtml",
+ content=html_content
+ )
+
+ book.add_item(chapter)
+ book.toc = (epub.Link("chapter1.xhtml", "Chapter 1", "chap1"),)
+ book.add_item(epub.EpubNcx())
+ book.add_item(epub.EpubNav())
+ book.spine = ["nav", chapter]
+
+ epub.write_epub(output_path, book)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="EPUB creation failed.")
+
+ # 4️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 5️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("📚 TXT → EPUB output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 6️⃣ Cleanup input TXT
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- TIFF → JPG ----------------
+@router.post("/tiff-to-jpg")
+async def api_tiff_to_jpg(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded TIFF
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved TIFF:", input_path)
+
+ # Extra validation (backend safety)
+ if not input_path.lower().endswith((".tif", ".tiff")):
+ raise HTTPException(status_code=400, detail="Invalid TIFF file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.jpg"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert TIFF → JPG
+ def _convert():
+ with Image.open(input_path) as img:
+ # Handle multi-page TIFF safely
+ try:
+ if getattr(img, "n_frames", 1) > 1:
+ img.seek(0)
+ except Exception:
+ pass
+
+ rgb = img.convert("RGB") # Required for JPG
+ rgb.save(output_path, "JPEG", quality=95)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="TIFF to JPG conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL (localhost + production safe)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 TIFF → JPG output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- TIFF → PDF ----------------
+@router.post("/tiff-to-pdf")
+async def api_tiff_to_pdf(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded TIFF
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved TIFF:", input_path)
+
+ # Extra validation
+ if not input_path.lower().endswith((".tif", ".tiff")):
+ raise HTTPException(status_code=400, detail="Invalid TIFF file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.pdf"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert TIFF → PDF (supports multi-page TIFF)
+ def _convert():
+ with Image.open(input_path) as img:
+
+ # Collect all frames (for multi-page TIFF)
+ frames = []
+
+ try:
+ for i in range(getattr(img, "n_frames", 1)):
+ img.seek(i)
+ frames.append(img.convert("RGB"))
+ except Exception:
+ frames.append(img.convert("RGB"))
+
+ # Save as PDF
+ if len(frames) > 1:
+ frames[0].save(
+ output_path,
+ save_all=True,
+ append_images=frames[1:]
+ )
+ else:
+ frames[0].save(output_path)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="TIFF to PDF conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL (localhost + production safe)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 TIFF → PDF output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+
+# ---------------- TXT → DOCX ----------------
+from docx import Document
+
+@router.post("/txt-to-docx")
+async def api_txt_to_docx(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded TXT
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved TXT:", input_path)
+
+ # Extra validation
+ if not input_path.lower().endswith(".txt"):
+ raise HTTPException(status_code=400, detail="Invalid TXT file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.docx"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert TXT → DOCX
+ def _convert():
+ document = Document()
+
+ with open(input_path, "r", encoding="utf-8", errors="ignore") as f:
+ for line in f:
+ document.add_paragraph(line.rstrip())
+
+ document.save(output_path)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="TXT to DOCX conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL (localhost + production safe)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 TXT → DOCX output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- TXT → PDF ----------------
+from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
+from reportlab.lib.styles import getSampleStyleSheet
+from reportlab.lib import colors
+from reportlab.lib.units import inch
+
+@router.post("/txt-to-pdf")
+async def api_txt_to_pdf(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ import os
+ import uuid
+ import traceback
+
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save TXT
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved TXT:", input_path)
+
+ if not input_path.lower().endswith(".txt"):
+ raise HTTPException(status_code=400, detail="Invalid TXT file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.pdf"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert TXT → PDF
+ def _convert():
+ doc = SimpleDocTemplate(output_path)
+ styles = getSampleStyleSheet()
+ elements = []
+
+ with open(input_path, "r", encoding="utf-8", errors="ignore") as f:
+ for line in f:
+ text = escape(line.strip()) # ✅ FIX HERE
+
+ if text:
+ elements.append(Paragraph(text, styles["Normal"]))
+ else:
+ elements.append(Spacer(1, 0.2 * inch))
+
+ doc.build(elements)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="TXT to PDF conversion failed.")
+
+ # 3️⃣ Move to output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("📤 TXT → PDF:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- RESIZE VIDEO ----------------
+@router.post("/resize-video")
+async def api_resize_video(
+ request: Request,
+ file: UploadFile = File(...),
+ resolution: str = Form(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Validate resolution
+ resolution_map = {
+ "1080p": "1920:1080",
+ "720p": "1280:720",
+ "480p": "854:480",
+ "360p": "640:360"
+ }
+
+ if resolution not in resolution_map:
+ raise HTTPException(status_code=400, detail="Invalid resolution selected.")
+
+ target_scale = resolution_map[resolution]
+
+ # 2️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved Video:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.mp4"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 3️⃣ Resize video using ffmpeg
+ def _convert():
+ cmd = [
+ "ffmpeg",
+ "-y",
+ "-loglevel", "error",
+ "-i", input_path,
+ "-vf", f"scale={target_scale}:force_original_aspect_ratio=decrease",
+ "-c:v", "libx264",
+ "-preset", "fast",
+ "-crf", "23",
+ "-c:a", "aac",
+ "-b:a", "128k",
+ "-movflags", "+faststart",
+ output_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="Video resize failed.")
+
+ # 4️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 5️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 Video resized:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size,
+ "resolution": resolution
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 6️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- VIDEO → FRAMES (ZIP) ----------------
+@router.post("/video-to-frames")
+async def api_video_to_frames(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ frames_dir = None
+ zip_path = None
+
+ try:
+ # 1️⃣ Save uploaded video
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved Video:", input_path)
+
+ uid = str(uuid.uuid4())
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # Folder to store frames
+ frames_dir = os.path.join(TMP_DIR, f"{uid}_frames")
+ os.makedirs(frames_dir, exist_ok=True)
+
+ # 2️⃣ Extract frames using ffmpeg
+ def _extract():
+ cmd = [
+ "ffmpeg",
+ "-y",
+ "-loglevel", "error",
+ "-i", input_path,
+ os.path.join(frames_dir, "frame_%04d.jpg")
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_extract)
+
+ # Validate frames exist
+ if not os.listdir(frames_dir):
+ raise HTTPException(500, "Frame extraction failed.")
+
+ # 3️⃣ Zip frames
+ zip_filename = f"{uid}.zip"
+ zip_path = os.path.join(TMP_DIR, zip_filename)
+
+ def _zip():
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
+ for filename in sorted(os.listdir(frames_dir)):
+ full_path = os.path.join(frames_dir, filename)
+ zipf.write(full_path, filename)
+
+ await run_in_threadpool(_zip)
+
+ if not os.path.exists(zip_path):
+ raise HTTPException(500, "ZIP creation failed.")
+
+ # 4️⃣ Move ZIP to static/output
+ final_path = os.path.join(OUTPUT_DIR, zip_filename)
+ os.replace(zip_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 5️⃣ Build dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{zip_filename}"
+
+ print("📤 Frames ZIP created:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size,
+ "frames_count": len(os.listdir(frames_dir))
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 6️⃣ Cleanup input video
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+ # Cleanup frames folder
+ if frames_dir and os.path.exists(frames_dir):
+ try:
+ for f in os.listdir(frames_dir):
+ os.remove(os.path.join(frames_dir, f))
+ os.rmdir(frames_dir)
+ except:
+ pass
+
+# ---------------- VIDEO → MP3 ----------------
+@router.post("/video-to-mp3")
+async def api_video_to_mp3(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded video
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved Video:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.mp3"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Extract audio using ffmpeg
+ def _convert():
+ cmd = [
+ "ffmpeg",
+ "-y",
+ "-loglevel", "error",
+ "-i", input_path,
+ "-map", "0:a:0", # first audio stream
+ "-vn", # no video
+ "-acodec", "libmp3lame",
+ "-b:a", "192k",
+ output_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="Video to MP3 conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL (localhost + production safe)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 Video → MP3 output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- VIDEO → MP4 ----------------
+@router.post("/video-to-mp4")
+async def api_video_to_mp4(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded video
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved Video:", input_path)
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.mp4"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert to MP4 using ffmpeg
+ def _convert():
+ cmd = [
+ "ffmpeg",
+ "-y",
+ "-loglevel", "error",
+ "-i", input_path,
+ "-map", "0:v:0",
+ "-map", "0:a?",
+ "-c:v", "libx264",
+ "-preset", "fast",
+ "-crf", "23",
+ "-pix_fmt", "yuv420p",
+ "-movflags", "+faststart",
+ "-c:a", "aac",
+ "-b:a", "128k",
+ output_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="Video to MP4 conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 Video → MP4 output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- WAV → MP3 ----------------
+@router.post("/wav-to-mp3")
+async def api_wav_to_mp3(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded WAV
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved WAV:", input_path)
+
+ # Extra validation
+ if not input_path.lower().endswith(".wav"):
+ raise HTTPException(status_code=400, detail="Invalid WAV file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.mp3"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert WAV → MP3 using ffmpeg
+ def _convert():
+ cmd = [
+ "ffmpeg",
+ "-y",
+ "-loglevel", "error",
+ "-i", input_path,
+ "-vn",
+ "-acodec", "libmp3lame",
+ "-b:a", "192k",
+ output_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="WAV to MP3 conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 WAV → MP3 output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- WEBM → MP4 ----------------
+@router.post("/webm-to-mp4")
+async def api_webm_to_mp4(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded WebM
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved WebM:", input_path)
+
+ # Extra validation
+ if not input_path.lower().endswith(".webm"):
+ raise HTTPException(status_code=400, detail="Invalid WebM file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.mp4"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert WebM → MP4 using ffmpeg
+ def _convert():
+ cmd = [
+ "ffmpeg",
+ "-y",
+ "-loglevel", "error",
+ "-i", input_path,
+ "-map", "0:v:0",
+ "-map", "0:a?",
+ "-c:v", "libx264",
+ "-preset", "fast",
+ "-crf", "23",
+ "-pix_fmt", "yuv420p",
+ "-movflags", "+faststart",
+ "-c:a", "aac",
+ "-b:a", "128k",
+ output_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="WebM to MP4 conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 WebM → MP4 output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- WEBP → AVIF ----------------
+@router.post("/webp-to-avif")
+async def api_webp_to_avif(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded WebP
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved WebP:", input_path)
+
+ # Extra validation
+ if not input_path.lower().endswith(".webp"):
+ raise HTTPException(status_code=400, detail="Invalid WebP file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.avif"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert WebP → AVIF
+ def _convert():
+ with Image.open(input_path) as img:
+ img.save(output_path, "AVIF", quality=50) # Adjust quality as needed
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="WebP to AVIF conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 WebP → AVIF output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- WEBP → JPG ----------------
+@router.post("/webp-to-jpg")
+async def api_webp_to_jpg(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded WebP
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved WebP:", input_path)
+
+ # Extra validation
+ if not input_path.lower().endswith(".webp"):
+ raise HTTPException(status_code=400, detail="Invalid WebP file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.jpg"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert WebP → JPG
+ def _convert():
+ with Image.open(input_path) as img:
+ # JPG doesn't support transparency
+ if img.mode in ("RGBA", "LA"):
+ img = img.convert("RGB")
+ else:
+ img = img.convert("RGB")
+
+ img.save(output_path, "JPEG", quality=95)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="WebP to JPG conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 WebP → JPG output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- WEBP → PNG ----------------
+@router.post("/webp-to-png")
+async def api_webp_to_png(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded WebP
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved WebP:", input_path)
+
+ # Extra validation
+ if not input_path.lower().endswith(".webp"):
+ raise HTTPException(status_code=400, detail="Invalid WebP file.")
+
+ uid = str(uuid.uuid4())
+ output_filename = f"{uid}.png"
+
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert WebP → PNG
+ def _convert():
+ with Image.open(input_path) as img:
+ # Preserve transparency if exists
+ if img.mode in ("RGBA", "LA"):
+ img.save(output_path, "PNG")
+ else:
+ img.convert("RGB").save(output_path, "PNG")
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="WebP to PNG conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 WebP → PNG output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # 5️⃣ Cleanup input file
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- WORD → PDF ----------------
+@router.post("/word-to-pdf")
+async def api_word_to_pdf(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded file
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved Word:", input_path)
+
+ # Validate extension
+ if not input_path.lower().endswith((".doc", ".docx")):
+ raise HTTPException(status_code=400, detail="Invalid Word document.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ # LibreOffice outputs PDF in same folder
+ output_path = os.path.join(TMP_DIR, f"{uid}.pdf")
+
+ # 2️⃣ Convert using LibreOffice headless
+ def _convert():
+ cmd = [
+ "soffice",
+ "--headless",
+ "--convert-to", "pdf",
+ "--outdir", TMP_DIR,
+ input_path
+ ]
+ subprocess.run(cmd, check=True)
+
+ # LibreOffice keeps original filename
+ original_pdf = os.path.join(
+ TMP_DIR,
+ os.path.basename(input_path).rsplit(".", 1)[0] + ".pdf"
+ )
+
+ if os.path.exists(original_pdf):
+ os.rename(original_pdf, output_path)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="Word to PDF conversion failed.")
+
+ # 3️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic base URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 Word → PDF output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # Cleanup input
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+# ---------------- XLS → XLSX ----------------
+
+@router.post("/xls-to-xlsx")
+async def api_xls_to_xlsx(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+
+ try:
+ uid = str(uuid.uuid4())
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ input_path = os.path.join(OUTPUT_DIR, f"{uid}.xls")
+ output_path = os.path.join(OUTPUT_DIR, f"{uid}.xlsx")
+
+ # 1️⃣ Save uploaded file
+ def _save_file():
+ file.file.seek(0)
+ with open(input_path, "wb") as f_out:
+ while True:
+ chunk = file.file.read(65536)
+ if not chunk:
+ break
+ f_out.write(chunk)
+
+ await run_in_threadpool(_save_file)
+ saved_size = os.path.getsize(input_path)
+ print(f"📥 Saved XLS: {input_path} ({saved_size} bytes)")
+
+ # 2️⃣ Validate extension
+ if not file.filename.lower().endswith(".xls"):
+ raise HTTPException(status_code=400, detail="Only .xls files allowed.")
+
+ # 3️⃣ Validate magic bytes
+ with open(input_path, "rb") as f:
+ header = f.read(8)
+ if not header.startswith(b'\xd0\xcf\x11\xe0'):
+ raise HTTPException(status_code=400, detail="Invalid XLS file.")
+
+ # 4️⃣ Size check
+ if saved_size > 50 * 1024 * 1024:
+ raise HTTPException(status_code=400, detail="Max file size is 50MB.")
+
+ # 5️⃣ Convert using xlrd + openpyxl (no LibreOffice)
+ def _convert():
+ import xlrd
+ from openpyxl import Workbook as OWorkbook
+ from openpyxl.utils import get_column_letter
+
+ rb = xlrd.open_workbook(input_path, formatting_info=False)
+ wb = OWorkbook()
+ wb.remove(wb.active) # remove default empty sheet
+
+ for sheet_idx in range(rb.nsheets):
+ rs = rb.sheet_by_index(sheet_idx)
+ ws = wb.create_sheet(title=rs.name)
+
+ for row in range(rs.nrows):
+ for col in range(rs.ncols):
+ cell = rs.cell(row, col)
+ import xlrd as _xlrd
+ # Handle date cells
+ if cell.ctype == _xlrd.XL_CELL_DATE:
+ try:
+ dt = _xlrd.xldate_as_datetime(cell.value, rb.datemode)
+ ws.cell(row=row+1, column=col+1, value=dt)
+ except Exception:
+ ws.cell(row=row+1, column=col+1, value=cell.value)
+ else:
+ ws.cell(row=row+1, column=col+1, value=cell.value)
+
+ wb.save(output_path)
+ print(f"✅ Converted: {output_path}")
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="Conversion failed.")
+
+ size = os.path.getsize(output_path)
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{uid}.xlsx"
+
+ print(f"✅ XLS → XLSX | {size} bytes | {file_url}")
+ return JSONResponse({"url": file_url, "size": size})
+
+ except HTTPException:
+ raise
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path and os.path.exists(input_path):
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+# ---------------- XLSX → CSV ----------------
+import csv
+from openpyxl import load_workbook
+
+@router.post("/xlsx-to-csv")
+async def api_xlsx_to_csv(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded XLSX
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved XLSX:", input_path)
+
+ if not input_path.lower().endswith(".xlsx"):
+ raise HTTPException(status_code=400, detail="Invalid XLSX file.")
+
+ # Optional size limit
+ if os.path.getsize(input_path) > 50 * 1024 * 1024:
+ raise HTTPException(status_code=400, detail="File too large. Max 50MB.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_filename = f"{uid}.csv"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert XLSX → CSV (first sheet only)
+ def _convert():
+ wb = load_workbook(input_path, data_only=True)
+ sheet = wb.active # first sheet
+
+ with open(output_path, "w", newline="", encoding="utf-8") as f:
+ writer = csv.writer(f)
+ for row in sheet.iter_rows(values_only=True):
+ writer.writerow(row)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="XLSX to CSV conversion failed.")
+
+ # 3️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("📤 XLSX → CSV output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- XLSX → HTML ----------------
+from openpyxl import load_workbook
+
+@router.post("/xlsx-to-html")
+async def api_xlsx_to_html(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded XLSX
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved XLSX:", input_path)
+
+ if not input_path.lower().endswith(".xlsx"):
+ raise HTTPException(status_code=400, detail="Invalid XLSX file.")
+
+ # Optional size limit
+ if os.path.getsize(input_path) > 50 * 1024 * 1024:
+ raise HTTPException(status_code=400, detail="File too large. Max 50MB.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_filename = f"{uid}.html"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert XLSX → HTML (first sheet)
+ def _convert():
+ wb = load_workbook(input_path, data_only=True)
+ sheet = wb.active
+
+ with open(output_path, "w", encoding="utf-8") as f:
+ f.write("""
+
+
+
+
+Excel to HTML
+
+
+
+
+""")
+
+ for row_idx, row in enumerate(sheet.iter_rows(values_only=True)):
+ f.write("")
+ for cell in row:
+ value = "" if cell is None else str(cell)
+ tag = "th" if row_idx == 0 else "td"
+ f.write(f"<{tag}>{value}{tag}>")
+ f.write(" \n")
+
+ f.write("""
+
+
+
+""")
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="XLSX to HTML conversion failed.")
+
+ # 3️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("📤 XLSX → HTML output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- XLSX → JSON ----------------
+import json
+from openpyxl import load_workbook
+
+@router.post("/xlsx-to-json")
+async def api_xlsx_to_json(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded XLSX
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved XLSX:", input_path)
+
+ if not input_path.lower().endswith(".xlsx"):
+ raise HTTPException(status_code=400, detail="Invalid XLSX file.")
+
+ # Optional size limit
+ if os.path.getsize(input_path) > 50 * 1024 * 1024:
+ raise HTTPException(status_code=400, detail="File too large. Max 50MB.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_filename = f"{uid}.json"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert XLSX → JSON
+ def _convert():
+ wb = load_workbook(input_path, data_only=True)
+ sheet = wb.active
+
+ rows = list(sheet.iter_rows(values_only=True))
+ if not rows:
+ raise Exception("Empty Excel file.")
+
+ headers = [str(h) if h is not None else f"column_{i}" for i, h in enumerate(rows[0])]
+
+ json_data = []
+ for row in rows[1:]:
+ obj = {}
+ for i, cell in enumerate(row):
+ key = headers[i] if i < len(headers) else f"column_{i}"
+ obj[key] = cell
+ json_data.append(obj)
+
+ with open(output_path, "w", encoding="utf-8") as f:
+ json.dump(json_data, f, indent=4, ensure_ascii=False)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="XLSX to JSON conversion failed.")
+
+ # 3️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("📤 XLSX → JSON output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- XML → CSV ----------------
+import csv
+import xml.etree.ElementTree as ET
+
+@router.post("/xml-to-csv")
+async def api_xml_to_csv(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded XML
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved XML:", input_path)
+
+ if not input_path.lower().endswith(".xml"):
+ raise HTTPException(status_code=400, detail="Invalid XML file.")
+
+ # Optional size limit
+ if os.path.getsize(input_path) > 50 * 1024 * 1024:
+ raise HTTPException(status_code=400, detail="File too large. Max 50MB.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_filename = f"{uid}.csv"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert XML → CSV
+ def _convert():
+ tree = ET.parse(input_path)
+ root = tree.getroot()
+
+ # Try to detect repeating record nodes
+ records = list(root)
+
+ if not records:
+ raise Exception("No records found in XML.")
+
+ rows = []
+ headers = set()
+
+ for record in records:
+ row_data = {}
+
+ # Attributes
+ for attr_key, attr_value in record.attrib.items():
+ row_data[attr_key] = attr_value
+ headers.add(attr_key)
+
+ # Child elements
+ for child in record:
+ row_data[child.tag] = child.text
+ headers.add(child.tag)
+
+ rows.append(row_data)
+
+ headers = list(headers)
+
+ with open(output_path, "w", newline="", encoding="utf-8") as f:
+ writer = csv.DictWriter(f, fieldnames=headers)
+ writer.writeheader()
+ for row in rows:
+ writer.writerow(row)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="XML to CSV conversion failed.")
+
+ # 3️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("📤 XML → CSV output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except ET.ParseError:
+ raise HTTPException(status_code=400, detail="Invalid XML structure.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- XML → PDF ----------------
+import xml.etree.ElementTree as ET
+from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
+from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
+from reportlab.lib import colors
+from reportlab.lib.units import inch
+from reportlab.platypus import Preformatted
+from reportlab.pdfbase.ttfonts import TTFont
+from reportlab.pdfbase import pdfmetrics
+
+@router.post("/xml-to-pdf")
+async def api_xml_to_pdf(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded XML
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved XML:", input_path)
+
+ if not input_path.lower().endswith(".xml"):
+ raise HTTPException(status_code=400, detail="Invalid XML file.")
+
+ if os.path.getsize(input_path) > 50 * 1024 * 1024:
+ raise HTTPException(status_code=400, detail="File too large. Max 50MB.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ output_filename = f"{uid}.pdf"
+ output_path = os.path.join(TMP_DIR, output_filename)
+
+ # 2️⃣ Convert XML → PDF
+ def _convert():
+ tree = ET.parse(input_path)
+ root = tree.getroot()
+
+ doc = SimpleDocTemplate(output_path)
+ elements = []
+
+ styles = getSampleStyleSheet()
+ mono_style = styles["Code"] if "Code" in styles else styles["Normal"]
+
+ def format_xml(element, indent=0):
+ spaces = " " * indent
+ text = f"{spaces}<{element.tag}"
+
+ # Attributes
+ for k, v in element.attrib.items():
+ text += f' {k}="{v}"'
+ text += ">"
+
+ if element.text and element.text.strip():
+ text += element.text.strip()
+
+ lines = [text]
+
+ for child in element:
+ lines.extend(format_xml(child, indent + 1))
+
+ lines.append(f"{spaces}{element.tag}>")
+ return lines
+
+ xml_lines = format_xml(root)
+
+ for line in xml_lines:
+ elements.append(Preformatted(line, mono_style))
+ elements.append(Spacer(1, 0.1 * inch))
+
+ doc.build(elements)
+
+ await run_in_threadpool(_convert)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="XML to PDF conversion failed.")
+
+ # 3️⃣ Move to static/output
+ final_path = os.path.join(OUTPUT_DIR, output_filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ # 4️⃣ Dynamic URL
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{output_filename}"
+
+ print("📤 XML → PDF output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except ET.ParseError:
+ raise HTTPException(status_code=400, detail="Invalid XML structure.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+# ---------------- ZIP → RAR ----------------
+import zipfile
+import shutil
+
+@router.post("/zip-to-rar")
+async def api_zip_to_rar(
+ request: Request,
+ file: UploadFile = File(...),
+ db: Session = Depends(get_db)
+):
+ input_path = None
+ extract_dir = None
+ output_path = None
+
+ try:
+ # 1️⃣ Save uploaded ZIP
+ input_path = await run_in_threadpool(save_upload_file, file)
+ print("📥 Saved ZIP:", input_path)
+
+ if not input_path.lower().endswith(".zip"):
+ raise HTTPException(status_code=400, detail="Invalid ZIP file.")
+
+ if os.path.getsize(input_path) > 200 * 1024 * 1024:
+ raise HTTPException(status_code=400, detail="File too large. Max 200MB.")
+
+ uid = str(uuid.uuid4())
+ TMP_DIR = "tmp"
+ os.makedirs(TMP_DIR, exist_ok=True)
+
+ extract_dir = os.path.join(TMP_DIR, f"extract_{uid}")
+ os.makedirs(extract_dir, exist_ok=True)
+
+ # 2️⃣ Extract ZIP
+ def _extract():
+ with zipfile.ZipFile(input_path, 'r') as zip_ref:
+ zip_ref.extractall(extract_dir)
+
+ await run_in_threadpool(_extract)
+
+ # 3️⃣ Create RAR
+ output_path = os.path.join(TMP_DIR, f"{uid}.rar")
+
+ def _rar():
+ cmd = [
+ "rar",
+ "a", # add files
+ "-ep1", # exclude base path
+ output_path,
+ extract_dir
+ ]
+ subprocess.run(cmd, check=True, timeout=180)
+
+ await run_in_threadpool(_rar)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(status_code=500, detail="RAR creation failed.")
+
+ # 4️⃣ Move to static/output
+ filename = os.path.basename(output_path)
+ final_path = os.path.join(OUTPUT_DIR, filename)
+ os.replace(output_path, final_path)
+
+ size = os.path.getsize(final_path)
+
+ base_url = str(request.base_url).rstrip("/")
+ file_url = f"{base_url}/static/output/{filename}"
+
+ print("📤 ZIP → RAR output:", final_path)
+
+ return JSONResponse({
+ "url": file_url,
+ "size": size
+ })
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(status_code=500, detail="RAR binary not installed or failed.")
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+ finally:
+ # Cleanup
+ if input_path:
+ try:
+ await run_in_threadpool(os.remove, input_path)
+ except:
+ pass
+
+ if extract_dir and os.path.exists(extract_dir):
+ try:
+ await run_in_threadpool(shutil.rmtree, extract_dir)
+ except:
+ pass
+
diff --git a/routers/developer.py b/routers/developer.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d1493f8e36eac719c59471385b9c3414cbaa88f
--- /dev/null
+++ b/routers/developer.py
@@ -0,0 +1,329 @@
+# backend/routers/developer.py
+from fastapi import APIRouter, Form, File, UploadFile, Depends, HTTPException
+from fastapi.responses import FileResponse, JSONResponse
+from sqlalchemy.orm import Session
+from typing import Optional
+import json
+import os
+import tempfile
+import subprocess
+import shutil
+import traceback
+
+from core.database import get_db
+from core.dependencies import LogToolUsage
+from services.developer_service import (
+ format_code_raw,
+ format_code_html,
+ json_pretty,
+ json_minify,
+ json_validate,
+ xml_pretty,
+ xml_validate,
+ sql_format,
+ base64_encode,
+ base64_decode,
+ json_to_csv,
+ analyze_url,
+ regex_test,
+ generate_hash,
+ api_request,
+)
+from utils.file_utils import save_upload_file
+from utils.response_utils import send_file
+from services.stats_service import increment_tool_usage
+
+router = APIRouter()
+
+
+# -----------------------
+# Helper: Prettier Runner
+# -----------------------
+def _find_local_prettier():
+ """
+ Try to find a local prettier binary in node_modules/.bin,
+ or fall back to 'npx prettier' or global 'prettier'.
+ Returns a list (command) suitable for subprocess.run.
+ """
+ # 1) project local node_modules/.bin/prettier
+ local_bin = os.path.join(os.getcwd(), "node_modules", ".bin", "prettier")
+ if os.path.isfile(local_bin) and os.access(local_bin, os.X_OK):
+ return [local_bin]
+
+ # 2) npx (use npx prettier)
+ if shutil.which("npx"):
+ return ["npx", "prettier"]
+
+ # 3) global prettier
+ if shutil.which("prettier"):
+ return ["prettier"]
+
+ return None
+
+
+def run_prettier_on_text(code: str, language: str, timeout: int = 10) -> str:
+ """
+ Run Prettier (if available) to format code. If Prettier is not available or fails,
+ raise HTTPException. Caller may choose to fallback to Python formatter.
+ """
+ cmd_prefix = _find_local_prettier()
+ if not cmd_prefix:
+ raise FileNotFoundError("Prettier not found (install locally with `npm i --save-dev prettier` or make `prettier` available).")
+
+ # Map language to prettier parser
+ parser_map = {
+ "javascript": "babel",
+ "typescript": "typescript",
+ "json": "json",
+ "html": "html",
+ "xml": "html",
+ "css": "css",
+ }
+ parser = parser_map.get(language.lower(), "babel")
+
+ # Prepare temp input file (prettier accepts file path or stdin; we'll use stdin to avoid temp files)
+ try:
+ proc = subprocess.run(
+ cmd_prefix + ["--parser", parser, "--stdin-filepath", f"file.{language}"],
+ input=code.encode("utf-8"),
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ timeout=timeout,
+ )
+ except subprocess.TimeoutExpired as te:
+ raise RuntimeError(f"Prettier timed out: {te}")
+
+ if proc.returncode != 0:
+ stderr = proc.stderr.decode("utf-8", errors="ignore")
+ raise RuntimeError(f"Prettier failed: {stderr.strip() or 'unknown error'}")
+
+ return proc.stdout.decode("utf-8")
+
+
+# ---------------- Code Formatter (Conditional Logging) ----------------
+# We keep manual logging because the tool name / mode may be conditional.
+@router.post("/code/format")
+async def api_code_format(
+ code: str = Form(...),
+ lang: Optional[str] = Form(None),
+ html: bool = Form(False),
+ db: Session = Depends(get_db),
+):
+ """
+ Format provided code string.
+ If html=True, return highlighted HTML output (via format_code_html).
+ Otherwise return raw formatted code.
+ """
+ try:
+ if html:
+ out = format_code_html(code, lang)
+ increment_tool_usage(db, "code_format_html")
+ return {"html": out}
+ else:
+ out = format_code_raw(code, lang)
+ increment_tool_usage(db, "code_format_raw")
+ return {"code": out}
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
+# ---------------- JSON Tools (Conditional Logging) ----------------
+@router.post("/json/format")
+async def api_json_format(text: str = Form(...), minify: bool = Form(False), db: Session = Depends(get_db)):
+ valid, msg = json_validate(text)
+ if not valid:
+ raise HTTPException(status_code=400, detail=msg)
+ try:
+ if minify:
+ out = json_minify(text)
+ increment_tool_usage(db, "json_minify")
+ else:
+ out = json_pretty(text)
+ increment_tool_usage(db, "json_pretty")
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+ return {"result": out}
+
+
+# ---------------- XML Tools (Automatic Logging) ----------------
+@router.post("/xml/format", dependencies=[Depends(LogToolUsage("xml_pretty"))])
+async def api_xml_format(text: str = Form(...), db: Session = Depends(get_db)):
+ valid, msg = xml_validate(text)
+ if not valid:
+ raise HTTPException(status_code=400, detail=msg)
+ try:
+ out = xml_pretty(text)
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+ return {"result": out}
+
+
+# ---------------- SQL Formatter (Automatic Logging) ----------------
+@router.post("/sql/format", dependencies=[Depends(LogToolUsage("sql_format"))])
+async def api_sql_format(query: str = Form(...), db: Session = Depends(get_db)):
+ try:
+ out = sql_format(query)
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+ return {"result": out}
+
+
+# ---------------- Base64 (Automatic Logging) ----------------
+@router.post("/base64/encode", dependencies=[Depends(LogToolUsage("b64_encode"))])
+async def api_b64_encode(text: str = Form(...), db: Session = Depends(get_db)):
+ out = base64_encode(text)
+ return {"result": out}
+
+
+@router.post("/base64/decode", dependencies=[Depends(LogToolUsage("b64_decode"))])
+async def api_b64_decode(text: str = Form(...), db: Session = Depends(get_db)):
+ out = base64_decode(text)
+ return {"result": out}
+
+
+# ---------------- JSON -> CSV (Automatic Logging) ----------------
+@router.post("/json/to-csv", dependencies=[Depends(LogToolUsage("json_to_csv"))])
+async def api_json_to_csv(file: UploadFile = File(...), db: Session = Depends(get_db)):
+ p = save_upload_file(file)
+ try:
+ with open(p, "r", encoding="utf-8") as f:
+ json_content = f.read()
+ out_path = json_to_csv(json_content)
+ finally:
+ try:
+ os.remove(p)
+ except Exception:
+ pass
+ return send_file(out_path)
+
+
+# ---------------- URL Analyzer (Automatic Logging) ----------------
+@router.post("/url/analyze", dependencies=[Depends(LogToolUsage("url_analyze"))])
+async def api_url_analyze(url: str = Form(...), db: Session = Depends(get_db)):
+ try:
+ out = analyze_url(url)
+ except Exception as e:
+ raise HTTPException(status_code=400, detail=str(e))
+ return out
+
+
+# ---------------- Regex Tester (Automatic Logging) ----------------
+@router.post("/regex/test", dependencies=[Depends(LogToolUsage("regex_test"))])
+async def api_regex_test(pattern: str = Form(...), text: str = Form(...), db: Session = Depends(get_db)):
+ out = regex_test(pattern, text)
+ return out
+
+
+# ---------------- Hash Generator (Automatic Logging) ----------------
+@router.post("/hash/generate", dependencies=[Depends(LogToolUsage("hash_generate"))])
+async def api_hash_generate(text: str = Form(...), algo: str = Form("md5"), db: Session = Depends(get_db)):
+ try:
+ out = generate_hash(text, algo)
+ except Exception as e:
+ raise HTTPException(status_code=400, detail=str(e))
+ return {"hash": out}
+
+
+# ---------------- API Tester (Automatic Logging) ----------------
+@router.post("/api/test", dependencies=[Depends(LogToolUsage("api_test"))])
+async def api_api_test(
+ method: str = Form("GET"),
+ url: str = Form(...),
+ headers: Optional[str] = Form(None),
+ params: Optional[str] = Form(None),
+ body: Optional[str] = Form(None),
+ timeout: int = Form(20),
+ db: Session = Depends(get_db),
+):
+ try:
+ hdrs = json.loads(headers) if headers else {}
+ pms = json.loads(params) if params else {}
+ except Exception as e:
+ raise HTTPException(status_code=400, detail="headers/params must be valid JSON if provided: " + str(e))
+
+ out = api_request(method, url, headers=hdrs, params=pms, body=body, timeout=timeout)
+ return out
+
+
+# -------------------------
+# CLEAN /developer/format ENDPOINT
+# -------------------------
+
+from fastapi import UploadFile, File, Form, HTTPException
+from fastapi.responses import FileResponse
+import tempfile
+import subprocess
+import os
+
+@router.post("/format")
+async def format_code_backend(
+ file: UploadFile = File(...),
+ language: str = Form(...)
+):
+ """
+ Accept uploaded code file and format it using Prettier backend.
+ Returns formatted file as FileResponse.
+ """
+
+ # Read uploaded file safely
+ try:
+ raw_code = (await file.read()).decode("utf-8", errors="ignore")
+ except Exception:
+ raise HTTPException(status_code=400, detail="Failed to read uploaded file")
+
+ if not raw_code.strip():
+ raise HTTPException(status_code=400, detail="Empty code input")
+
+ # Temp file for input
+ tmp_in = tempfile.NamedTemporaryFile(delete=False, suffix=".txt")
+ tmp_in.write(raw_code.encode("utf-8"))
+ tmp_in.close()
+
+ # Temp file for output
+ tmp_out = tempfile.NamedTemporaryFile(delete=False, suffix=".txt")
+ tmp_out.close()
+
+ # Language → Prettier parser mapping
+ parser_map = {
+ "javascript": "babel",
+ "json": "json",
+ "html": "html",
+ "xml": "html",
+ "css": "css",
+ }
+ parser = parser_map.get(language, "babel")
+
+ # Run Prettier
+ try:
+ subprocess.run(
+ [
+ "npx", "prettier",
+ "--parser", parser,
+ tmp_in.name
+ ],
+ check=True,
+ stdout=open(tmp_out.name, "w"),
+ stderr=subprocess.PIPE
+ )
+ except subprocess.CalledProcessError as e:
+ error_details = e.stderr.decode() if e.stderr else "Unknown error"
+ raise HTTPException(
+ status_code=400,
+ detail=f"Prettier formatting failed: {error_details}"
+ )
+
+ # Prepare output
+ final_output = tmp_out.name
+
+ # Cleanup input temp file
+ try:
+ os.remove(tmp_in.name)
+ except:
+ pass
+
+ return FileResponse(
+ final_output,
+ media_type="text/plain",
+ filename=f"formatted_{language}.txt"
+ )
+
diff --git a/routers/devtools.py b/routers/devtools.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac8af256e2021b69da2607c58c8b81ee8249ff3b
--- /dev/null
+++ b/routers/devtools.py
@@ -0,0 +1,22 @@
+# routers/devtools.py — UNIVERSAL TOOL TRACKING ENDPOINTS
+
+from fastapi import APIRouter
+
+router = APIRouter(prefix="/devtools")
+
+@router.post("/open")
+async def devtool_open(data: dict):
+ return {"status": "ok", "event": "open"}
+
+@router.post("/process")
+async def devtool_process(data: dict):
+ return {"status": "ok", "event": "process"}
+
+@router.post("/result")
+async def devtool_result(data: dict):
+ return {"status": "ok", "event": "result"}
+
+@router.post("/download")
+async def devtool_download(data: dict):
+ return {"status": "ok", "event": "download"}
+
diff --git a/routers/force-calculation_numbered.pdf b/routers/force-calculation_numbered.pdf
new file mode 100644
index 0000000000000000000000000000000000000000..83e70703c760e53f4313f9a5cffbc95480fda6fc
Binary files /dev/null and b/routers/force-calculation_numbered.pdf differ
diff --git a/routers/image.py b/routers/image.py
new file mode 100644
index 0000000000000000000000000000000000000000..61a9f0429e45c1d4456c5bd6fdd5d1fed8ba3002
--- /dev/null
+++ b/routers/image.py
@@ -0,0 +1,39 @@
+# routers/image.py — CLEAN VERSION (ONLY TRACKING ENDPOINTS)
+
+from fastapi import APIRouter
+
+router = APIRouter()
+
+# ============================================================
+# TOOL OPEN
+# ============================================================
+@router.post("/tool/open")
+async def tool_open(data: dict):
+ return {"status": "ok", "event": "open"}
+
+
+# ============================================================
+# TOOL PROCESS
+# (Frontend may call this even if backend doesn't process images)
+# Always return OK so the frontend fallback works.
+# ============================================================
+@router.post("/tool/process")
+async def tool_process(data: dict):
+ return {"status": "ok", "event": "process"}
+
+
+# ============================================================
+# TOOL RESULT
+# ============================================================
+@router.post("/tool/result")
+async def tool_result(data: dict):
+ return {"status": "ok", "event": "result"}
+
+
+# ============================================================
+# TOOL DOWNLOAD
+# ============================================================
+@router.post("/tool/download")
+async def tool_download(data: dict):
+ return {"status": "ok", "event": "download"}
+
diff --git a/routers/image_tools.py b/routers/image_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..c232b0cf621d26dc0d00e19690fe6afee9847b2e
--- /dev/null
+++ b/routers/image_tools.py
@@ -0,0 +1,1192 @@
+# routers/image_tools.py
+from fastapi import APIRouter, UploadFile, File, Form, HTTPException, Request
+from fastapi.concurrency import run_in_threadpool
+from pydantic import BaseModel
+from PIL import Image
+from PIL import (
+ Image, ImageFilter, ImageEnhance, ImageOps,
+ ImageDraw, ImageFont, ImageColor, ExifTags
+)
+from fastapi.responses import FileResponse
+import tempfile
+import subprocess
+import json
+import os, io, uuid, base64, shutil
+from math import cos, sin, radians
+# ============================================================
+# CONFIG
+# ============================================================
+
+router = APIRouter()
+
+BASE_URL = "https://api.cloudaipdf.com"
+OUTPUT_DIR = "static/output"
+UPLOAD_DIR = "static/uploads"
+TMP_DIR = "/tmp"
+
+os.makedirs(OUTPUT_DIR, exist_ok=True)
+os.makedirs(UPLOAD_DIR, exist_ok=True)
+
+# ============================================================
+# HELPERS
+# ============================================================
+
+def public_url(path: str) -> str:
+ return f"{BASE_URL}{path}"
+
+
+def save_upload_file(file: UploadFile) -> str:
+ path = os.path.join(TMP_DIR, f"{uuid.uuid4().hex}_{file.filename}")
+ with open(path, "wb") as f:
+ shutil.copyfileobj(file.file, f)
+ return path
+
+
+def decode_base64_image(data_url: str) -> Image.Image:
+ try:
+ header, encoded = data_url.split(",", 1)
+ raw = base64.b64decode(encoded)
+ img = Image.open(io.BytesIO(raw))
+ img.load()
+ return img
+ except Exception as e:
+ raise HTTPException(400, f"Invalid base64 image: {e}")
+
+
+def force_white_background(img: Image.Image) -> Image.Image:
+ """
+ ALWAYS returns RGB with white background.
+ No transparency survives.
+ """
+ if img.mode == "RGBA":
+ bg = Image.new("RGB", img.size, (255, 255, 255))
+ bg.paste(img, mask=img.split()[3])
+ return bg.convert("RGB")
+
+ return img.convert("RGB")
+# ============================================================
+# FLIP (BASE64)
+# ============================================================
+
+class FlipPayload(BaseModel):
+ image: str
+ settings: dict
+ format: str = "png"
+
+
+@router.post("/flip")
+async def flip(payload: FlipPayload):
+ img = decode_base64_image(payload.image).convert("RGBA")
+ s = payload.settings or {}
+
+ if s.get("flipHorizontal"):
+ img = img.transpose(Image.FLIP_LEFT_RIGHT)
+ if s.get("flipVertical"):
+ img = img.transpose(Image.FLIP_TOP_BOTTOM)
+
+ rot = int(s.get("rotation", 0))
+ if rot:
+ img = img.rotate(-rot, expand=True)
+
+ img = force_white_background(img)
+
+ name = f"flip_{uuid.uuid4().hex}.png"
+ path = os.path.join(OUTPUT_DIR, name)
+ img.save(path, "PNG")
+
+ return {
+ "url": public_url(f"/static/output/{name}"),
+ "size": os.path.getsize(path)
+ }
+@router.post("/compressor-standard")
+async def compressor_standard(
+ image: UploadFile = File(...),
+ quality: float = Form(0.75),
+ format: str = Form("webp")
+):
+ # -----------------------------
+ # Validate
+ # -----------------------------
+ try:
+ quality = float(quality)
+ quality = max(0.1, min(1.0, quality))
+ except:
+ quality = 0.75
+
+ fmt = format.lower()
+ if fmt not in ("jpeg", "jpg", "png", "webp"):
+ raise HTTPException(status_code=400, detail="Unsupported format")
+
+ # -----------------------------
+ # Save temp
+ # -----------------------------
+ temp_path = os.path.join(TMP_DIR, f"{uuid.uuid4().hex}_{image.filename}")
+ with open(temp_path, "wb") as f:
+ shutil.copyfileobj(image.file, f)
+
+ try:
+ img = Image.open(temp_path)
+ img = force_white_background(img)
+
+ # -----------------------------
+ # Output format
+ # -----------------------------
+ if fmt in ("jpeg", "jpg"):
+ pil_fmt = "JPEG"
+ ext = "jpg"
+ elif fmt == "png":
+ pil_fmt = "PNG"
+ ext = "png"
+ else:
+ pil_fmt = "WEBP"
+ ext = "webp"
+
+ name = f"compressed_{uuid.uuid4().hex}.{ext}"
+ out_path = os.path.join(UPLOAD_DIR, name)
+
+ save_args = {}
+ if pil_fmt in ("JPEG", "WEBP"):
+ save_args["quality"] = int(quality * 100)
+ if pil_fmt == "JPEG":
+ save_args["optimize"] = True
+
+ img.save(out_path, pil_fmt, **save_args)
+
+ return {
+ "url": f"{BASE_URL}/static/uploads/{name}",
+ "size": os.path.getsize(out_path),
+ "quality": quality,
+ "format": ext
+ }
+
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=f"Compression failed: {str(e)}")
+
+ finally:
+ try:
+ os.remove(temp_path)
+ except:
+ pass
+# ============================================================
+# REMOVE BACKGROUND (UPLOAD) – KEEP TRANSPARENT
+# ============================================================
+
+
+
+# ============================================================
+# COMPRESS IMAGE (UPLOAD)
+# ============================================================
+
+@router.post("/compress-image")
+async def compress_image(
+ file: UploadFile = File(...),
+ target: str = Form("jpg"),
+ quality: float = Form(0.8)
+):
+ q = max(0.1, min(1.0, float(quality)))
+ temp = save_upload_file(file)
+
+ try:
+ img = Image.open(temp)
+ img = force_white_background(img)
+
+ ext = target.lower()
+ fmt = "JPEG" if ext in ("jpg", "jpeg") else "PNG"
+ out_ext = "jpg" if fmt == "JPEG" else "png"
+
+ name = f"compressed_{uuid.uuid4().hex}.{out_ext}"
+ path = os.path.join(UPLOAD_DIR, name)
+
+ if fmt == "JPEG":
+ img.save(path, "JPEG", quality=int(q * 100))
+ else:
+ img.save(path, "PNG")
+
+ return {
+ "url": public_url(f"/static/uploads/{name}"),
+ "size": os.path.getsize(path)
+ }
+ finally:
+ os.remove(temp)
+
+# ============================================================
+# UPSCALE (UPLOAD)
+# ============================================================
+# --- helper: fill background when requested ----
+def fill_background(img: Image.Image, color: str):
+ if img.mode != "RGBA":
+ img = img.convert("RGBA")
+
+ bg = Image.new("RGB", img.size, color)
+ bg.paste(img, mask=img.split()[3])
+ return bg
+
+
+# -----------------------------------------------
+# UPSCALE ENDPOINT
+# -----------------------------------------------
+@router.post("/upscale")
+async def upscale(
+ image: UploadFile = File(...),
+ factor: str = Form("auto"),
+ backgroundColor: str = Form("white"),
+ apply_background: str = Form("1") # 1 = fill, 0 = keep transparent
+):
+ temp_path = os.path.join(TMP_DIR, f"{uuid.uuid4().hex}_{image.filename}")
+
+ try:
+ with open(temp_path, "wb") as f:
+ shutil.copyfileobj(image.file, f)
+
+ img = Image.open(temp_path).convert("RGBA")
+ w, h = img.size
+
+ # auto upscale logic
+ if factor == "auto":
+ scale = 4 if max(w, h) < 800 else 2
+ else:
+ try:
+ scale = max(1, int(factor))
+ except ValueError:
+ raise HTTPException(400, "Invalid upscale factor")
+
+ img = img.resize((w * scale, h * scale), Image.LANCZOS)
+
+ # -------- BACKGROUND OPTION --------
+ if apply_background == "1":
+ img = fill_background(img, backgroundColor)
+ ext = "jpg"
+ pil_fmt = "JPEG"
+ else:
+ ext = "png"
+ pil_fmt = "PNG"
+
+ name = f"upscale_{uuid.uuid4().hex}.{ext}"
+ out_path = os.path.join(UPLOAD_DIR, name)
+
+ img.save(out_path, pil_fmt, quality=95)
+
+ return {
+ "url": f"{BASE_URL}/static/uploads/{name}",
+ "path": name
+ }
+
+ finally:
+ try:
+ os.remove(temp_path)
+ except:
+ pass
+
+
+# -----------------------------------------------
+# FORCE DOWNLOAD (FIXES ANDROID / iOS BROWSER)
+# -----------------------------------------------
+@router.get("/download-upscaled")
+async def download_upscaled(path: str):
+ filename = os.path.basename(path)
+ full_path = os.path.join(UPLOAD_DIR, filename)
+
+ if not os.path.exists(full_path):
+ raise HTTPException(404, "File not found")
+
+ return FileResponse(
+ full_path,
+ media_type="application/octet-stream",
+ filename=filename
+ )
+
+
+
+@router.post("/blur-advanced")
+async def blur_advanced(
+ image: UploadFile = File(...),
+ blur: int = Form(0),
+ blurMode: str = Form("normal"),
+ pixelSize: int = Form(8),
+ brightness: int = Form(100),
+ contrast: int = Form(100),
+ saturation: int = Form(100),
+ temperature: int = Form(0),
+ format: str = Form("png"),
+ backgroundColor: str = Form("#ffffff"),
+ apply_background: str = Form("0"),
+):
+ temp_path = os.path.join(TMP_DIR, f"{uuid.uuid4().hex}_{image.filename}")
+
+ def fill_background(img, color):
+ if img.mode != "RGBA":
+ img = img.convert("RGBA")
+
+ bg = Image.new("RGBA", img.size, color)
+ bg.paste(img, mask=img.split()[3])
+ return bg
+
+ try:
+ # Save upload temporarily
+ with open(temp_path, "wb") as f:
+ shutil.copyfileobj(image.file, f)
+
+ img = Image.open(temp_path)
+
+ # Normalize base mode
+ img = img.convert("RGBA") if img.mode in ("RGBA", "LA") else img.convert("RGB")
+
+ # --- BLUR MODES ---
+ if blurMode == "gaussian":
+ img = img.filter(ImageFilter.GaussianBlur(radius=blur))
+
+ elif blurMode == "pixelate":
+ pixel = max(2, min(64, pixelSize))
+ small = img.resize(
+ (max(1, img.width // pixel), max(1, img.height // pixel)),
+ Image.NEAREST,
+ )
+ img = small.resize((img.width, img.height), Image.NEAREST)
+
+ else:
+ img = img.filter(ImageFilter.BoxBlur(blur))
+
+ # --- ADJUSTMENTS ---
+ img = ImageEnhance.Brightness(img).enhance(brightness / 100)
+ img = ImageEnhance.Contrast(img).enhance(contrast / 100)
+ img = ImageEnhance.Color(img).enhance(saturation / 100)
+
+ # handle formats + background
+ ext = format.lower()
+ should_fill = apply_background == "1"
+ bg_color = backgroundColor
+
+ if ext in ("jpg", "jpeg"):
+ img = fill_background(img, bg_color)
+ pil_fmt = "JPEG"
+ ext = "jpg"
+
+ elif should_fill:
+ img = fill_background(img, bg_color)
+ pil_fmt = "PNG" if ext == "png" else "WEBP"
+
+ else:
+ pil_fmt = "PNG" if ext == "png" else "WEBP"
+
+ # save output
+ name = f"blur_{uuid.uuid4().hex}.{ext}"
+ out_path = os.path.join(UPLOAD_DIR, name)
+
+ img.save(out_path, pil_fmt, quality=92)
+
+ return {
+ "url": f"{BASE_URL}/static/uploads/{name}",
+ "size": os.path.getsize(out_path)
+ }
+
+ finally:
+ if os.path.exists(temp_path):
+ os.remove(temp_path)
+
+# ============================================================
+# SHARPEN (BASE64)
+# ============================================================
+
+@router.post("/sharpen")
+async def sharpen(payload: dict):
+ img = decode_base64_image(payload["image"])
+ img = img.filter(ImageFilter.UnsharpMask(radius=2, percent=150))
+ img = force_white_background(img)
+
+ name = f"sharpen_{uuid.uuid4().hex}.png"
+ path = os.path.join(OUTPUT_DIR, name)
+ img.save(path, "PNG")
+
+ return {"url": public_url(f"/static/output/{name}")}
+
+# ============================================================
+# GRAYSCALE
+# ============================================================
+
+@router.post("/grayscale")
+async def grayscale(request: Request):
+ body = await request.json()
+ img = decode_base64_image(body["image"]).convert("RGB")
+ img = ImageOps.grayscale(img).convert("RGB")
+
+ name = f"gray_{uuid.uuid4().hex}.png"
+ path = os.path.join(OUTPUT_DIR, name)
+ img.save(path, "PNG")
+
+ return {"url": public_url(f"/static/output/{name}")}
+
+# ============================================================
+# ROTATE
+# ============================================================
+
+@router.post("/rotate-advanced")
+async def rotate(request: Request):
+ body = await request.json()
+ img = decode_base64_image(body["image"]).convert("RGBA")
+ deg = float(body.get("degrees", 0))
+
+ img = img.rotate(-deg, expand=True)
+ img = force_white_background(img)
+
+ name = f"rotate_{uuid.uuid4().hex}.png"
+ path = os.path.join(OUTPUT_DIR, name)
+ img.save(path, "PNG")
+
+ return {"url": public_url(f"/static/output/{name}")}
+
+# ============================================================
+# CROP
+# ============================================================
+
+@router.post("/crop")
+async def crop(request: Request):
+ body = await request.json()
+ img = decode_base64_image(body["image"])
+
+ s = body["settings"]
+ img = img.crop((s["x"], s["y"], s["x"] + s["width"], s["y"] + s["height"]))
+ img = force_white_background(img)
+
+ name = f"crop_{uuid.uuid4().hex}.png"
+ path = os.path.join(OUTPUT_DIR, name)
+ img.save(path, "PNG")
+
+ return {"url": public_url(f"/static/output/{name}")}
+
+# ============================================================
+# RESIZE
+# =====================================================
+@router.post("/resize-image")
+async def resize_image(
+ file: UploadFile = File(...),
+ width: int = Form(...),
+ height: int = Form(...),
+ target: str = Form("jpg"),
+ quality: float = Form(0.9)
+):
+ """
+ Server-side image resizer
+ - preserves quality
+ - supports JPEG / PNG / WEBP
+ - produces mobile-friendly file sizes
+ """
+
+ temp_path = os.path.join(TMP_DIR, f"{uuid.uuid4().hex}_{file.filename}")
+
+ try:
+ # Save upload
+ with open(temp_path, "wb") as f:
+ shutil.copyfileobj(file.file, f)
+
+ img = Image.open(temp_path)
+
+ # resize
+ width = max(1, int(width))
+ height = max(1, int(height))
+ img = img.resize((width, height), Image.LANCZOS)
+
+ # ---------- format handling ----------
+ target = target.lower()
+ if target in ("jpg", "jpeg"):
+ img = force_white_background(img)
+ pil_fmt = "JPEG"
+ ext = "jpg"
+ elif target == "webp":
+ pil_fmt = "WEBP"
+ ext = "webp"
+ else:
+ pil_fmt = "PNG"
+ ext = "png"
+
+ name = f"resized_{uuid.uuid4().hex}.{ext}"
+ out_path = os.path.join(UPLOAD_DIR, name)
+
+ # compression (keeps quality, speeds mobile download)
+ save_args = {}
+ if pil_fmt in ("JPEG", "WEBP"):
+ save_args["quality"] = int(float(quality) * 100)
+ save_args["optimize"] = True
+
+ img.save(out_path, pil_fmt, **save_args)
+
+ return {
+ "url": f"{BASE_URL}/static/uploads/{name}",
+ "size": os.path.getsize(out_path),
+ "width": width,
+ "height": height,
+ "format": ext
+ }
+
+ except Exception as e:
+ raise HTTPException(500, f"Resize failed: {str(e)}")
+
+ finally:
+ if os.path.exists(temp_path):
+ os.remove(temp_path)
+
+
+
+
+@router.post("/convert")
+async def convert_image(
+ image: UploadFile = File(...),
+ format: str = Form(...),
+ quality: float = Form(0.92)
+):
+ # -----------------------------
+ # Validate format
+ # -----------------------------
+ format = format.lower()
+
+ FORMAT_MAP = {
+ "image/jpeg": ("JPEG", "jpg"),
+ "image/jpg": ("JPEG", "jpg"),
+ "image/png": ("PNG", "png"),
+ "image/webp": ("WEBP", "webp"),
+ "image/bmp": ("BMP", "bmp"),
+ }
+
+ if format not in FORMAT_MAP:
+ raise HTTPException(400, "Unsupported output format")
+
+ pil_format, ext = FORMAT_MAP[format]
+
+ try:
+ quality = float(quality)
+ quality = max(0.1, min(1.0, quality))
+ except:
+ quality = 0.92
+
+ # -----------------------------
+ # Save temp file
+ # -----------------------------
+ temp_path = os.path.join(TMP_DIR, f"{uuid.uuid4().hex}_{image.filename}")
+ with open(temp_path, "wb") as f:
+ shutil.copyfileobj(image.file, f)
+
+ try:
+ img = Image.open(temp_path)
+
+ # -----------------------------
+ # Transparency handling
+ # -----------------------------
+ if pil_format in ("JPEG", "BMP"):
+ img = force_white_background(img)
+ else:
+ img = img.convert("RGBA") if img.mode == "RGBA" else img.convert("RGB")
+
+ # -----------------------------
+ # Save output
+ # -----------------------------
+ name = f"converted_{uuid.uuid4().hex}.{ext}"
+ out_path = os.path.join(UPLOAD_DIR, name)
+
+ save_args = {}
+ if pil_format in ("JPEG", "WEBP"):
+ save_args["quality"] = int(quality * 100)
+ save_args["optimize"] = True
+
+ img.save(out_path, pil_format, **save_args)
+
+ return {
+ "url": f"{BASE_URL}/static/uploads/{name}",
+ "size": os.path.getsize(out_path),
+ "format": ext
+ }
+
+ except Exception as e:
+ raise HTTPException(500, f"Conversion failed: {str(e)}")
+
+ finally:
+ try:
+ os.remove(temp_path)
+ except:
+ pass
+
+
+# ============================================================
+# REMOVE BACKGROUND (PRODUCTION SAFE)
+# ============================================================
+
+
+@router.post("/remove-bg")
+async def remove_bg(image: UploadFile = File(...)):
+ """
+ Ultra-safe background remover
+ - disk-based
+ - Cloudflare safe
+ - prevents black background
+ """
+
+ # ----------------------------
+ # Validate
+ # ----------------------------
+ if not image.content_type or not image.content_type.startswith("image/"):
+ raise HTTPException(status_code=400, detail="Invalid image file")
+
+ try:
+ from rembg import remove
+ except Exception:
+ raise HTTPException(status_code=500, detail="rembg not installed")
+
+ temp_path = os.path.join(
+ TMP_DIR,
+ f"{uuid.uuid4().hex}_{image.filename}"
+ )
+
+ try:
+ # ----------------------------
+ # Save file FIRST
+ # ----------------------------
+ with open(temp_path, "wb") as f:
+ shutil.copyfileobj(image.file, f)
+
+ # ----------------------------
+ # Load image SAFELY
+ # ----------------------------
+ with Image.open(temp_path) as img:
+ img = img.convert("RGBA")
+ img.load() # 🚨 force decode NOW
+
+ # ----------------------------
+ # Run rembg in thread
+ # ----------------------------
+ out = await run_in_threadpool(remove, img)
+
+ # ----------------------------
+ # Save output
+ # ----------------------------
+ filename = f"nobg_{uuid.uuid4().hex}.png"
+ out_path = os.path.join(UPLOAD_DIR, filename)
+ out.save(out_path, "PNG")
+
+ return {
+ "url": f"{BASE_URL}/static/uploads/{filename}",
+ "size": os.path.getsize(out_path)
+ }
+
+ except Exception as e:
+ # NEVER leak internals to client
+ raise HTTPException(
+ status_code=500,
+ detail="Background removal failed. Try a different image."
+ )
+
+ finally:
+ try:
+ os.remove(temp_path)
+ except:
+ pass
+# ============================================================
+# REQUEST SCHEMA (MATCHES FRONTEND)
+# ============================================================
+
+class ContrastPayload(BaseModel):
+ image: str # base64 data URL
+ fileName: str | None = None
+ settings: dict
+ format: str = "png"
+
+
+# ============================================================
+# IMAGE CONTRAST ENDPOINT
+# ============================================================
+
+@router.post("/contrast")
+async def adjust_contrast(payload: ContrastPayload):
+ try:
+ # -----------------------------
+ # Decode Base64
+ # -----------------------------
+ if "," in payload.image:
+ _, b64data = payload.image.split(",", 1)
+ else:
+ b64data = payload.image
+
+ raw = base64.b64decode(b64data)
+ img = Image.open(io.BytesIO(raw)).convert("RGB")
+
+ # -----------------------------
+ # Contrast Logic
+ # -----------------------------
+ contrast_value = int(payload.settings.get("contrast", 0))
+ factor = max(0.0, min(2.0, 1.0 + contrast_value / 100))
+
+ img = ImageEnhance.Contrast(img).enhance(factor)
+
+ # -----------------------------
+ # Output format
+ # -----------------------------
+ ext = payload.format.lower().replace(".", "")
+ if ext not in ("png", "jpg", "jpeg", "webp"):
+ ext = "png"
+
+ filename = f"contrast_{uuid.uuid4().hex}.{ext}"
+ out_path = os.path.join(UPLOAD_DIR, filename) # ✅ FIXED
+
+ if ext in ("jpg", "jpeg"):
+ img.save(out_path, "JPEG", quality=92)
+ elif ext == "webp":
+ img.save(out_path, "WEBP", quality=92)
+ else:
+ img.save(out_path, "PNG")
+
+ return {
+ "url": f"{BASE_URL}/static/uploads/{filename}", # ✅ MATCHES
+ "size": os.path.getsize(out_path)
+ }
+
+ except Exception as e:
+ raise HTTPException(500, f"Contrast processing failed: {str(e)}")
+
+
+# ============================================================
+# IMAGE FILTERS (SEPIA / VINTAGE / COOL / ETC)
+# ============================================================
+
+class FilterPayload(BaseModel):
+ image: str # base64 data URL
+ filter: str
+ intensity: int = 100 # 0–100
+
+
+@router.post("/filter")
+async def apply_filter(payload: FilterPayload):
+ try:
+ # -----------------------------
+ # Decode base64 image
+ # -----------------------------
+ if "," in payload.image:
+ _, b64data = payload.image.split(",", 1)
+ else:
+ b64data = payload.image
+
+ raw = base64.b64decode(b64data)
+ img = Image.open(io.BytesIO(raw)).convert("RGB")
+
+ intensity = max(0, min(100, int(payload.intensity)))
+ strength = intensity / 100
+
+ # -----------------------------
+ # FILTER LOGIC
+ # -----------------------------
+ f = payload.filter.lower()
+
+ if f == "sepia":
+ sepia = ImageOps.colorize(
+ ImageOps.grayscale(img),
+ black="#704214",
+ white="#C0A080"
+ )
+ img = Image.blend(img, sepia, strength)
+
+ elif f == "vintage":
+ img = ImageEnhance.Color(img).enhance(0.8)
+ img = ImageEnhance.Contrast(img).enhance(0.9)
+
+ elif f == "cool":
+ r, g, b = img.split()
+ b = b.point(lambda i: min(255, i + 20 * strength))
+ img = Image.merge("RGB", (r, g, b))
+
+ elif f == "warm":
+ r, g, b = img.split()
+ r = r.point(lambda i: min(255, i + 20 * strength))
+ img = Image.merge("RGB", (r, g, b))
+
+ elif f == "noir":
+ img = ImageOps.grayscale(img)
+ img = ImageEnhance.Contrast(img).enhance(1.3)
+
+ elif f == "fade":
+ img = ImageEnhance.Contrast(img).enhance(0.85)
+ img = ImageEnhance.Brightness(img).enhance(1.05)
+
+ elif f == "hdr":
+ img = ImageEnhance.Contrast(img).enhance(1.4)
+ img = ImageEnhance.Color(img).enhance(1.3)
+
+ elif f == "lomo":
+ img = ImageEnhance.Color(img).enhance(1.4)
+ img = ImageEnhance.Contrast(img).enhance(1.3)
+
+ # else: keep original
+
+ # -----------------------------
+ # Save output
+ # -----------------------------
+ filename = f"filter_{f}_{uuid.uuid4().hex}.png"
+ out_path = os.path.join(UPLOAD_DIR, filename)
+ img.save(out_path, "PNG")
+
+ return {
+ "url": f"{BASE_URL}/static/uploads/{filename}",
+ "size": os.path.getsize(out_path)
+ }
+
+ except Exception as e:
+ raise HTTPException(500, f"Filter processing failed: {str(e)}")
+
+
+# ============================================================
+# EXIF METADATA (FULL – EXIFTOOL)
+# ============================================================
+
+class ExifPayload(BaseModel):
+ image: str
+ fileName: str | None = "image"
+
+
+def save_base64_to_temp(image_b64: str) -> str:
+ if "," in image_b64:
+ _, image_b64 = image_b64.split(",", 1)
+
+ image_b64 = image_b64.replace("\n", "").replace("\r", "").strip()
+
+ try:
+ raw = base64.b64decode(image_b64, validate=True)
+ except Exception:
+ raise HTTPException(400, "Invalid base64 image")
+
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".img", dir=TMP_DIR)
+ tmp.write(raw)
+ tmp.close()
+
+ return tmp.name
+
+
+@router.post("/exif")
+async def extract_full_metadata(payload: ExifPayload):
+ tmp_path = None
+ try:
+ tmp_path = save_base64_to_temp(payload.image)
+
+ proc = subprocess.run(
+ ["exiftool", "-json", "-G", "-a", "-u", tmp_path],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True
+ )
+
+ if proc.returncode != 0:
+ raise HTTPException(500, proc.stderr)
+
+ data = json.loads(proc.stdout)[0]
+
+ return {
+ "fileName": payload.fileName,
+ "metadata": data
+ }
+
+ finally:
+ if tmp_path and os.path.exists(tmp_path):
+ os.remove(tmp_path)
+
+
+@router.post("/exif/pdf")
+async def exif_to_pdf(payload: ExifPayload):
+ from reportlab.lib.pagesizes import A4
+ from reportlab.pdfgen import canvas
+
+ tmp_img = None
+ tmp_pdf = None
+
+ try:
+ tmp_img = save_base64_to_temp(payload.image)
+
+ proc = subprocess.run(
+ ["exiftool", "-G", "-a", "-u", tmp_img],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True
+ )
+
+ lines = proc.stdout.splitlines() or ["No metadata found"]
+
+ tmp_pdf = os.path.join(TMP_DIR, f"exif_{uuid.uuid4().hex}.pdf")
+
+ c = canvas.Canvas(tmp_pdf, pagesize=A4)
+ w, h = A4
+ y = h - 40
+
+ c.setFont("Helvetica-Bold", 14)
+ c.drawString(40, y, "Image Metadata Report")
+ y -= 30
+
+ c.setFont("Helvetica", 9)
+ c.drawString(40, y, f"File: {payload.fileName}")
+ y -= 20
+
+ for line in lines:
+ if y < 40:
+ c.showPage()
+ c.setFont("Helvetica", 9)
+ y = h - 40
+ c.drawString(40, y, line[:120])
+ y -= 12
+
+ c.save()
+
+ return FileResponse(
+ tmp_pdf,
+ media_type="application/pdf",
+ filename=f"{payload.fileName.split('.')[0]}_metadata.pdf"
+ )
+
+ finally:
+ if tmp_img and os.path.exists(tmp_img):
+ os.remove(tmp_img)
+@router.post("/exif/strip")
+async def strip_metadata(payload: ExifPayload):
+ tmp_img = None
+ out_img = None
+
+ try:
+ tmp_img = save_base64_to_temp(payload.image)
+
+ out_img = os.path.join(
+ UPLOAD_DIR,
+ f"clean_{uuid.uuid4().hex}.png"
+ )
+
+ # 🔥 STRIP EVERYTHING
+ proc = subprocess.run(
+ [
+ "exiftool",
+ "-all=", # remove all metadata
+ "-overwrite_original",
+ tmp_img
+ ],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True
+ )
+
+ if proc.returncode != 0:
+ raise HTTPException(500, proc.stderr)
+
+ shutil.copy(tmp_img, out_img)
+
+ return {
+ "url": f"{BASE_URL}/static/uploads/{os.path.basename(out_img)}",
+ "status": "metadata_removed"
+ }
+
+ finally:
+ if tmp_img and os.path.exists(tmp_img):
+ os.remove(tmp_img)
+@router.post("/exif/ai-detect")
+async def detect_ai_image(payload: ExifPayload):
+ tmp_img = None
+
+ try:
+ tmp_img = save_base64_to_temp(payload.image)
+
+ proc = subprocess.run(
+ ["exiftool", "-json", "-G", "-a", "-u", tmp_img],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True
+ )
+
+ data = json.loads(proc.stdout)[0]
+
+ ai_signals = []
+ text = json.dumps(data).lower()
+
+ AI_KEYWORDS = [
+ "c2pa",
+ "trainedalgorithmicmedia",
+ "generative",
+ "firefly",
+ "dall-e",
+ "stable diffusion",
+ "midjourney",
+ "google ai",
+ "adobe",
+ "xmp:creatorTool"
+ ]
+
+ for k in AI_KEYWORDS:
+ if k in text:
+ ai_signals.append(k)
+
+ return {
+ "is_ai_generated": len(ai_signals) > 0,
+ "confidence": "high" if len(ai_signals) > 2 else "medium",
+ "signals": ai_signals,
+ }
+
+ finally:
+ if tmp_img and os.path.exists(tmp_img):
+ os.remove(tmp_img)
+@router.post("/adjust-brightness")
+async def adjust_brightness(
+ file: UploadFile = File(...),
+ brightness: int = Form(0),
+ format: str = Form("png")
+):
+ temp_path = os.path.join(TMP_DIR, f"{uuid.uuid4().hex}_{file.filename}")
+
+ try:
+ # Save upload
+ with open(temp_path, "wb") as f:
+ shutil.copyfileobj(file.file, f)
+
+ # Load image
+ img = Image.open(temp_path)
+
+ # Convert safely
+ if img.mode in ("RGBA", "LA"):
+ img = img.convert("RGBA")
+ else:
+ img = img.convert("RGB")
+
+ # Brightness range: -100 → +100
+ brightness = max(-100, min(100, int(brightness)))
+
+ # Convert to Pillow factor
+ # 0 => 1.0 (no change)
+ # +100 => 2.0
+ # -100 => 0.0
+ factor = 1.0 + (brightness / 100.0)
+
+ enhancer = ImageEnhance.Brightness(img)
+ img = enhancer.enhance(factor)
+
+ # Handle output format
+ ext = format.lower()
+ if ext not in ("png", "jpg", "jpeg", "webp"):
+ ext = "png"
+
+ if ext in ("jpg", "jpeg"):
+ img = force_white_background(img)
+ pil_fmt = "JPEG"
+ ext = "jpg"
+ elif ext == "webp":
+ pil_fmt = "WEBP"
+ else:
+ pil_fmt = "PNG"
+
+ name = f"brightness_{uuid.uuid4().hex}.{ext}"
+ out_path = os.path.join(UPLOAD_DIR, name)
+
+ save_args = {}
+ if pil_fmt in ("JPEG", "WEBP"):
+ save_args["quality"] = 92
+ save_args["optimize"] = True
+
+ img.save(out_path, pil_fmt, **save_args)
+
+ return {
+ "url": f"{BASE_URL}/static/uploads/{name}",
+ "size": os.path.getsize(out_path),
+ "brightness": brightness
+ }
+
+ except Exception as e:
+ raise HTTPException(500, f"Brightness adjustment failed: {str(e)}")
+
+ finally:
+ try:
+ os.remove(temp_path)
+ except:
+ pass
+class ColorAdjustPayload(BaseModel):
+ image: str
+ saturation: int = 100 # 0–200
+ temperature: int = 0 # -100–100
+ hue: int = 0 # -180–180
+ grayscale: bool = False
+
+
+@router.post("/color-adjust")
+async def color_adjust(payload: ColorAdjustPayload):
+ try:
+ # -----------------------------
+ # Decode base64 image
+ # -----------------------------
+ if "," in payload.image:
+ _, b64data = payload.image.split(",", 1)
+ else:
+ b64data = payload.image
+
+ raw = base64.b64decode(b64data)
+ img = Image.open(io.BytesIO(raw)).convert("RGB")
+
+ # -----------------------------
+ # Grayscale
+ # -----------------------------
+ if payload.grayscale:
+ img = ImageOps.grayscale(img).convert("RGB")
+
+ # -----------------------------
+ # Saturation
+ # -----------------------------
+ sat = max(0, min(200, payload.saturation))
+ img = ImageEnhance.Color(img).enhance(sat / 100.0)
+
+ # -----------------------------
+ # Temperature (warm / cool)
+ # -----------------------------
+ if payload.temperature != 0:
+ r, g, b = img.split()
+ temp = max(-100, min(100, payload.temperature))
+
+ if temp > 0:
+ r = r.point(lambda i: min(255, i + temp))
+ b = b.point(lambda i: max(0, i - temp))
+ else:
+ r = r.point(lambda i: max(0, i + temp))
+ b = b.point(lambda i: min(255, i - temp))
+
+ img = Image.merge("RGB", (r, g, b))
+
+ # -----------------------------
+ # Hue rotation
+ # -----------------------------
+ if payload.hue != 0:
+ hue = radians(payload.hue)
+ cos_h = cos(hue)
+ sin_h = sin(hue)
+
+ def rotate_hue(pixel):
+ r, g, b = pixel
+ nr = int(
+ (.213 + cos_h * .787 - sin_h * .213) * r +
+ (.715 - cos_h * .715 - sin_h * .715) * g +
+ (.072 - cos_h * .072 + sin_h * .928) * b
+ )
+ ng = int(
+ (.213 - cos_h * .213 + sin_h * .143) * r +
+ (.715 + cos_h * .285 + sin_h * .140) * g +
+ (.072 - cos_h * .072 - sin_h * .283) * b
+ )
+ nb = int(
+ (.213 - cos_h * .213 - sin_h * .787) * r +
+ (.715 - cos_h * .715 + sin_h * .715) * g +
+ (.072 + cos_h * .928 + sin_h * .072) * b
+ )
+ return (
+ max(0, min(255, nr)),
+ max(0, min(255, ng)),
+ max(0, min(255, nb)),
+ )
+
+ pixels = list(img.getdata())
+ img.putdata([rotate_hue(p) for p in pixels])
+
+ # -----------------------------
+ # Save output
+ # -----------------------------
+ name = f"color_adjust_{uuid.uuid4().hex}.png"
+ out_path = os.path.join(UPLOAD_DIR, name)
+ img.save(out_path, "PNG")
+
+ return {
+ "url": f"{BASE_URL}/static/uploads/{name}",
+ "size": os.path.getsize(out_path)
+ }
+
+ except Exception as e:
+ raise HTTPException(500, f"Color adjustment failed: {str(e)}")
diff --git a/routers/network_tools.py b/routers/network_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..852abb989fae8afc1f2c3635fc42922aaaf37c3a
--- /dev/null
+++ b/routers/network_tools.py
@@ -0,0 +1,340 @@
+from fastapi import APIRouter, HTTPException, Query
+import subprocess
+import platform
+import dns.resolver
+from mac_vendor_lookup import MacLookup
+import socket
+import asyncio
+import hashlib
+from datetime import datetime, timezone
+import subprocess
+import re
+import ssl
+import httpx
+
+from cryptography import x509
+from cryptography.hazmat.backends import default_backend
+from cryptography.hazmat.primitives import hashes
+from cryptography.hazmat.primitives.asymmetric import rsa, ec, dsa
+
+router = APIRouter()
+
+from fastapi import APIRouter, HTTPException, Query
+import subprocess
+import platform
+import dns.resolver
+from mac_vendor_lookup import MacLookup
+import socket
+import asyncio
+import hashlib
+from datetime import datetime, timezone
+import subprocess
+import re
+import ssl
+import httpx
+
+from cryptography import x509
+from cryptography.hazmat.backends import default_backend
+from cryptography.hazmat.primitives import hashes
+from cryptography.hazmat.primitives.asymmetric import rsa, ec, dsa
+
+router = APIRouter()
+
+# Function to convert timezone-aware datetime to naive
+def convert_to_naive(dt: datetime) -> datetime:
+ if dt.tzinfo is not None:
+ return dt.astimezone(timezone.utc).replace(tzinfo=None) # Convert to naive
+ return dt # Already naive, no changes needed
+
+# Function to fetch certificate chain (simplified)
+def fetch_certificate_chain(domain: str):
+ ctx = ssl.create_default_context()
+ cert_chain = []
+
+ try:
+ with socket.create_connection((domain, 443)) as sock:
+ with ctx.wrap_socket(sock, server_hostname=domain) as ssock:
+ cert_bin = ssock.getpeercert(binary_form=True)
+ cert = x509.load_der_x509_certificate(cert_bin, default_backend())
+ cert_chain.append(cert)
+ # Add intermediate certs and root certs here if available
+ except Exception as e:
+ return {"error": f"Failed to fetch certificate chain: {str(e)}"}
+
+ return cert_chain
+
+# Consolidated endpoint for SSL, OCSP, Certificate Chain, Protocols and Ciphers
+@router.get("/decoderssh")
+async def ssl_details(domain: str = Query(...)):
+ ctx = ssl.create_default_context()
+
+ try:
+ clean_domain = domain.replace("https://", "").replace("http://", "").split('/')[0].split(':')[0]
+
+ # Establish a connection and fetch certificate
+ with socket.create_connection((clean_domain, 443), timeout=5) as sock:
+ with ctx.wrap_socket(sock, server_hostname=clean_domain) as ssock:
+ cert_bin = ssock.getpeercert(binary_form=True)
+ cert = x509.load_der_x509_certificate(cert_bin, default_backend())
+
+ # Fingerprints and Public Key Details
+ sha256 = hashlib.sha256(cert_bin).hexdigest().upper()
+ sha1 = hashlib.sha1(cert_bin).hexdigest().upper()
+ pub_key = cert.public_key()
+ key_size = getattr(pub_key, 'key_size', 'Unknown')
+ key_type = pub_key.__class__.__name__.replace('RSAPublicKey', 'RSA').replace('EllipticCurvePublicKey', 'EC')
+
+ # Extended Key Usage and Revocation Check
+ extended_key_usage = []
+ try:
+ eku_ext = cert.extensions.get_extension_for_oid(x509.ExtensionOID.EXTENDED_KEY_USAGE)
+ extended_key_usage = eku_ext.value
+ except Exception:
+ pass
+
+ # Convert to naive datetime objects to avoid timezone issues
+ not_before_naive = convert_to_naive(cert.not_valid_before_utc)
+ not_after_naive = convert_to_naive(cert.not_valid_after_utc)
+
+ # Get certificate chain
+ cert_chain = fetch_certificate_chain(domain)
+ if "error" in cert_chain:
+ raise HTTPException(status_code=400, detail=cert_chain["error"])
+
+ # Get protocols and ciphers
+ with socket.create_connection((clean_domain, 443)) as sock:
+ with ctx.wrap_socket(sock, server_hostname=clean_domain) as ssock:
+ supported_protocol = ssock.version()
+ supported_ciphers = ssock.cipher()
+
+ # Placeholder for OCSP status (to be improved with real OCSP checks)
+ ocsp_status = "OCSP Status: Valid"
+
+ # Return detailed certificate info
+ return {
+ "domain": domain,
+ "subject": {attr.oid._name: str(attr.value) for attr in cert.subject},
+ "issuer": {attr.oid._name: str(attr.value) for attr in cert.issuer},
+ "validity": {
+ "notBefore": not_before_naive.isoformat(),
+ "notAfter": not_after_naive.isoformat(),
+ "days_remaining": (not_after_naive - datetime.now()).days
+ },
+ "serialNumber": format(cert.serial_number, 'X'),
+ "fingerprints": {"sha256": sha256, "sha1": sha1},
+ "key_info": f"{key_type} {key_size} bits",
+ "extendedKeyUsage": [str(eku) for eku in extended_key_usage],
+ "certificateChain": [str(cert.subject) for cert in cert_chain],
+ "revocationStatus": ocsp_status,
+ "protocols": supported_protocol,
+ "ciphers": supported_ciphers
+ }
+ except Exception as e:
+ raise HTTPException(status_code=400, detail=f"Failed to fetch certificate details: {str(e)}")
+
+
+
+
+@router.get("/mac-lookup")
+async def mac_address_lookup(mac: str = Query(...)):
+ try:
+ url = f"https://api.macvendors.com/{mac}"
+
+ async with httpx.AsyncClient(timeout=10) as client:
+ r = await client.get(url)
+
+ if r.status_code == 200:
+ vendor = r.text
+ else:
+ vendor = "Private / Randomized MAC"
+
+ return {
+ "mac": mac,
+ "vendor": vendor
+ }
+
+ except Exception:
+ return {
+ "mac": mac,
+ "vendor": "Lookup failed"
+ }
+
+@router.get("/ping")
+async def ping_host(host: str = Query(...)):
+
+ try:
+ # Windows vs Linux ping command
+ param = "-n" if platform.system().lower() == "windows" else "-c"
+
+ cmd = ["ping", param, "4", host]
+
+ result = subprocess.run(
+ cmd,
+ capture_output=True,
+ text=True,
+ timeout=10
+ )
+
+ return {
+ "pingResult": result.stdout or result.stderr
+ }
+
+ except Exception:
+ raise HTTPException(
+ status_code=500,
+ detail="Ping failed"
+ )
+
+@router.get("/dns-lookup")
+async def dns_lookup(domain: str = Query(...), type: str = Query("A")):
+ try:
+ answers = dns.resolver.resolve(domain, type)
+ records = [str(r.to_text()) for r in answers]
+
+ return {
+ "recordType": type,
+ "records": records
+ }
+
+ except dns.resolver.NoAnswer:
+ return {
+ "recordType": type,
+ "records": [],
+ "message": "No records found for this type"
+ }
+
+ except Exception:
+ raise HTTPException(
+ status_code=400,
+ detail="DNS lookup failed"
+ )
+
+
+# Safe predefined ports (web / mail / ssh etc.)
+COMMON_PORTS = [
+ 21, 22, 25, 53,
+ 80, 110, 143,
+ 443, 465, 587,
+ 993, 995,
+ 3306, 3389,
+ 8080, 8443
+]
+
+
+async def scan_port(host: str, port: int):
+ try:
+ conn = asyncio.open_connection(host, port)
+ reader, writer = await asyncio.wait_for(conn, timeout=1)
+ writer.close()
+ return port
+ except:
+ return None
+
+
+@router.get("/port-scan")
+async def port_scan(host: str = Query(...)):
+ try:
+ tasks = [scan_port(host, p) for p in COMMON_PORTS]
+ results = await asyncio.gather(*tasks)
+
+ open_ports = [p for p in results if p]
+
+ if not open_ports:
+ output = "No common open ports detected."
+ else:
+ output = "Open ports:\n" + "\n".join(str(p) for p in open_ports)
+
+ return {
+ "host": host,
+ "open_ports": open_ports,
+ "scanResult": output
+ }
+
+ except Exception:
+ raise HTTPException(
+ status_code=400,
+ detail="Unable to scan host"
+ )
+
+
+@router.get("/ssl-check")
+async def ssl_check(domain: str = Query(...)):
+
+ ctx = ssl.create_default_context()
+
+ try:
+ with ctx.wrap_socket(socket.socket(), server_hostname=domain) as s:
+ s.settimeout(5)
+ s.connect((domain, 443))
+
+ cert = s.getpeercert()
+
+ except Exception:
+ raise HTTPException(
+ status_code=400,
+ detail="Unable to fetch SSL certificate"
+ )
+
+ issuer = dict(x[0] for x in cert.get("issuer", []))
+ subject = dict(x[0] for x in cert.get("subject", []))
+
+ return {
+ "domain": domain,
+ "issuer": issuer.get("organizationName", "Unknown"),
+ "subject": subject.get("commonName", "Unknown"),
+ "validFrom": cert.get("notBefore"),
+ "validTo": cert.get("notAfter")
+ }
+
+@router.get("/traceroute")
+async def traceroute(host: str = Query(...)):
+
+ try:
+ # run traceroute safely
+ result = subprocess.run(
+ ["traceroute", "-m", "20", host],
+ capture_output=True,
+ text=True,
+ timeout=25
+ )
+
+ if result.returncode != 0:
+ raise HTTPException(
+ status_code=400,
+ detail="Traceroute failed"
+ )
+
+ return {
+ "traceResult": result.stdout
+ }
+
+ except subprocess.TimeoutExpired:
+ raise HTTPException(
+ status_code=400,
+ detail="Traceroute timeout"
+ )
+
+@router.get("/whois")
+async def whois_lookup(domain: str = Query(...)):
+
+ # basic validation (important)
+ if not re.match(r"^[a-zA-Z0-9\.\-]+$", domain):
+ raise HTTPException(status_code=400, detail="Invalid domain")
+
+ try:
+ result = subprocess.run(
+ ["whois", domain],
+ capture_output=True,
+ text=True,
+ timeout=20
+ )
+
+ if result.returncode != 0:
+ raise HTTPException(status_code=400, detail="WHOIS lookup failed")
+
+ return {
+ "whoisRecord": result.stdout
+ }
+
+ except subprocess.TimeoutExpired:
+ raise HTTPException(status_code=400, detail="WHOIS timeout")
diff --git a/routers/pdf.py b/routers/pdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..108401695675ccf55f135134d2abe3d6fe0e5cb4
--- /dev/null
+++ b/routers/pdf.py
@@ -0,0 +1,2183 @@
+# routers/pdf.py
+from fastapi import (
+ APIRouter,
+ UploadFile,
+ File,
+ Form,
+ HTTPException,
+ Request,
+ Query,
+)
+import math
+import json
+import pikepdf
+import io
+from fastapi.concurrency import run_in_threadpool
+from typing import List
+import os
+import uuid
+import subprocess
+from typing import List
+from pypdf import PdfReader, PdfWriter
+from pypdf.errors import PdfReadError
+from PIL import Image, ImageFile, ImageFont, ImageDraw
+from typing import Optional
+import pytesseract
+from pdf2image import convert_from_path
+from reportlab.pdfgen import canvas
+from reportlab.lib.utils import ImageReader
+from reportlab.lib.colors import HexColor
+from reportlab.lib.pagesizes import letter
+from typing import Set
+from fastapi.responses import FileResponse
+import fitz # PyMuPDF
+import tempfile
+import json
+from fastapi.responses import StreamingResponse
+import base64
+from reportlab.lib.colors import black
+
+ImageFile.LOAD_TRUNCATED_IMAGES = True
+
+router = APIRouter(tags=["PDF Tools"])
+
+# --------------------------------------------------
+# DIRECTORIES
+# --------------------------------------------------
+TEMP_DIR = "/tmp/pdf_tools"
+STATIC_DIR = "static/pdf"
+
+os.makedirs(TEMP_DIR, exist_ok=True)
+os.makedirs(STATIC_DIR, exist_ok=True)
+
+# --------------------------------------------------
+# HELPERS
+# --------------------------------------------------
+def safe_remove(path: str):
+ try:
+ os.remove(path)
+ except Exception:
+ pass
+
+# ==================================================
+# =============== PDF COMPRESS =====================
+# ==================================================
+
+# Adobe-style semantics:
+# Low → Best quality (may be 0%)
+# Medium → Balanced
+# High → Smallest size (most compression)
+PRESET_MAP = {
+ "low": "/prepress",
+ "medium": "/ebook",
+ "high": "/screen",
+}
+
+def ghostscript_compress(
+ input_path: str,
+ output_path: str,
+ preset: str,
+ aggressive: bool = False,
+):
+ cmd = [
+ "gs",
+ "-sDEVICE=pdfwrite",
+ "-dCompatibilityLevel=1.4",
+ f"-dPDFSETTINGS={preset}",
+ "-dNOPAUSE",
+ "-dQUIET",
+ "-dBATCH",
+ ]
+
+ # Extra aggressive downsampling ONLY for "high"
+ if aggressive:
+ cmd += [
+ "-dDownsampleColorImages=true",
+ "-dColorImageResolution=72",
+ "-dDownsampleGrayImages=true",
+ "-dGrayImageResolution=72",
+ "-dDownsampleMonoImages=true",
+ "-dMonoImageResolution=72",
+ "-dDetectDuplicateImages=true",
+ "-dCompressFonts=true",
+ ]
+
+ cmd += [
+ f"-sOutputFile={output_path}",
+ input_path,
+ ]
+
+ result = subprocess.run(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+
+ if result.returncode != 0:
+ raise RuntimeError(result.stderr.decode(errors="ignore"))
+
+@router.post("/compress")
+async def pdf_compress(
+ request: Request,
+ file: UploadFile = File(...),
+ level: str = Form("medium"),
+):
+ if file.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files are supported")
+
+ preset = PRESET_MAP.get(level, "/ebook")
+ aggressive = level == "high"
+ base_url = str(request.base_url).rstrip("/")
+
+ input_path = os.path.join(TEMP_DIR, f"{uuid.uuid4()}.pdf")
+ compressed_name = f"compressed_{uuid.uuid4().hex}.pdf"
+ compressed_path = os.path.join(STATIC_DIR, compressed_name)
+
+ try:
+ # Save original
+ with open(input_path, "wb") as f:
+ f.write(await file.read())
+
+ original_size = os.path.getsize(input_path)
+
+ # Compress
+ await run_in_threadpool(
+ ghostscript_compress,
+ input_path,
+ compressed_path,
+ preset,
+ aggressive,
+ )
+
+ if not os.path.exists(compressed_path):
+ raise HTTPException(500, "Compression failed")
+
+ compressed_size = os.path.getsize(compressed_path)
+
+ # Adobe-style fallback: never return worse file
+ if compressed_size >= original_size:
+ safe_remove(compressed_path)
+
+ final_name = f"original_{uuid.uuid4().hex}.pdf"
+ final_path = os.path.join(STATIC_DIR, final_name)
+ os.rename(input_path, final_path)
+
+ return {
+ "url": f"{base_url}/static/pdf/{final_name}",
+ "size": original_size,
+ "note": "Best quality preserved. No compression applied.",
+ }
+
+ return {
+ "url": f"{base_url}/static/pdf/{compressed_name}",
+ "size": compressed_size,
+ }
+
+ except Exception as e:
+ raise HTTPException(500, f"Compression error: {str(e)}")
+
+ finally:
+ if os.path.exists(input_path):
+ safe_remove(input_path)
+
+# ==================================================
+# ================ PDF MERGE =======================
+# ==================================================
+
+@router.post("/merge")
+async def pdf_merge(
+ request: Request,
+ file: List[UploadFile] = File(...),
+):
+ if len(file) < 2:
+ raise HTTPException(400, "At least two PDF files are required")
+
+ base_url = str(request.base_url).rstrip("/")
+ writer = PdfWriter()
+
+ temp_paths: List[str] = []
+ output_name = f"merged_{uuid.uuid4().hex}.pdf"
+ output_path = os.path.join(STATIC_DIR, output_name)
+
+ try:
+ for f in file:
+ if f.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files are allowed")
+
+ temp_path = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ temp_paths.append(temp_path)
+
+ with open(temp_path, "wb") as out:
+ out.write(await f.read())
+
+ try:
+ reader = PdfReader(temp_path)
+
+ # 🔒 BLOCK PASSWORD-PROTECTED PDFs (Adobe behavior)
+ if reader.is_encrypted:
+ raise HTTPException(
+ status_code=400,
+ detail="One or more PDFs are password-protected. Please unlock them before merging.",
+ )
+
+ for page in reader.pages:
+ writer.add_page(page)
+
+ except PdfReadError:
+ raise HTTPException(
+ status_code=400,
+ detail="Invalid or corrupted PDF detected. Please re-export or unlock the file.",
+ )
+
+ with open(output_path, "wb") as final_pdf:
+ writer.write(final_pdf)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "PDF merge failed")
+
+ return {
+ "url": f"{base_url}/static/pdf/{output_name}"
+ }
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ raise HTTPException(500, f"Merge error: {str(e)}")
+
+ finally:
+ for path in temp_paths:
+ safe_remove(path)
+
+# ==================================================
+# ================ PDF SPLIT / EXTRACT ==============
+# ==================================================
+
+@router.post("/split")
+async def pdf_split(
+ request: Request,
+ file: UploadFile = File(...),
+ pages: str = Form(...),
+):
+ if file.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files are supported")
+
+ base_url = str(request.base_url).rstrip("/")
+ temp_input = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ output_name = f"split_{uuid.uuid4().hex}.pdf"
+ output_path = os.path.join(STATIC_DIR, output_name)
+
+ try:
+ # ----------------------------------
+ # SAVE INPUT PDF
+ # ----------------------------------
+ with open(temp_input, "wb") as f:
+ f.write(await file.read())
+
+ # ----------------------------------
+ # PARSE PAGE NUMBERS (1-based → 0-based)
+ # ----------------------------------
+ try:
+ page_numbers = [
+ int(p.strip()) - 1
+ for p in pages.split(",")
+ if p.strip().isdigit()
+ ]
+ except Exception:
+ raise HTTPException(400, "Invalid page selection")
+
+ if not page_numbers:
+ raise HTTPException(400, "No pages selected")
+
+ reader = PdfReader(temp_input)
+
+ # 🔒 Block encrypted PDFs (Adobe behavior)
+ if reader.is_encrypted:
+ raise HTTPException(
+ status_code=400,
+ detail="This PDF is password-protected. Please unlock it before splitting.",
+ )
+
+ writer = PdfWriter()
+ total_pages = len(reader.pages)
+
+ for p in page_numbers:
+ if p < 0 or p >= total_pages:
+ raise HTTPException(400, "Selected page out of range")
+ writer.add_page(reader.pages[p])
+
+ # ----------------------------------
+ # WRITE OUTPUT PDF
+ # ----------------------------------
+ with open(output_path, "wb") as out:
+ writer.write(out)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "PDF split failed")
+
+ return {
+ "url": f"{base_url}/static/pdf/{output_name}"
+ }
+
+ except PdfReadError:
+ raise HTTPException(
+ status_code=400,
+ detail="Invalid or corrupted PDF file",
+ )
+
+ except HTTPException:
+ raise
+
+ except Exception as e:
+ raise HTTPException(500, f"Split error: {str(e)}")
+
+ finally:
+ safe_remove(temp_input)
+
+
+# ==================================================
+# ============ UNIVERSAL MERGE (PDF + IMAGES) ======
+# ==================================================
+
+@router.post("/universal-merge")
+async def pdf_universal_merge(
+ request: Request,
+ file: List[UploadFile] = File(...),
+):
+ if not file:
+ raise HTTPException(400, "No files provided")
+
+ base_url = str(request.base_url).rstrip("/")
+ writer = PdfWriter()
+
+ temp_paths: List[str] = []
+ output_name = f"merged_{uuid.uuid4().hex}.pdf"
+ output_path = os.path.join(STATIC_DIR, output_name)
+
+ try:
+ for f in file:
+ temp_path = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}")
+ temp_paths.append(temp_path)
+
+ with open(temp_path, "wb") as out:
+ out.write(await f.read())
+
+ # ----------------------------------
+ # PDF FILE
+ # ----------------------------------
+ if f.content_type == "application/pdf":
+ try:
+ reader = PdfReader(temp_path)
+
+ # 🔒 Block encrypted PDFs (Adobe-like)
+ if reader.is_encrypted:
+ raise HTTPException(
+ status_code=400,
+ detail="One or more PDFs are password-protected. Please unlock them before merging.",
+ )
+
+ for page in reader.pages:
+ writer.add_page(page)
+
+ except PdfReadError:
+ raise HTTPException(
+ status_code=400,
+ detail="Invalid or corrupted PDF detected.",
+ )
+
+ # ----------------------------------
+ # IMAGE FILE
+ # ----------------------------------
+ elif f.content_type.startswith("image/"):
+ try:
+ img = Image.open(temp_path).convert("RGB")
+
+ img_pdf_path = f"{temp_path}.pdf"
+ img.save(img_pdf_path)
+
+ img_reader = PdfReader(img_pdf_path)
+ writer.add_page(img_reader.pages[0])
+
+ temp_paths.append(img_pdf_path)
+
+ except Exception:
+ raise HTTPException(
+ status_code=400,
+ detail="Unsupported or corrupted image file.",
+ )
+
+ else:
+ raise HTTPException(
+ status_code=400,
+ detail="Unsupported file type. Only PDFs and images are allowed.",
+ )
+
+ # ----------------------------------
+ # WRITE FINAL MERGED PDF
+ # ----------------------------------
+ with open(output_path, "wb") as final_pdf:
+ writer.write(final_pdf)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "Merge failed")
+
+ return {
+ "url": f"{base_url}/static/pdf/{output_name}"
+ }
+
+ except HTTPException:
+ raise
+
+ except Exception as e:
+ raise HTTPException(500, f"Merge error: {str(e)}")
+
+ finally:
+ for path in temp_paths:
+ try:
+ os.remove(path)
+ except Exception:
+ pass
+
+
+# ==================================================
+# ================= PDF CROP =======================
+# ==================================================
+
+@router.post("/crop")
+async def pdf_crop(
+ request: Request,
+ file: UploadFile = File(...),
+
+ # crop box (PDF points)
+ x: float = Form(...),
+ y: float = Form(...),
+ width: float = Form(...),
+ height: float = Form(...),
+
+ # apply scope
+ scope: str = Form("all"), # all | current | range
+ page: Optional[int] = Form(None),
+ range: Optional[str] = Form(None),
+):
+ if file.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files are supported")
+
+ base_url = str(request.base_url).rstrip("/")
+ temp_input = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ output_name = f"cropped_{uuid.uuid4().hex}.pdf"
+ output_path = os.path.join(STATIC_DIR, output_name)
+
+ try:
+ # ----------------------------------
+ # SAVE INPUT
+ # ----------------------------------
+ with open(temp_input, "wb") as f:
+ f.write(await file.read())
+
+ reader = PdfReader(temp_input)
+
+ # 🔒 block encrypted PDFs
+ if reader.is_encrypted:
+ raise HTTPException(
+ status_code=400,
+ detail="PDF is password-protected. Please unlock it first.",
+ )
+
+ writer = PdfWriter()
+ total_pages = len(reader.pages)
+
+ # ----------------------------------
+ # DETERMINE PAGES TO CROP
+ # ----------------------------------
+ pages_to_crop = set()
+
+ if scope == "all":
+ pages_to_crop = set(range(total_pages))
+
+ elif scope == "current":
+ if page is None or page < 0 or page >= total_pages:
+ raise HTTPException(400, "Invalid page number")
+ pages_to_crop.add(page)
+
+ elif scope == "range":
+ if not range:
+ raise HTTPException(400, "Range is required")
+
+ parts = range.split(",")
+ for p in parts:
+ if "-" in p:
+ s, e = p.split("-")
+ for i in range(int(s) - 1, int(e)):
+ if 0 <= i < total_pages:
+ pages_to_crop.add(i)
+ else:
+ i = int(p) - 1
+ if 0 <= i < total_pages:
+ pages_to_crop.add(i)
+
+ else:
+ raise HTTPException(400, "Invalid scope")
+
+ # ----------------------------------
+ # APPLY CROP
+ # ----------------------------------
+ for idx, page_obj in enumerate(reader.pages):
+ if idx in pages_to_crop:
+ page_height = page_obj.mediabox.height
+
+ # PDF origin is bottom-left
+ crop_y = page_height - y - height
+
+ page_obj.cropbox.lower_left = (x, crop_y)
+ page_obj.cropbox.upper_right = (x + width, crop_y + height)
+
+ writer.add_page(page_obj)
+
+ # ----------------------------------
+ # WRITE OUTPUT
+ # ----------------------------------
+ with open(output_path, "wb") as out:
+ writer.write(out)
+
+ return {
+ "url": f"{base_url}/static/pdf/{output_name}",
+ "size": os.path.getsize(output_path),
+ }
+
+ except PdfReadError:
+ raise HTTPException(400, "Invalid or corrupted PDF")
+
+ except Exception as e:
+ raise HTTPException(500, f"Crop error: {str(e)}")
+
+ finally:
+ safe_remove(temp_input)
+
+
+# ==================================================
+# ================= PDF OCR ========================
+# ==================================================
+
+def run_ocr(input_pdf: str, output_pdf: str, text_file: str):
+ images = convert_from_path(input_pdf, dpi=300)
+
+ writer = PdfWriter()
+ extracted_text = []
+
+ for img in images:
+ # OCR text
+ text = pytesseract.image_to_string(img)
+ extracted_text.append(text)
+
+ # OCR PDF page
+ pdf_bytes = pytesseract.image_to_pdf_or_hocr(img, extension="pdf")
+ page_reader = PdfReader(io.BytesIO(pdf_bytes))
+ writer.add_page(page_reader.pages[0])
+
+ # Write searchable PDF
+ with open(output_pdf, "wb") as f:
+ writer.write(f)
+
+ # Write text file
+ with open(text_file, "w", encoding="utf-8") as f:
+ f.write("\n\n".join(extracted_text))
+
+
+@router.post("/ocr")
+async def pdf_ocr(
+ request: Request,
+ file: UploadFile = File(...),
+):
+ if file.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files are supported")
+
+ base_url = str(request.base_url).rstrip("/")
+
+ input_pdf = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ output_pdf = os.path.join(STATIC_DIR, f"ocr_{uuid.uuid4().hex}.pdf")
+ text_file = os.path.join(STATIC_DIR, f"text_{uuid.uuid4().hex}.txt")
+
+ try:
+ # Save input
+ with open(input_pdf, "wb") as f:
+ f.write(await file.read())
+
+ reader = PdfReader(input_pdf)
+
+ # 🔒 Block encrypted PDFs
+ if reader.is_encrypted:
+ raise HTTPException(
+ status_code=400,
+ detail="PDF is password-protected. Please unlock it before OCR.",
+ )
+
+ # 🔥 RUN OCR OFF EVENT LOOP
+ await run_in_threadpool(
+ run_ocr,
+ input_pdf,
+ output_pdf,
+ text_file,
+ )
+
+ return {
+ "url": f"{base_url}/static/pdf/{os.path.basename(output_pdf)}",
+ "textUrl": f"{base_url}/static/pdf/{os.path.basename(text_file)}",
+ "size": os.path.getsize(output_pdf),
+ "message": "OCR Complete! Document is now searchable.",
+ }
+
+ except Exception as e:
+ raise HTTPException(500, f"OCR error: {str(e)}")
+
+ finally:
+ safe_remove(input_pdf)
+
+# ==================================================
+# ============ PDF ADD PAGE NUMBERS =================
+# ==================================================
+
+@router.post("/info")
+async def pdf_info(file: UploadFile = File(...)):
+ if file.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files allowed")
+
+ temp_path = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+
+ try:
+ with open(temp_path, "wb") as f:
+ f.write(await file.read())
+
+ reader = PdfReader(temp_path)
+
+ if reader.is_encrypted:
+ raise HTTPException(400, "PDF is password-protected")
+
+ return {
+ "pageCount": len(reader.pages)
+ }
+
+ except PdfReadError:
+ raise HTTPException(400, "Invalid or corrupted PDF")
+
+ finally:
+ if os.path.exists(temp_path):
+ os.remove(temp_path)
+
+def _render_preview(input_pdf: str, page: int, output_path: str):
+ images = convert_from_path(
+ input_pdf,
+ dpi=150,
+ first_page=page,
+ last_page=page,
+ )
+ images[0].save(output_path, "PNG")
+
+
+@router.post("/preview")
+async def pdf_preview(
+ request: Request,
+ file: UploadFile = File(...),
+ page: int = Form(...),
+):
+ if file.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files allowed")
+
+ base_url = str(request.base_url).rstrip("/")
+
+ temp_pdf = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ image_name = f"preview_{uuid.uuid4().hex}.png"
+ image_path = os.path.join(STATIC_DIR, image_name)
+
+ try:
+ with open(temp_pdf, "wb") as f:
+ f.write(await file.read())
+
+ reader = PdfReader(temp_pdf)
+ if reader.is_encrypted:
+ raise HTTPException(400, "PDF is password-protected")
+
+ await run_in_threadpool(
+ _render_preview,
+ temp_pdf,
+ page,
+ image_path,
+ )
+
+ return {
+ "url": f"{base_url}/static/pdf/{image_name}"
+ }
+
+ finally:
+ if os.path.exists(temp_pdf):
+ os.remove(temp_pdf)
+
+@router.post("/page-numbers")
+async def add_page_numbers(
+ request: Request,
+ file: UploadFile = File(...),
+ pagesConfig: str = Form(...),
+):
+ if file.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files allowed")
+
+ base_url = str(request.base_url).rstrip("/")
+
+ temp_pdf = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ overlay_pdf = os.path.join(TEMP_DIR, f"overlay_{uuid.uuid4().hex}.pdf")
+ output_name = f"page_numbers_{uuid.uuid4().hex}.pdf"
+ output_path = os.path.join(STATIC_DIR, output_name)
+
+ try:
+ with open(temp_pdf, "wb") as f:
+ f.write(await file.read())
+
+ reader = PdfReader(temp_pdf)
+ if reader.is_encrypted:
+ raise HTTPException(400, "PDF is password-protected")
+
+ try:
+ configs = json.loads(pagesConfig)
+ except Exception:
+ raise HTTPException(400, "Invalid pagesConfig JSON")
+
+ total_pages = len(reader.pages)
+
+ if len(configs) != total_pages:
+ raise HTTPException(
+ 400,
+ "pagesConfig length must match page count",
+ )
+
+ # ---------- CREATE OVERLAY ----------
+ c = canvas.Canvas(overlay_pdf)
+
+ for i, page in enumerate(reader.pages):
+ width = float(page.mediabox.width)
+ height = float(page.mediabox.height)
+ c.setPageSize((width, height))
+
+ cfg = configs[i]
+
+ text = (
+ cfg.get("text", "")
+ .replace("{n}", str(i + 1))
+ .replace("{total}", str(total_pages))
+ )
+
+ font_size = int(cfg.get("fontSize", 12))
+ color = cfg.get("color", "#000000")
+
+ # normalized → PDF coords (MATCH PREVIEW)
+ norm_x = float(cfg.get("x", 0.5))
+ norm_y = float(cfg.get("y", 0.95))
+
+ raw_x = norm_x * width
+ raw_y = (1 - norm_y) * height
+
+ c.setFont("Helvetica", font_size)
+ c.setFillColor(HexColor(color))
+ # 🔧 FIX: center text like preview
+ text_width = c.stringWidth(text, "Helvetica", font_size)
+ # center text
+ x = raw_x - (text_width / 2)
+ y = raw_y - (font_size / 2)
+
+ # 🔒 CLAMP inside page (SMART FIX)
+ MARGIN = 8 # points
+
+ # horizontal clamp
+ x = max(MARGIN, min(x, width - text_width - MARGIN))
+
+ # vertical clamp
+ y = max(MARGIN, min(y, height - font_size - MARGIN))
+
+ c.drawString(x, y, text)
+
+ c.showPage()
+
+ c.save()
+
+ # ---------- MERGE ----------
+ overlay_reader = PdfReader(overlay_pdf)
+ writer = PdfWriter()
+
+ for i in range(total_pages):
+ base_page = reader.pages[i]
+ base_page.merge_page(overlay_reader.pages[i])
+ writer.add_page(base_page)
+
+ with open(output_path, "wb") as out:
+ writer.write(out)
+
+ return {
+ "url": f"{base_url}/static/pdf/{output_name}"
+ }
+
+ except PdfReadError:
+ raise HTTPException(400, "Invalid or corrupted PDF")
+
+ finally:
+ for p in (temp_pdf, overlay_pdf):
+ if os.path.exists(p):
+ os.remove(p)
+
+
+# -------------------------------------------------
+# PDF BOOKMARK ENDPOINT
+# -------------------------------------------------
+@router.post("/bookmark")
+async def add_pdf_bookmarks(
+ file: UploadFile = File(...),
+ bookmarks: str = Form(...), # JSON string
+):
+ # 1️⃣ Validate file
+ if file.content_type != "application/pdf":
+ raise HTTPException(status_code=400, detail="Only PDF files are supported")
+
+ # 2️⃣ Parse bookmarks JSON
+ try:
+ bookmark_list = json.loads(bookmarks)
+ except Exception:
+ raise HTTPException(status_code=400, detail="Invalid bookmarks JSON")
+
+ if not isinstance(bookmark_list, list):
+ raise HTTPException(status_code=400, detail="Bookmarks must be a list")
+
+ # 3️⃣ Paths
+ input_path = os.path.join(TEMP_DIR, f"{uuid.uuid4()}.pdf")
+ output_name = f"bookmarked_{uuid.uuid4().hex}.pdf"
+ output_path = os.path.join(STATIC_DIR, output_name)
+
+ # 4️⃣ Save uploaded file
+ with open(input_path, "wb") as f:
+ f.write(await file.read())
+
+ # 5️⃣ Process bookmarks (threadpool)
+ try:
+ await run_in_threadpool(
+ process_pdf_bookmarks,
+ input_path,
+ output_path,
+ bookmark_list,
+ )
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+ # 6️⃣ Return downloadable URL
+ return {
+ "url": f"https://api.cloudaipdf.com/static/pdf/{output_name}"
+ }
+
+
+# -------------------------------------------------
+# CORE BOOKMARK LOGIC
+# -------------------------------------------------
+def process_pdf_bookmarks(input_pdf_path, output_pdf_path, bookmarks):
+ reader = PdfReader(input_pdf_path)
+ writer = PdfWriter()
+
+ total_pages = len(reader.pages)
+
+ # Copy all pages first
+ for page in reader.pages:
+ writer.add_page(page)
+
+ # Add bookmarks (PDF outlines)
+ for bm in bookmarks:
+ title = str(bm.get("title", "")).strip()
+ page_number = bm.get("page", 1)
+
+ if not title:
+ continue
+
+ try:
+ page_index = int(page_number) - 1
+ except Exception:
+ page_index = 0
+
+ # Clamp page number safely
+ page_index = max(0, min(page_index, total_pages - 1))
+
+ writer.add_outline_item(
+ title=title,
+ page_number=page_index,
+ )
+
+ # Write final PDF
+ with open(output_pdf_path, "wb") as f:
+ writer.write(f)
+
+
+# =====================================================
+# PDF EDITOR — INFO (pages + dimensions)
+# =====================================================
+@router.post("/editor/info")
+async def pdf_editor_info(file: UploadFile = File(...)):
+ if file.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files allowed")
+
+ temp_path = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+
+ try:
+ with open(temp_path, "wb") as f:
+ f.write(await file.read())
+
+ reader = PdfReader(temp_path)
+
+ if reader.is_encrypted:
+ raise HTTPException(400, "PDF is password-protected")
+
+ dimensions = []
+ for page in reader.pages:
+ dimensions.append({
+ "width": float(page.mediabox.width),
+ "height": float(page.mediabox.height),
+ })
+
+ return {
+ "pageCount": len(reader.pages),
+ "dimensions": dimensions,
+ }
+
+ finally:
+ if os.path.exists(temp_path):
+ os.remove(temp_path)
+# =====================================================
+# PDF EDITOR — PAGE PREVIEW
+# =====================================================
+def _render_editor_preview(input_pdf: str, page: int, out_path: str):
+ images = convert_from_path(
+ input_pdf,
+ dpi=150,
+ first_page=page,
+ last_page=page,
+ )
+ images[0].save(out_path, "PNG")
+
+
+@router.post("/editor/preview")
+async def pdf_editor_preview(
+ request: Request,
+ file: UploadFile = File(...),
+ page: int = Form(...),
+):
+ if file.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files allowed")
+
+ base_url = str(request.base_url).rstrip("/")
+ temp_pdf = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ img_name = f"editor_preview_{uuid.uuid4().hex}.png"
+ img_path = os.path.join(STATIC_DIR, img_name)
+
+ try:
+ with open(temp_pdf, "wb") as f:
+ f.write(await file.read())
+
+ await run_in_threadpool(
+ _render_editor_preview,
+ temp_pdf,
+ page,
+ img_path,
+ )
+
+ return {
+ "url": f"{base_url}/static/pdf/{img_name}"
+ }
+
+ finally:
+ if os.path.exists(temp_pdf):
+ os.remove(temp_pdf)
+# =====================================================
+# PDF EDITOR — EXPORT FINAL PDF
+# =====================================================
+def safe_base64_decode(data: str) -> bytes:
+ print("🧪 safe_base64_decode type:", type(data))
+
+ if "," in data:
+ print("🧪 stripping data URL prefix")
+ data = data.split(",", 1)[1]
+
+ missing_padding = len(data) % 4
+ if missing_padding:
+ print("🧪 fixing padding")
+ data += "=" * (4 - missing_padding)
+
+ decoded = base64.b64decode(data, validate=False)
+ print("🧪 decoded bytes length:", len(decoded))
+ return decoded
+
+
+@router.post("/editor/export")
+async def pdf_editor_export(
+ request: Request,
+ file: UploadFile = File(...),
+ pageImages: str | None = Form(None),
+):
+ print("\n================ EXPORT START ================")
+
+ print("📄 file:", file)
+ print("📄 filename:", getattr(file, "filename", None))
+ print("📄 content_type:", getattr(file, "content_type", None))
+ print("🖼️ raw pageImages:", pageImages)
+
+ if not file:
+ print("❌ ERROR: file missing")
+ raise HTTPException(400, "File missing")
+
+ if file.content_type != "application/pdf":
+ print("❌ ERROR: not a PDF")
+ raise HTTPException(400, "Only PDF files are allowed")
+
+ base_url = str(request.base_url).rstrip("/")
+ temp_pdf = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ output_name = f"edited_{uuid.uuid4().hex}.pdf"
+ output_path = os.path.join(STATIC_DIR, output_name)
+
+ try:
+ # -------- PARSE OVERLAYS --------
+ if pageImages:
+ print("🧪 pageImages provided")
+ try:
+ overlays = json.loads(pageImages)
+ print("🧪 overlays type:", type(overlays))
+ print("🧪 overlays keys:", overlays.keys())
+ except Exception as e:
+ print("❌ JSON parse error:", e)
+ raise HTTPException(400, "Invalid pageImages JSON")
+ else:
+ print("ℹ️ no overlays provided")
+ overlays = {}
+
+ # -------- SAVE PDF --------
+ with open(temp_pdf, "wb") as f:
+ pdf_bytes = await file.read()
+ print("📦 PDF byte length:", len(pdf_bytes))
+ f.write(pdf_bytes)
+
+ reader = PdfReader(temp_pdf)
+ print("📄 total pages:", len(reader.pages))
+
+ if reader.is_encrypted:
+ print("❌ ERROR: PDF encrypted")
+ raise HTTPException(400, "PDF is password protected")
+
+ writer = PdfWriter()
+
+ # -------- PROCESS PAGES --------
+ for i, page in enumerate(reader.pages):
+ page_num = str(i + 1)
+ print(f"➡️ Processing page {page_num}")
+
+ if page_num in overlays:
+ print(f"🖼️ Overlay found for page {page_num}")
+ try:
+ overlay_value = overlays[page_num]
+ print("🧪 overlay_value type:", type(overlay_value))
+ print("🧪 overlay_value:", overlay_value)
+
+ if isinstance(overlay_value, dict):
+ img_src = overlay_value.get("src")
+ print("🧪 extracted src from dict")
+ elif isinstance(overlay_value, str):
+ img_src = overlay_value
+ print("🧪 overlay is raw string")
+ else:
+ print("❌ invalid overlay type")
+ raise HTTPException(
+ 400, f"Invalid overlay format on page {page_num}"
+ )
+
+ if not img_src:
+ print("❌ missing src")
+ raise HTTPException(
+ 400, f"Overlay src missing on page {page_num}"
+ )
+
+ img_bytes = safe_base64_decode(img_src)
+
+ overlay_pdf = io.BytesIO()
+ c = canvas.Canvas(
+ overlay_pdf,
+ pagesize=(
+ float(page.mediabox.width),
+ float(page.mediabox.height),
+ ),
+ )
+
+ print("🧪 creating ImageReader")
+ image_reader = ImageReader(io.BytesIO(img_bytes))
+
+ print("🧪 drawing image via ReportLab")
+ c.drawImage(
+ image_reader,
+ 0,
+ 0,
+ width=float(page.mediabox.width),
+ height=float(page.mediabox.height),
+ mask="auto",
+ )
+
+ c.showPage()
+ c.save()
+
+ overlay_reader = PdfReader(io.BytesIO(overlay_pdf.getvalue()))
+ page.merge_page(overlay_reader.pages[0])
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ print("❌ ERROR overlay processing:", e)
+ raise HTTPException(
+ 400,
+ f"Overlay processing failed on page {page_num}",
+ )
+
+ writer.add_page(page)
+
+ # -------- WRITE OUTPUT --------
+ with open(output_path, "wb") as out:
+ writer.write(out)
+
+ print("✅ EXPORT SUCCESS:", output_path)
+
+ return {
+ "url": f"{base_url}/static/pdf/{output_name}"
+ }
+
+ except HTTPException:
+ raise
+
+ except Exception as e:
+ print("❌ UNEXPECTED ERROR:", e)
+ raise HTTPException(400, f"Export failed: {str(e)}")
+
+ finally:
+ if os.path.exists(temp_pdf):
+ os.remove(temp_pdf)
+ print("🧹 temp file removed")
+
+ print("================ EXPORT END =================\n")
+
+# ==================================================
+# ============ PDF EXTRACT PAGES (FRONTEND MATCH) ===
+# ==================================================
+
+@router.post("/extract-pages")
+async def pdf_extract_pages(
+ request: Request,
+ file: UploadFile = File(...),
+ pages: str = Form(...),
+):
+ if file.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files are supported")
+
+ base_url = str(request.base_url).rstrip("/")
+
+ temp_input = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ output_name = f"extracted_{uuid.uuid4().hex}.pdf"
+ output_path = os.path.join(STATIC_DIR, output_name)
+
+ try:
+ # -------------------------------
+ # SAVE INPUT PDF
+ # -------------------------------
+ with open(temp_input, "wb") as f:
+ f.write(await file.read())
+
+ # -------------------------------
+ # PARSE PAGES (1-based → 0-based)
+ # frontend sends: "1,3,5"
+ # -------------------------------
+ try:
+ page_numbers = [
+ int(p.strip()) - 1
+ for p in pages.split(",")
+ if p.strip().isdigit()
+ ]
+ except Exception:
+ raise HTTPException(400, "Invalid page list")
+
+ if not page_numbers:
+ raise HTTPException(400, "No pages selected")
+
+ reader = PdfReader(temp_input)
+
+ # 🔒 BLOCK PASSWORD PDFs
+ if reader.is_encrypted:
+ raise HTTPException(
+ status_code=400,
+ detail="PDF is password-protected. Please unlock it first.",
+ )
+
+ writer = PdfWriter()
+ total_pages = len(reader.pages)
+
+ for p in page_numbers:
+ if p < 0 or p >= total_pages:
+ raise HTTPException(400, "Selected page out of range")
+ writer.add_page(reader.pages[p])
+
+ # -------------------------------
+ # WRITE OUTPUT PDF
+ # -------------------------------
+ with open(output_path, "wb") as out:
+ writer.write(out)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "Page extraction failed")
+
+ # -------------------------------
+ # RETURN FORMAT FRONTEND EXPECTS
+ # -------------------------------
+ return {
+ "url": f"{base_url}/static/pdf/{output_name}",
+ "size": os.path.getsize(output_path),
+ }
+
+ except PdfReadError:
+ raise HTTPException(400, "Invalid or corrupted PDF")
+
+ except HTTPException:
+ raise
+
+ except Exception as e:
+ raise HTTPException(500, f"Extract error: {str(e)}")
+
+ finally:
+ safe_remove(temp_input)
+
+
+# ==================================================
+# ============ PDF PAGE REORDER ====================
+# ==================================================
+
+@router.post("/reorder")
+async def pdf_reorder(
+ request: Request,
+ file: UploadFile = File(...),
+ pageOrder: str = Form(...),
+):
+ if file.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files are supported")
+
+ base_url = str(request.base_url).rstrip("/")
+
+ temp_input = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ output_name = f"reordered_{uuid.uuid4().hex}.pdf"
+ output_path = os.path.join(STATIC_DIR, output_name)
+
+ try:
+ # -------------------------------
+ # SAVE INPUT PDF
+ # -------------------------------
+ with open(temp_input, "wb") as f:
+ f.write(await file.read())
+
+ # -------------------------------
+ # PARSE PAGE ORDER (1-based → 0-based)
+ # frontend sends: "3,1,2"
+ # -------------------------------
+ try:
+ page_indices = [
+ int(p.strip()) - 1
+ for p in pageOrder.split(",")
+ if p.strip().isdigit()
+ ]
+ except Exception:
+ raise HTTPException(400, "Invalid pageOrder format")
+
+ if not page_indices:
+ raise HTTPException(400, "Page order is empty")
+
+ reader = PdfReader(temp_input)
+
+ # 🔒 BLOCK PASSWORD-PROTECTED PDFs
+ if reader.is_encrypted:
+ raise HTTPException(
+ status_code=400,
+ detail="PDF is password-protected. Please unlock it first.",
+ )
+
+ total_pages = len(reader.pages)
+
+ # Validate indices
+ for i in page_indices:
+ if i < 0 or i >= total_pages:
+ raise HTTPException(400, "Page index out of range")
+
+ writer = PdfWriter()
+
+ # -------------------------------
+ # REORDER PAGES
+ # -------------------------------
+ for i in page_indices:
+ writer.add_page(reader.pages[i])
+
+ # -------------------------------
+ # WRITE OUTPUT PDF
+ # -------------------------------
+ with open(output_path, "wb") as out:
+ writer.write(out)
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "PDF reorder failed")
+
+ return {
+ "url": f"{base_url}/static/pdf/{output_name}",
+ "size": os.path.getsize(output_path),
+ }
+
+ except PdfReadError:
+ raise HTTPException(400, "Invalid or corrupted PDF")
+
+ except HTTPException:
+ raise
+
+ except Exception as e:
+ raise HTTPException(500, f"Reorder error: {str(e)}")
+
+ finally:
+ safe_remove(temp_input)
+
+
+# ==================================================
+# ============ PDF PAGE ROTATE =====================
+# ==================================================
+
+@router.post("/rotate")
+async def pdf_rotate(
+ request: Request,
+ file: UploadFile = File(...),
+ rotations: str = Form(...), # JSON: { "1": 90, "2": 270 }
+):
+ if file.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files are supported")
+
+ base_url = str(request.base_url).rstrip("/")
+
+ temp_input = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ output_name = f"rotated_{uuid.uuid4().hex}.pdf"
+ output_path = os.path.join(STATIC_DIR, output_name)
+
+ try:
+ # -------------------------------
+ # PARSE ROTATIONS JSON
+ # -------------------------------
+ try:
+ rotation_map = json.loads(rotations)
+ except Exception:
+ raise HTTPException(400, "Invalid rotations JSON")
+
+ if not isinstance(rotation_map, dict):
+ raise HTTPException(400, "Rotations must be an object")
+
+ # -------------------------------
+ # SAVE INPUT PDF
+ # -------------------------------
+ with open(temp_input, "wb") as f:
+ f.write(await file.read())
+
+ reader = PdfReader(temp_input)
+
+ # 🔒 BLOCK PASSWORD PDFs
+ if reader.is_encrypted:
+ raise HTTPException(
+ status_code=400,
+ detail="PDF is password-protected. Please unlock it first.",
+ )
+
+ writer = PdfWriter()
+ total_pages = len(reader.pages)
+
+ # -------------------------------
+ # APPLY ROTATIONS
+ # -------------------------------
+ for index, page in enumerate(reader.pages):
+ page_number = str(index + 1)
+
+ if page_number in rotation_map:
+ try:
+ angle = int(rotation_map[page_number]) % 360
+ except Exception:
+ angle = 0
+
+ # pypdf rotates clockwise with negative values
+ page.rotate(angle)
+
+ writer.add_page(page)
+
+ # -------------------------------
+ # WRITE OUTPUT
+ # -------------------------------
+ with open(output_path, "wb") as out:
+ writer.write(out)
+
+ return {
+ "url": f"{base_url}/static/pdf/{output_name}",
+ "size": os.path.getsize(output_path),
+ }
+
+ except PdfReadError:
+ raise HTTPException(400, "Invalid or corrupted PDF")
+
+ except HTTPException:
+ raise
+
+ except Exception as e:
+ raise HTTPException(500, f"Rotate error: {str(e)}")
+
+ finally:
+ safe_remove(temp_input)
+
+
+# ==================================================
+# ============ PDF PROTECT / ENCRYPT (FINAL) =======
+# ==================================================
+
+@router.post("/protect")
+async def pdf_protect(
+ request: Request,
+ file: UploadFile = File(...),
+
+ userPassword: str = Form(...),
+ ownerPassword: str = Form(None),
+
+ encryptionLevel: str = Form("AES-256"),
+
+ allowPrint: str = Form("true"), # received but not enforced (PDF spec limit)
+ allowCopy: str = Form("true"),
+ allowModify: str = Form("false"),
+
+ watermarkText: str = Form(""),
+):
+ print("\n================ /pdf/protect DEBUG ================")
+ print("📥 METHOD:", request.method)
+ print("📥 CONTENT-TYPE:", request.headers.get("content-type"))
+
+ # -------- RAW FORM DATA --------
+ try:
+ form = await request.form()
+ print("📦 RAW FORM KEYS:", list(form.keys()))
+ for k, v in form.items():
+ if hasattr(v, "filename"):
+ print(f"📄 {k} -> FILE:", v.filename, "|", v.content_type)
+ else:
+ print(f"🧾 {k} ->", v)
+ except Exception as e:
+ print("❌ ERROR reading form:", e)
+
+ print("🔐 userPassword:", userPassword)
+ print("🔐 ownerPassword:", ownerPassword)
+ print("🔐 encryptionLevel:", encryptionLevel)
+ print("🧩 allowPrint:", allowPrint)
+ print("🧩 allowCopy:", allowCopy)
+ print("🧩 allowModify:", allowModify)
+ print("💧 watermarkText:", watermarkText)
+ print("==================================================")
+
+ # ------------------------------------------------
+ # NORMALIZE INPUTS
+ # ------------------------------------------------
+ files = [file] # single-file normalize
+ ownerPassword = ownerPassword or userPassword
+
+ base_url = str(request.base_url).rstrip("/")
+ temp_inputs = []
+ merged_pdf = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ output_name = f"protected_{uuid.uuid4().hex}.pdf"
+ output_path = os.path.join(STATIC_DIR, output_name)
+
+ try:
+ # ------------------------------------------------
+ # SAVE & COPY PDF
+ # ------------------------------------------------
+ writer = PdfWriter()
+
+ for f in files:
+ print("➡️ Processing file:", f.filename)
+
+ if f.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files allowed")
+
+ temp_path = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ temp_inputs.append(temp_path)
+
+ with open(temp_path, "wb") as out:
+ data = await f.read()
+ print("📦 File size:", len(data), "bytes")
+ out.write(data)
+
+ reader = PdfReader(temp_path)
+
+ if reader.is_encrypted:
+ raise HTTPException(400, "Uploaded PDF is already password protected")
+
+ print("📄 Pages:", len(reader.pages))
+
+ for page in reader.pages:
+ writer.add_page(page)
+
+ with open(merged_pdf, "wb") as f:
+ writer.write(f)
+
+ print("✅ Base PDF ready:", merged_pdf)
+
+ # ------------------------------------------------
+ # OPTIONAL WATERMARK
+ # ------------------------------------------------
+ if watermarkText:
+ print("💧 Applying watermark")
+
+ watermarked = os.path.join(TEMP_DIR, f"wm_{uuid.uuid4().hex}.pdf")
+ reader = PdfReader(merged_pdf)
+ writer = PdfWriter()
+
+ for page in reader.pages:
+ packet = io.BytesIO()
+ c = canvas.Canvas(
+ packet,
+ pagesize=(page.mediabox.width, page.mediabox.height),
+ )
+
+ c.setFont("Helvetica-Bold", 40)
+ c.setFillColorRGB(0.7, 0.7, 0.7)
+ c.saveState()
+ c.translate(page.mediabox.width / 2, page.mediabox.height / 2)
+ c.rotate(45)
+ c.drawCentredString(0, 0, watermarkText)
+ c.restoreState()
+ c.showPage()
+ c.save()
+
+ overlay = PdfReader(packet)
+ page.merge_page(overlay.pages[0])
+ writer.add_page(page)
+
+ with open(watermarked, "wb") as f:
+ writer.write(f)
+
+ merged_pdf = watermarked
+ print("✅ Watermark applied")
+
+ # ------------------------------------------------
+ # ENCRYPT FINAL PDF (pypdf-compatible)
+ # ------------------------------------------------
+ print("🔐 Encrypting PDF")
+
+ reader = PdfReader(merged_pdf)
+ writer = PdfWriter()
+
+ for page in reader.pages:
+ writer.add_page(page)
+
+ writer.encrypt(
+ user_password=userPassword,
+ owner_password=ownerPassword,
+ use_128bit=(encryptionLevel == "AES-128"),
+ )
+
+ with open(output_path, "wb") as f:
+ writer.write(f)
+
+ print("✅ SUCCESS: Protected PDF written:", output_path)
+ print("==================================================\n")
+
+ return {
+ "url": f"{base_url}/static/pdf/{output_name}",
+ "size": os.path.getsize(output_path),
+ }
+
+ except Exception as e:
+ print("❌ ERROR:", e)
+ raise HTTPException(500, f"Protect error: {str(e)}")
+
+ finally:
+ for p in temp_inputs:
+ safe_remove(p)
+ print("🧹 Temp files cleaned")
+
+
+# ==================================================
+# ============ PDF → PDF/A CONVERTER ===============
+# ==================================================
+
+@router.post("/convert-pdfa")
+async def convert_pdfa(
+ request: Request,
+ file: UploadFile = File(...),
+ conformance: str = Form(...),
+):
+ print("\n================ /pdf/convert-pdfa DEBUG ================")
+ print("📥 METHOD:", request.method)
+ print("📥 CONTENT-TYPE:", request.headers.get("content-type"))
+
+ try:
+ form = await request.form()
+ print("📦 RAW FORM KEYS:", list(form.keys()))
+ for k, v in form.items():
+ if hasattr(v, "filename"):
+ print(f"📄 {k} -> FILE:", v.filename)
+ else:
+ print(f"🧾 {k} ->", v)
+ except Exception as e:
+ print("❌ FORM READ ERROR:", e)
+
+ print("📐 Requested conformance:", conformance)
+ print("========================================================\n")
+
+ if file.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files are supported")
+
+ # -------------------------------------------------
+ # MAP FRONTEND → GHOSTSCRIPT PDF/A FLAGS
+ # -------------------------------------------------
+ pdfa_map = {
+ "PDF/A-1b": "PDF/A-1",
+ "PDF/A-2b": "PDF/A-2",
+ "PDF/A-2u": "PDF/A-2",
+ "PDF/A-3b": "PDF/A-3",
+ }
+
+ if conformance not in pdfa_map:
+ raise HTTPException(400, "Unsupported PDF/A conformance level")
+
+ base_url = str(request.base_url).rstrip("/")
+ temp_input = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ output_name = f"pdfa_{uuid.uuid4().hex}.pdf"
+ output_path = os.path.join(STATIC_DIR, output_name)
+
+ try:
+ # -------------------------------------------------
+ # SAVE INPUT PDF
+ # -------------------------------------------------
+ with open(temp_input, "wb") as f:
+ data = await file.read()
+ f.write(data)
+
+ print("📦 Input size:", len(data), "bytes")
+
+ # -------------------------------------------------
+ # GHOSTSCRIPT COMMAND
+ # -------------------------------------------------
+ gs_cmd = [
+ "gs",
+ "-dSAFER",
+ "-dBATCH",
+ "-dNOPAUSE",
+ "-dNOOUTERSAVE",
+ "-sDEVICE=pdfwrite",
+ f"-dPDFA={pdfa_map[conformance][-1]}",
+ "-dPDFACompatibilityPolicy=1",
+ f"-sOutputFile={output_path}",
+ temp_input,
+ ]
+
+ print("⚙️ Ghostscript command:")
+ print(" ".join(gs_cmd))
+
+ result = subprocess.run(
+ gs_cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ )
+
+ if result.returncode != 0:
+ print("❌ Ghostscript STDERR:", result.stderr)
+ raise HTTPException(500, "PDF/A conversion failed")
+
+ if not os.path.exists(output_path):
+ raise HTTPException(500, "PDF/A output not generated")
+
+ print("✅ PDF/A conversion success:", output_path)
+ print("========================================================\n")
+
+ return {
+ "url": f"{base_url}/static/pdf/{output_name}",
+ "size": os.path.getsize(output_path),
+ }
+
+ except Exception as e:
+ print("❌ ERROR:", e)
+ raise HTTPException(500, f"PDF/A conversion error: {str(e)}")
+
+ finally:
+ safe_remove(temp_input)
+ print("🧹 Temp input cleaned")
+
+
+# ==================================================
+# ============ PDF REPAIR ==========================
+# ==================================================
+
+@router.post("/repair")
+async def repair_pdf(
+ request: Request,
+ file: UploadFile = File(...),
+):
+ print("\n================ /pdf/repair DEBUG ================")
+ print("📥 METHOD:", request.method)
+ print("📥 CONTENT-TYPE:", request.headers.get("content-type"))
+
+ try:
+ form = await request.form()
+ print("📦 RAW FORM KEYS:", list(form.keys()))
+ for k, v in form.items():
+ if hasattr(v, "filename"):
+ print(f"📄 {k} -> FILE:", v.filename)
+ else:
+ print(f"🧾 {k} ->", v)
+ except Exception as e:
+ print("❌ FORM READ ERROR:", e)
+
+ print("==================================================")
+
+ if file.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files are supported")
+
+ base_url = str(request.base_url).rstrip("/")
+
+ temp_input = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ output_name = f"repaired_{uuid.uuid4().hex}.pdf"
+ output_path = os.path.join(STATIC_DIR, output_name)
+
+ try:
+ # ---------------------------------------------
+ # SAVE INPUT
+ # ---------------------------------------------
+ with open(temp_input, "wb") as f:
+ data = await file.read()
+ f.write(data)
+
+ print("📦 Input size:", len(data), "bytes")
+
+ # ---------------------------------------------
+ # GHOSTSCRIPT REPAIR
+ # ---------------------------------------------
+ gs_cmd = [
+ "gs",
+ "-dSAFER",
+ "-dBATCH",
+ "-dNOPAUSE",
+ "-dNOOUTERSAVE",
+ "-sDEVICE=pdfwrite",
+ f"-sOutputFile={output_path}",
+ temp_input,
+ ]
+
+ print("⚙️ Ghostscript repair command:")
+ print(" ".join(gs_cmd))
+
+ result = subprocess.run(
+ gs_cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ )
+
+ if result.returncode != 0:
+ print("❌ Ghostscript STDERR:", result.stderr)
+ raise HTTPException(
+ status_code=422,
+ detail="The document structure is too damaged for automatic recovery.",
+ )
+
+ if not os.path.exists(output_path):
+ raise HTTPException(
+ status_code=422,
+ detail="Repair failed. Output file not generated.",
+ )
+
+ print("✅ Repair successful:", output_path)
+ print("==================================================\n")
+
+ return {
+ "url": f"{base_url}/static/pdf/{output_name}",
+ "message": "File successfully repaired.",
+ }
+
+ except HTTPException:
+ raise
+
+ except Exception as e:
+ print("❌ ERROR:", e)
+ raise HTTPException(
+ status_code=422,
+ detail="The document structure is too damaged for automatic recovery.",
+ )
+
+ finally:
+ safe_remove(temp_input)
+ print("🧹 Temp input cleaned")
+
+
+# ==================================================
+# ============ PDF UNLOCK ==========================
+# ==================================================
+
+@router.post("/unlock")
+async def unlock_pdf(
+ request: Request,
+ file: UploadFile = File(...),
+ password: str = Form(...),
+):
+ print("\n================ /pdf/unlock DEBUG ================")
+ print("📥 METHOD:", request.method)
+ print("📥 CONTENT-TYPE:", request.headers.get("content-type"))
+
+ try:
+ form = await request.form()
+ print("📦 RAW FORM KEYS:", list(form.keys()))
+ for k, v in form.items():
+ if hasattr(v, "filename"):
+ print(f"📄 {k} -> FILE:", v.filename)
+ else:
+ print(f"🧾 {k} ->", v)
+ except Exception as e:
+ print("❌ FORM READ ERROR:", e)
+
+ print("🔑 Password length:", len(password))
+ print("==================================================")
+
+ if file.content_type != "application/pdf":
+ raise HTTPException(400, "Only PDF files are supported")
+
+ if not password:
+ raise HTTPException(
+ status_code=422,
+ detail="Unlock Failed: Password is required.",
+ )
+
+ base_url = str(request.base_url).rstrip("/")
+ temp_input = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ output_name = f"unlocked_{uuid.uuid4().hex}.pdf"
+ output_path = os.path.join(STATIC_DIR, output_name)
+
+ try:
+ # ---------------------------------------------
+ # SAVE INPUT PDF
+ # ---------------------------------------------
+ with open(temp_input, "wb") as f:
+ data = await file.read()
+ f.write(data)
+
+ print("📦 Input size:", len(data), "bytes")
+
+ # ---------------------------------------------
+ # LOAD & DECRYPT
+ # ---------------------------------------------
+ reader = PdfReader(temp_input)
+
+ if not reader.is_encrypted:
+ print("⚠️ PDF is not encrypted, copying as-is")
+
+ else:
+ print("🔐 PDF is encrypted, attempting unlock")
+ success = reader.decrypt(password)
+
+ if success == 0:
+ print("❌ Wrong password")
+ raise HTTPException(
+ status_code=422,
+ detail="Unlock Failed: Incorrect password.",
+ )
+
+ print("✅ Password accepted")
+
+ # ---------------------------------------------
+ # WRITE UNLOCKED PDF
+ # ---------------------------------------------
+ writer = PdfWriter()
+
+ for page in reader.pages:
+ writer.add_page(page)
+
+ with open(output_path, "wb") as f:
+ writer.write(f)
+
+ print("✅ PDF unlocked:", output_path)
+ print("==================================================\n")
+
+ return {
+ "url": f"{base_url}/static/pdf/{output_name}",
+ "message": "File successfully unlocked.",
+ }
+
+ except HTTPException:
+ raise
+
+ except Exception as e:
+ print("❌ ERROR:", e)
+ raise HTTPException(
+ status_code=422,
+ detail="Unlock Failed: Unable to decrypt the file.",
+ )
+
+ finally:
+ safe_remove(temp_input)
+ print("🧹 Temp input cleaned")
+
+# ==================================================
+# ============ PDF WATERMARK (FINAL FIXED) =========
+# ==================================================
+
+@router.post("/watermark")
+async def pdf_watermark(
+ request: Request,
+ file: UploadFile = File(...),
+ pagesConfig: str = Form(...),
+ watermarkImage: UploadFile | None = File(None),
+):
+ print("\n================ /pdf/watermark DEBUG ================")
+ print("📥 METHOD:", request.method)
+ print("📥 CONTENT-TYPE:", request.headers.get("content-type"))
+
+ try:
+ form = await request.form()
+ print("📦 RAW FORM KEYS:", list(form.keys()))
+ except Exception as e:
+ print("❌ ERROR reading form:", e)
+
+ print("📄 file:", file)
+ print("📄 filename:", getattr(file, "filename", None))
+ print("📄 content_type:", getattr(file, "content_type", None))
+ print("🧾 raw pagesConfig:", pagesConfig[:300], "..." if len(pagesConfig) > 300 else "")
+
+ if file.content_type != "application/pdf":
+ print("❌ ERROR: Not a PDF")
+ raise HTTPException(400, "Only PDF allowed")
+
+ base_url = str(request.base_url).rstrip("/")
+
+ tmp_pdf = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}.pdf")
+ out_name = f"watermarked_{uuid.uuid4().hex}.pdf"
+ out_path = os.path.join(STATIC_DIR, out_name)
+
+ # -------------------------------
+ # SAVE PDF
+ # -------------------------------
+ with open(tmp_pdf, "wb") as f:
+ data = await file.read()
+ print("📦 PDF size:", len(data), "bytes")
+ f.write(data)
+
+ # -------------------------------
+ # PARSE pagesConfig
+ # -------------------------------
+ try:
+ configs = json.loads(pagesConfig)
+ print("✅ pagesConfig parsed")
+ print("🧪 pagesConfig type:", type(configs))
+ print("🧪 pagesConfig length:", len(configs))
+ print("🧪 first page config:", configs[0] if configs else None)
+ except Exception as e:
+ print("❌ JSON PARSE ERROR:", e)
+ os.remove(tmp_pdf)
+ raise HTTPException(400, "Invalid pagesConfig JSON")
+
+ if not isinstance(configs, list):
+ print("❌ pagesConfig is NOT a list")
+ os.remove(tmp_pdf)
+ raise HTTPException(400, "pagesConfig must be a list")
+
+ # -------------------------------
+ # APPLY WATERMARK (THREADPOOL)
+ # -------------------------------
+ try:
+ await run_in_threadpool(
+ apply_watermark_debug,
+ tmp_pdf,
+ out_path,
+ configs,
+ watermarkImage,
+ )
+ except Exception as e:
+ print("❌ WATERMARK FAILED:", e)
+ if os.path.exists(tmp_pdf):
+ os.remove(tmp_pdf)
+ raise HTTPException(400, str(e))
+
+ os.remove(tmp_pdf)
+
+ print("✅ SUCCESS →", out_path)
+ print("====================================================\n")
+
+ return {
+ "url": f"{base_url}/static/pdf/{out_name}",
+ "size": os.path.getsize(out_path),
+ }
+
+
+# --------------------------------------------------
+# CORE WATERMARK LOGIC (MATCHES FRONTEND PREVIEW)
+# --------------------------------------------------
+def apply_watermark_debug(input_pdf, output_pdf, pages_config, watermarkImage):
+ print("\n🧪 apply_watermark_debug START")
+ print("📄 input_pdf:", input_pdf)
+ print("📄 output_pdf:", output_pdf)
+ print("📄 pages_config length:", len(pages_config))
+
+ doc = fitz.open(input_pdf)
+ print("📄 PDF page count:", doc.page_count)
+ # ✅ READ IMAGE BYTES ONCE
+ image_bytes = None
+ if watermarkImage:
+ image_bytes = watermarkImage.file.read()
+ print("🖼️ watermarkImage bytes:", len(image_bytes))
+
+ if len(pages_config) != doc.page_count:
+ doc.close()
+ raise ValueError(
+ f"pagesConfig length ({len(pages_config)}) "
+ f"!= page count ({doc.page_count})"
+ )
+
+ for i, cfg in enumerate(pages_config):
+ print(f"\n➡️ Page {i + 1}")
+ print("🧾 cfg:", cfg)
+
+ page = doc[i]
+ rect = page.rect
+
+ try:
+ norm_x = float(cfg.get("x", 0.1))
+ norm_y = float(cfg.get("y", 0.1))
+ cx = norm_x * rect.width
+ cy = norm_y * rect.height
+ cx -= rect.width * 0.0001
+ cy -= rect.height * 0.001
+ rotate = -float(cfg.get("rotate", 0))
+ opacity = float(cfg.get("opacity", 0.3))
+ scale = float(cfg.get("scale", 1))
+ except Exception as e:
+ raise ValueError(f"Invalid numeric values on page {i+1}: {e}")
+
+ print("📐 cx, cy:", cx, cy)
+ print("🔄 rotate:", rotate, "💧 opacity:", opacity, "📏 scale:", scale)
+
+ if cfg.get("type") == "text":
+ text = cfg.get("text", "")
+ print("✏️ TEXT watermark:", text)
+
+ if not text.strip():
+ print("⚠️ empty text → skipped")
+ continue
+
+ png, (w, h) = make_text_png_safe(
+ text=text,
+ font_size=int(int(cfg.get("fontSize", 18)) * 0.67),
+ color=cfg.get("color", "#000000"),
+ opacity=opacity,
+ rotate=rotate,
+ )
+
+ elif cfg.get("type") == "image":
+ print("🖼️ IMAGE watermark")
+
+ if not image_bytes:
+ print("⚠️ imageUrl missing → skipped")
+ continue
+
+
+
+ png, (w, h) = make_image_png_safe(
+ image_bytes=image_bytes,
+ opacity=opacity,
+ rotate=rotate,
+ )
+
+ if "width" in cfg and "height" in cfg:
+ w = float(cfg["width"])
+ h = float(cfg["height"])
+ print("📐 using explicit size:", w, h)
+ else:
+ w *= scale
+ h *= scale
+ print("📐 using scaled size:", w, h)
+
+ else:
+ print("⚠️ Unknown watermark type → skipped")
+ continue
+
+ rect_img = fitz.Rect(
+ cx - (w / 2.0),
+ cy - (h / 2.0),
+ cx + (w / 2.0),
+ cy + (h / 2.0),
+ ).round()
+
+ print("📦 inserting image at:", rect_img)
+ page.insert_image(rect_img, stream=png)
+
+ doc.save(output_pdf)
+ doc.close()
+ print("✅ apply_watermark_debug DONE\n")
+
+# --------------------------------------------------
+# SAFE TEXT PNG GENERATOR
+# --------------------------------------------------
+
+def make_text_png_safe(text, font_size, color, opacity, rotate):
+ # ---- Load font ----
+ try:
+ font = ImageFont.truetype("DejaVuSans-Bold.ttf", font_size)
+ except Exception:
+ font = ImageFont.load_default()
+
+ # ---- Measure real text size ----
+ dummy_img = Image.new("RGBA", (1, 1))
+ dummy_draw = ImageDraw.Draw(dummy_img)
+ text_bbox = dummy_draw.textbbox((0, 0), text, font=font)
+
+ text_width = text_bbox[2] - text_bbox[0]
+ text_height = text_bbox[3] - text_bbox[1]
+
+ # Add small padding
+ horizontal_padding = int(font_size * 0.010)
+ vertical_padding = int(font_size * 0.001) # much smaller
+
+ W = text_width + horizontal_padding
+ H = text_height + vertical_padding
+
+ # ---- Create exact-size image ----
+ img = Image.new("RGBA", (W, H), (0, 0, 0, 0))
+ draw = ImageDraw.Draw(img)
+
+ r = int(color[1:3], 16)
+ g = int(color[3:5], 16)
+ b = int(color[5:7], 16)
+ a = int(255 * opacity)
+
+ draw.text(
+ (W // 2, H // 2),
+ text,
+ fill=(r, g, b, a),
+ font=font,
+ anchor="mm",
+ )
+
+ if rotate:
+ img = img.rotate(rotate, expand=True, resample=Image.BICUBIC)
+
+ buf = io.BytesIO()
+ img.save(buf, "PNG")
+
+ return buf.getvalue(), img.size
+
+
+# --------------------------------------------------
+# SAFE IMAGE PNG GENERATOR
+# --------------------------------------------------
+
+def make_image_png_safe(image_bytes, opacity, rotate):
+ img = Image.open(io.BytesIO(image_bytes)).convert("RGBA")
+
+ alpha = img.split()[3].point(lambda p: int(p * opacity))
+ img.putalpha(alpha)
+
+ if rotate:
+ img = img.rotate(rotate, expand=True, resample=Image.BICUBIC)
+
+ buf = io.BytesIO()
+ img.save(buf, "PNG")
+ return buf.getvalue(), img.size
+
diff --git a/routers/pdf_watermark.py b/routers/pdf_watermark.py
new file mode 100644
index 0000000000000000000000000000000000000000..abd37e7f0a335afd1d518286e276c095847858ef
--- /dev/null
+++ b/routers/pdf_watermark.py
@@ -0,0 +1,114 @@
+import os, io, json, uuid
+import fitz
+from PIL import Image, ImageDraw, ImageFont, ImageColor
+from fastapi import APIRouter, UploadFile, File, Form, HTTPException
+from fastapi.responses import FileResponse
+
+router = APIRouter(prefix="/pdf/watermark", tags=["PDF Watermark"])
+
+
+BASE_DIR = os.path.dirname(os.path.abspath(__file__))
+TEMP_PDF = os.path.join(BASE_DIR, "..", "temp", "watermark")
+TEMP_PREVIEW = os.path.join(BASE_DIR, "..", "temp", "preview")
+OUT_DIR = os.path.join(BASE_DIR, "..", "output", "watermark")
+
+FONT_PATH = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
+
+os.makedirs(TEMP_PDF, exist_ok=True)
+os.makedirs(TEMP_PREVIEW, exist_ok=True)
+os.makedirs(OUT_DIR, exist_ok=True)
+
+
+# -----------------------------
+# PREVIEW
+# -----------------------------
+@router.post("/preview")
+async def preview_pdf(file: UploadFile = File(...)):
+ if not file.filename.lower().endswith(".pdf"):
+ raise HTTPException(400, "Only PDF supported")
+
+ file_id = str(uuid.uuid4())
+
+ pdf_path = os.path.join(TEMP_PDF, f"{file_id}.pdf")
+ with open(pdf_path, "wb") as f:
+ f.write(await file.read())
+
+ doc = fitz.open(pdf_path)
+ page = doc[0]
+
+ pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
+
+ preview_path = os.path.join(TEMP_PREVIEW, f"{file_id}.png")
+ img.save(preview_path)
+
+ doc.close()
+
+ return {
+ "fileId": file_id,
+ "previewUrl": f"/preview/{file_id}.png"
+ }
+
+
+# -----------------------------
+# APPLY WATERMARK
+# -----------------------------
+@router.post("/apply")
+async def apply_watermark(
+ file_id: str = Form(...),
+ watermark: str = Form(...)
+):
+ pdf_path = os.path.join(TEMP_PDF, f"{file_id}.pdf")
+ if not os.path.exists(pdf_path):
+ raise HTTPException(404, "Source PDF not found. Please re-upload.")
+
+ cfg = json.loads(watermark)
+
+ doc = fitz.open(pdf_path)
+ out_path = os.path.join(OUT_DIR, f"watermarked_{file_id}.pdf")
+
+ for page in doc:
+ pw, ph = page.rect.width, page.rect.height
+
+ cx = cfg["normalizedX"] * pw
+ cy = (1 - cfg["normalizedY"]) * ph # PDF Y flip
+
+ text = cfg["text"]
+ font_size = int(cfg["fontSize"] * cfg.get("scale", 1))
+ opacity = float(cfg.get("opacity", 0.5))
+ rotation = float(cfg.get("rotation", 0))
+ color = cfg.get("color", "#000000")
+
+ font = ImageFont.truetype(FONT_PATH, font_size)
+
+ dummy = Image.new("RGBA", (10, 10))
+ d = ImageDraw.Draw(dummy)
+ bbox = d.textbbox((0, 0), text, font=font)
+
+ w = bbox[2] - bbox[0]
+ h = bbox[3] - bbox[1]
+
+ img = Image.new("RGBA", (w + 40, h + 40), (0, 0, 0, 0))
+ draw = ImageDraw.Draw(img)
+
+ r, g, b = ImageColor.getrgb(color)
+ draw.text((20, 20), text, font=font, fill=(r, g, b, int(255 * opacity)))
+
+ img = img.rotate(-rotation, expand=True)
+
+ rect = fitz.Rect(
+ cx - img.width / 2,
+ cy - img.height / 2,
+ cx + img.width / 2,
+ cy + img.height / 2
+ )
+
+ buf = io.BytesIO()
+ img.save(buf, format="PNG")
+
+ page.insert_image(rect, stream=buf.getvalue())
+
+ doc.save(out_path)
+ doc.close()
+
+ return FileResponse(out_path, filename="watermarked.pdf")
diff --git a/routers/ratings.py b/routers/ratings.py
new file mode 100644
index 0000000000000000000000000000000000000000..c19bae5e6ac60b7e1166d7fae4aef142bd9d39ef
--- /dev/null
+++ b/routers/ratings.py
@@ -0,0 +1,75 @@
+from fastapi import APIRouter, Depends, HTTPException
+from sqlalchemy.orm import Session
+from pydantic import BaseModel, conint
+from core.database import get_db
+from core.models import Rating, ToolRatingAggregate
+from sqlalchemy import func
+
+router = APIRouter(prefix="/api/ratings", tags=["Ratings"])
+
+
+# -----------------------
+# Schemas
+# -----------------------
+class RatingIn(BaseModel):
+ tool: str
+ rating: conint(ge=1, le=5) # only 1–5 allowed
+
+
+# -----------------------
+# POST rating
+# -----------------------
+@router.post("")
+def submit_rating(payload: RatingIn, db: Session = Depends(get_db)):
+ rating = Rating(
+ tool=payload.tool,
+ rating=payload.rating
+ )
+ db.add(rating)
+ db.commit()
+ # 2. Recalculate aggregate
+ avg, count = db.query(
+ func.avg(Rating.rating),
+ func.count(Rating.id)
+ ).filter(Rating.tool == payload.tool).first()
+
+ avg = round(avg or 0, 2)
+ count = count or 0
+
+ # 3. Upsert aggregate
+ agg = db.get(ToolRatingAggregate, payload.tool)
+
+ if agg:
+ agg.average_rating = avg
+ agg.rating_count = count
+ else:
+ agg = ToolRatingAggregate(
+ tool=payload.tool,
+ average_rating=avg,
+ rating_count=count
+ )
+ db.add(agg)
+
+ db.commit()
+
+ return {"success": True, "average": avg, "count": count}
+
+# -----------------------
+# GET rating summary
+# -----------------------
+@router.get("/{tool}")
+def get_rating(tool: str, db: Session = Depends(get_db)):
+ agg = db.get(ToolRatingAggregate, tool)
+
+ if not agg:
+ return {
+ "tool": tool,
+ "average": 0,
+ "count": 0
+ }
+
+ return {
+ "tool": agg.tool,
+ "average": agg.average_rating,
+ "count": agg.rating_count
+ }
diff --git a/routers/stats.py b/routers/stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d8a521b0ae54137da0534f47ae6a5bd27585262
--- /dev/null
+++ b/routers/stats.py
@@ -0,0 +1,62 @@
+# (venv) rihan@rihanrahiman:~/backend/routers$ cat stats.py
+from fastapi import APIRouter, Depends, HTTPException
+from sqlalchemy.orm import Session
+from core.database import get_db
+# ⚠️ Ensure this import exists in your dependencies file
+from dependencies.api_auth import get_current_admin_user
+# 🔑 FIX: MUST IMPORT ALL SERVICE FUNCTIONS USED IN THIS FILE
+from services.stats_service import (
+ get_all_tool_stats,
+ get_tool_usage_by_day,
+ get_tool_usage_by_month, # <--- 🔑 ADDED THIS
+ get_tool_usage_by_year # <--- 🔑 ADDED THIS
+)
+
+router = APIRouter(
+ prefix="/stats",
+ tags=["Stats"],
+ # ✅ FIX: Include the authentication dependency here
+ dependencies=[Depends(get_current_admin_user)]
+)
+
+@router.get("/tool_usage")
+async def api_get_tool_usage(db: Session = Depends(get_db)):
+ """
+ Retrieves the aggregate usage statistics (count) for ALL tools in the application.
+ Data is aggregated by the unique tool_name (e.g., 'pdf_merge', 'image_resize').
+ Requires admin privileges.
+ """
+ stats = get_all_tool_stats(db)
+ return {"status": "success", "data": stats}
+
+# ➕ NEW ENDPOINT: Daily Usage Statistics
+@router.get("/daily_usage")
+async def api_get_daily_usage(db: Session = Depends(get_db)):
+ """
+ Retrieves the total usage count aggregated by day.
+ This provides time-series data for dashboard trending charts.
+ Requires admin privileges.
+ """
+ stats = get_tool_usage_by_day(db)
+ return {"status": "success", "data": stats}
+
+@router.get("/monthly_usage")
+async def api_get_monthly_usage(db: Session = Depends(get_db)):
+ """
+ Retrieves the total usage count aggregated by Year and Month (YYYY-MM).
+ Provides time-series data for long-term monthly trend charts.
+ Requires admin privileges.
+ """
+ stats = get_tool_usage_by_month(db)
+ return {"status": "success", "data": stats}
+
+# ➕ NEW ENDPOINT: Yearly Usage Statistics
+@router.get("/yearly_usage")
+async def api_get_yearly_usage(db: Session = Depends(get_db)):
+ """
+ Retrieves the total usage count aggregated by Year (YYYY).
+ Provides time-series data for yearly trend charts.
+ Requires admin privileges.
+ """
+ stats = get_tool_usage_by_year(db)
+ return {"status": "success", "data": stats}
diff --git a/routers/tool_tracking.py b/routers/tool_tracking.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd2e6c1700e27f829982277f33928207a31b2b59
--- /dev/null
+++ b/routers/tool_tracking.py
@@ -0,0 +1,31 @@
+from fastapi import APIRouter, Depends
+from sqlalchemy.orm import Session
+from core.database import get_db
+from services.stats_service import increment_tool_usage
+
+router = APIRouter(prefix="/tool", tags=["Tool Tracking"])
+
+@router.post("/open")
+async def track_open(data: dict, db: Session = Depends(get_db)):
+ tool = data.get("tool")
+ if not tool:
+ return {"status": "error", "message": "Tool name missing"}
+ increment_tool_usage(db, tool, "open")
+ return {"status": "success"}
+
+@router.post("/process")
+async def track_process(data: dict, db: Session = Depends(get_db)):
+ tool = data.get("tool")
+ if not tool:
+ return {"status": "error", "message": "Tool name missing"}
+ increment_tool_usage(db, tool, "process")
+ return {"status": "success"}
+
+@router.post("/download")
+async def track_download(data: dict, db: Session = Depends(get_db)):
+ tool = data.get("tool")
+ if not tool:
+ return {"status": "error", "message": "Tool name missing"}
+ increment_tool_usage(db, tool, "download")
+ return {"status": "success"}
+
diff --git a/routers/universal_converter_full.py b/routers/universal_converter_full.py
new file mode 100644
index 0000000000000000000000000000000000000000..56f262d982b7f6f1d7092bd4778b8dc8dad7030f
--- /dev/null
+++ b/routers/universal_converter_full.py
@@ -0,0 +1,88 @@
+from fastapi import (
+ APIRouter, UploadFile, File, Form,
+ HTTPException, Depends
+)
+from sqlalchemy.orm import Session
+import uuid, traceback, os
+
+from celery.result import AsyncResult
+from celery_app import celery_app
+from fastapi.responses import FileResponse
+from fastapi.concurrency import run_in_threadpool # ⭐
+
+from core.database import get_db
+from core.dependencies import LogToolUsage
+from utils.file_utils import save_bytes_to_file
+from workers.converter_worker import convert_task
+
+router = APIRouter()
+
+@router.post(
+ "/file",
+ dependencies=[Depends(LogToolUsage("universal_converter"))],
+)
+async def convert_endpoint(
+ file: UploadFile = File(...),
+ target: str = Form(...),
+ db: Session = Depends(get_db),
+):
+ try:
+ data = await file.read()
+ if not data:
+ raise HTTPException(400, "Empty file")
+
+ job_id = str(uuid.uuid4())
+
+ input_path = await run_in_threadpool( # ⭐
+ save_bytes_to_file,
+ data,
+ f"{job_id}_{file.filename}"
+ )
+
+ task = convert_task.delay(input_path, target)
+
+ return {
+ "job_id": task.id,
+ "status": "queued"
+ }
+
+ except Exception as e:
+ traceback.print_exc()
+ raise HTTPException(500, str(e))
+
+
+@router.get("/status/{job_id}")
+def job_status(job_id: str):
+ task = AsyncResult(job_id, app=celery_app)
+
+ if task.state in ("PENDING", "RECEIVED"):
+ return {"status": "queued"}
+
+ if task.state in ("STARTED", "PROCESSING"):
+ return {"status": "processing"}
+
+ if task.state == "SUCCESS":
+ return task.result
+
+ if task.state == "FAILURE":
+ return {"status": "failed"}
+
+ return {"status": task.state}
+
+
+@router.get("/download/{job_id}")
+def download(job_id: str):
+ task = AsyncResult(job_id, app=celery_app)
+
+ if not task.result or task.result.get("status") != "done":
+ raise HTTPException(404, "Not ready")
+
+ path = task.result["output_path"]
+
+ if not os.path.exists(path):
+ raise HTTPException(404, "File missing")
+
+ return FileResponse(
+ path,
+ filename=os.path.basename(path)
+ )
diff --git a/routers/utility.py b/routers/utility.py
new file mode 100644
index 0000000000000000000000000000000000000000..0465c80bd5d1c618e936d8230f9aa13699f0d498
--- /dev/null
+++ b/routers/utility.py
@@ -0,0 +1,112 @@
+# backend/routers/utility.py
+from fastapi import APIRouter, Form, Depends
+from sqlalchemy.orm import Session
+from core.database import get_db
+
+# 🔑 IMPORT THE AUTOMATIC LOGGING DEPENDENCY
+from core.dependencies import LogToolUsage
+# ❌ REMOVED: No longer needed, as the dependency handles the call
+# from services.stats_service import increment_tool_usage
+
+from services.utility_service import (
+ convert_case, word_counter, lorem_ipsum, markdown_preview,
+ url_encode, url_decode, hex_to_rgb, rgb_to_hex, rgb_to_hsl,
+ timestamp_to_human, human_to_timestamp, ip_lookup,
+ generate_uuid, generate_password
+)
+
+router = APIRouter()
+
+# ---------------- TEXT TOOLS ----------------
+
+# ✅ /case-convert - ADDED DEPENDENCY & REMOVED MANUAL CALL
+@router.post("/case-convert", dependencies=[Depends(LogToolUsage("case_convert"))])
+async def api_case_convert(text: str = Form(...), mode: str = Form("upper"), db: Session = Depends(get_db)):
+ out = convert_case(text, mode)
+ # increment_tool_usage(db, "case_convert") # REMOVED
+ return {"result": out}
+
+# ✅ /word-counter - ADDED DEPENDENCY & REMOVED MANUAL CALL
+@router.post("/word-counter", dependencies=[Depends(LogToolUsage("word_counter"))])
+async def api_word_counter(text: str = Form(...), db: Session = Depends(get_db)):
+ out = word_counter(text)
+ # increment_tool_usage(db, "word_counter") # REMOVED
+ return out
+
+# ✅ /lorem-ipsum - ADDED DEPENDENCY & REMOVED MANUAL CALL
+@router.post("/lorem-ipsum", dependencies=[Depends(LogToolUsage("lorem_ipsum"))])
+async def api_lorem(paragraphs: int = Form(1), db: Session = Depends(get_db)):
+ out = lorem_ipsum(paragraphs)
+ # increment_tool_usage(db, "lorem_ipsum") # REMOVED
+ return {"text": out}
+
+# ✅ /markdown-preview - ADDED DEPENDENCY & REMOVED MANUAL CALL
+@router.post("/markdown-preview", dependencies=[Depends(LogToolUsage("markdown_preview"))])
+async def api_md_preview(text: str = Form(...), db: Session = Depends(get_db)):
+ html = markdown_preview(text)
+ # increment_tool_usage(db, "markdown_preview") # REMOVED
+ return {"html": html}
+
+# ---------------- WEB & DATA ----------------
+
+# ✅ /url-encode - ADDED DEPENDENCY & REMOVED MANUAL CALL
+@router.post("/url-encode", dependencies=[Depends(LogToolUsage("url_encode"))])
+async def api_url_encode(text: str = Form(...), db: Session = Depends(get_db)):
+ # increment_tool_usage(db, "url_encode") # REMOVED
+ return {"encoded": url_encode(text)}
+
+# ✅ /url-decode - ADDED DEPENDENCY & REMOVED MANUAL CALL
+@router.post("/url-decode", dependencies=[Depends(LogToolUsage("url_decode"))])
+async def api_url_decode(text: str = Form(...), db: Session = Depends(get_db)):
+ # increment_tool_usage(db, "url_decode") # REMOVED
+ return {"decoded": url_decode(text)}
+
+# ✅ /color/hex-to-rgb - ADDED DEPENDENCY & REMOVED MANUAL CALL
+@router.post("/color/hex-to-rgb", dependencies=[Depends(LogToolUsage("hex_to_rgb"))])
+async def api_hex_to_rgb(hex_color: str = Form(...), db: Session = Depends(get_db)):
+ # increment_tool_usage(db, "hex_to_rgb") # REMOVED
+ return hex_to_rgb(hex_color)
+
+# ✅ /color/rgb-to-hex - ADDED DEPENDENCY & REMOVED MANUAL CALL
+@router.post("/color/rgb-to-hex", dependencies=[Depends(LogToolUsage("rgb_to_hex"))])
+async def api_rgb_to_hex(r: int = Form(...), g: int = Form(...), b: int = Form(...), db: Session = Depends(get_db)):
+ # increment_tool_usage(db, "rgb_to_hex") # REMOVED
+ return {"hex": rgb_to_hex(r, g, b)}
+
+# ✅ /color/rgb-to-hsl - ADDED DEPENDENCY & REMOVED MANUAL CALL
+@router.post("/color/rgb-to-hsl", dependencies=[Depends(LogToolUsage("rgb_to_hsl"))])
+async def api_rgb_to_hsl(r: int = Form(...), g: int = Form(...), b: int = Form(...), db: Session = Depends(get_db)):
+ # increment_tool_usage(db, "rgb_to_hsl") # REMOVED
+ return rgb_to_hsl(r, g, b)
+
+# ✅ /timestamp/to-human - ADDED DEPENDENCY & REMOVED MANUAL CALL
+@router.post("/timestamp/to-human", dependencies=[Depends(LogToolUsage("ts_to_human"))])
+async def api_ts_to_human(ts: int = Form(...), db: Session = Depends(get_db)):
+ # increment_tool_usage(db, "ts_to_human") # REMOVED
+ return {"datetime": timestamp_to_human(ts)}
+
+# ✅ /timestamp/to-timestamp - ADDED DEPENDENCY & REMOVED MANUAL CALL
+@router.post("/timestamp/to-timestamp", dependencies=[Depends(LogToolUsage("human_to_ts"))])
+async def api_human_to_ts(date_str: str = Form(...), db: Session = Depends(get_db)):
+ # increment_tool_usage(db, "human_to_ts") # REMOVED
+ return {"timestamp": human_to_timestamp(date_str)}
+
+# ✅ /ip-lookup - ADDED DEPENDENCY & REMOVED MANUAL CALL
+@router.post("/ip-lookup", dependencies=[Depends(LogToolUsage("ip_lookup"))])
+async def api_ip_lookup(ip: str = Form(...), db: Session = Depends(get_db)):
+ # increment_tool_usage(db, "ip_lookup") # REMOVED
+ return ip_lookup(ip)
+
+# ---------------- SECURITY & ID ----------------
+
+# ✅ /uuid - ADDED DEPENDENCY & REMOVED MANUAL CALL
+@router.post("/uuid", dependencies=[Depends(LogToolUsage("uuid_gen"))])
+async def api_uuid(db: Session = Depends(get_db)):
+ # increment_tool_usage(db, "uuid_gen") # REMOVED
+ return {"uuid": generate_uuid()}
+
+# ✅ /password - ADDED DEPENDENCY & REMOVED MANUAL CALL
+@router.post("/password", dependencies=[Depends(LogToolUsage("password_gen"))])
+async def api_password(length: int = Form(12), upper: bool = Form(True), digits: bool = Form(True), symbols: bool = Form(True), db: Session = Depends(get_db)):
+ # increment_tool_usage(db, "password_gen") # REMOVED
+ return {"password": generate_password(length, upper, digits, symbols)}
diff --git a/routers/video.py b/routers/video.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd7d25d29c41282536f30cb2c6ed670f029009ae
--- /dev/null
+++ b/routers/video.py
@@ -0,0 +1,1285 @@
+
+
+import os, uuid, shutil, subprocess, mimetypes
+from pathlib import Path
+from fastapi import APIRouter, UploadFile, File, Form, HTTPException, Request
+from fastapi.responses import FileResponse
+import ffmpeg
+from utils.response_utils import send_file
+from typing import List
+import asyncio
+
+router = APIRouter()
+
+BASE_URL = "https://api.cloudaipdf.com"
+UPLOAD_DIR = Path("static/uploads")
+OUTPUT_DIR = Path("static/output")
+
+UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
+OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
+
+
+
+# ---------------- SAVE FILE ----------------
+def save_upload_file(file: UploadFile) -> str:
+ ext = os.path.splitext(file.filename)[1]
+ name = f"{uuid.uuid4().hex}{ext}"
+ path_obj = UPLOAD_DIR / name
+
+ with open(path_obj, "wb") as buffer:
+ shutil.copyfileobj(file.file, buffer)
+
+ return str(path_obj)
+
+
+# ---------------- UPLOAD VIDEO ----------------
+@router.post("/upload")
+async def upload_video(file: UploadFile = File(...)):
+ try:
+ # ---------------- SAVE ORIGINAL ----------------
+ saved_path = save_upload_file(file)
+ file_id = os.path.basename(saved_path)
+
+ preview_path = UPLOAD_DIR / f"{file_id}_preview.mp4"
+
+ # ---------------- FFMPEG PREVIEW BUILD ----------------
+ cmd = [
+ "ffmpeg", "-y",
+
+ # regenerate timestamps (fix reels/shorts duration)
+ "-fflags", "+genpts",
+
+ "-i", saved_path,
+
+ # map video + optional audio
+ "-map", "0:v:0",
+ "-map", "0:a?",
+ "-sn",
+ "-dn",
+ "-ignore_unknown",
+
+ # rebuild timeline
+ "-vf", "fps=30",
+
+ # encoding
+ "-c:v", "libx264",
+ "-preset", "veryfast",
+ "-crf", "28",
+ "-pix_fmt", "yuv420p",
+ "-r", "30",
+
+ # container fixes
+ "-movflags", "+faststart",
+ "-metadata", "title=preview",
+ "-avoid_negative_ts", "make_zero",
+
+ str(preview_path)
+ ]
+
+ subprocess.run(cmd, check=True)
+
+ # ---------------- RESPONSE ----------------
+ return {
+ "fileId": file_id,
+ "previewUrl": f"/video/preview/{preview_path.name}"
+ }
+
+ except subprocess.CalledProcessError as e:
+ raise HTTPException(500, f"FFmpeg failed: {str(e)}")
+
+
+# ---------------- PREVIEW VIDEO ----------------
+@router.get("/preview/{file_id}")
+async def preview_video(file_id: str):
+ path = UPLOAD_DIR / file_id
+
+ if not path.exists():
+ raise HTTPException(404, "File not found")
+
+ return FileResponse(
+ path,
+ media_type="video/mp4",
+ headers={"Accept-Ranges": "bytes"}
+ )
+
+# ---------------- EXTRACT AUDIO ----------------
+@router.post("/extract-audio-cloud")
+async def extract_audio_cloud(fileId: str = Form(...), format: str = Form(...)):
+ source_path = UPLOAD_DIR / fileId
+
+ if not source_path.exists():
+ raise HTTPException(404, "Video not found")
+
+ # 🔎 check if video has audio
+ try:
+ probe = ffmpeg.probe(str(source_path))
+ has_audio = any(s["codec_type"] == "audio" for s in probe["streams"])
+ except Exception:
+ raise HTTPException(400, "Unable to read video file")
+
+ if not has_audio:
+ raise HTTPException(400, "This video has no audio track to extract")
+
+ fmt = format.lower()
+
+ # -------- MP3 --------
+ if fmt == "mp3":
+ output_path = UPLOAD_DIR / f"{uuid.uuid4().hex}.mp3"
+ cmd = [
+ "ffmpeg", "-y", "-i", str(source_path),
+ "-vn", "-map", "a",
+ "-c:a", "libmp3lame",
+ "-b:a", "192k",
+ str(output_path)
+ ]
+
+ # -------- WAV --------
+ elif fmt == "wav":
+ output_path = UPLOAD_DIR / f"{uuid.uuid4().hex}.wav"
+ cmd = [
+ "ffmpeg", "-y", "-i", str(source_path),
+ "-vn", "-map", "a",
+ "-ac", "2",
+ "-ar", "44100",
+ str(output_path)
+ ]
+
+ # -------- AAC -> M4A CONTAINER --------
+ elif fmt == "aac":
+ output_path = UPLOAD_DIR / f"{uuid.uuid4().hex}.m4a"
+ cmd = [
+ "ffmpeg", "-y", "-i", str(source_path),
+ "-vn", "-map", "a",
+ "-c:a", "aac",
+ "-b:a", "192k",
+ "-movflags", "+faststart",
+ str(output_path)
+ ]
+
+ else:
+ raise HTTPException(400, "Invalid format")
+
+ subprocess.run(cmd, check=True)
+
+ # ⬇️ return directly (do NOT use send_file here)
+ mime, _ = mimetypes.guess_type(str(output_path))
+
+ return FileResponse(
+ str(output_path),
+ media_type=mime or "application/octet-stream",
+ filename=os.path.basename(output_path),
+ headers={"Accept-Ranges": "bytes"}
+ )
+
+# ---------------- MERGE VIDEOS ----------------
+# ---------------- MERGE VIDEOS (UNIVERSAL) ----------------
+@router.post("/merge")
+async def merge_videos(
+ request: Request,
+ files: List[UploadFile] = File(...),
+ outputFormat: str = Form("mp4")
+):
+ if len(files) < 2:
+ raise HTTPException(400, "Select at least 2 videos")
+
+ saved_files = []
+
+ # ---------------- SAVE UPLOADS ----------------
+ for f in files:
+ path = save_upload_file(f)
+ saved_files.append(path)
+
+ normalized_files = []
+
+ # ---------------- NORMALIZE EACH VIDEO ----------------
+ for src in saved_files:
+ norm = OUTPUT_DIR / f"{uuid.uuid4().hex}_norm.mp4"
+
+ cmd = [
+ "ffmpeg","-y",
+ "-i", src,
+ "-vf","scale=1280:-2,fps=30",
+ "-c:v","libx264",
+ "-preset","veryfast",
+ "-crf","23",
+ "-c:a","aac",
+ str(norm)
+ ]
+ subprocess.run(cmd, check=True)
+
+ normalized_files.append(norm)
+
+ # ---------------- CONCAT LIST ----------------
+ list_file = OUTPUT_DIR / f"{uuid.uuid4().hex}.txt"
+ with open(list_file, "w") as f:
+ for path in normalized_files:
+ f.write(f"file '{path.resolve()}'\n")
+
+ # ---------------- OUTPUT FILE ----------------
+ out_file = OUTPUT_DIR / f"{uuid.uuid4().hex}.{outputFormat.lower()}"
+
+ codec_map = {
+ "mp4": ("libx264","aac","video/mp4"),
+ "mov": ("libx264","aac","video/quicktime"),
+ "avi": ("mpeg4","mp3","video/x-msvideo"),
+ "webm": ("libvpx-vp9","libopus","video/webm"),
+ "mkv": ("libx264","aac","video/x-matroska")
+ }
+
+ vcodec, acodec, mime = codec_map.get(
+ outputFormat.lower(),
+ ("libx264","aac","video/mp4")
+ )
+
+ # ---------------- CONCAT + ENCODE ----------------
+ cmd = [
+ "ffmpeg","-y",
+ "-f","concat","-safe","0",
+ "-i", str(list_file),
+ "-c:v", vcodec,
+ "-c:a", acodec,
+ "-preset","veryfast",
+ "-crf","23",
+ str(out_file)
+ ]
+
+ process = await asyncio.create_subprocess_exec(
+ *cmd,
+ stdout=asyncio.subprocess.DEVNULL,
+ stderr=asyncio.subprocess.DEVNULL
+ )
+
+ while True:
+ if process.returncode is not None:
+ break
+
+ if await request.is_disconnected():
+ process.terminate()
+ return {"detail": "Merge cancelled — user closed the page"}
+
+ await asyncio.sleep(0.5)
+
+ await process.wait()
+
+ os.remove(list_file)
+
+ # ---------------- RETURN FILE ----------------
+ return FileResponse(
+ str(out_file),
+ filename=os.path.basename(out_file),
+ media_type=mime,
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Length": str(os.path.getsize(out_file)),
+ "Access-Control-Expose-Headers": "Content-Length"
+ }
+ )
+
+@router.delete("/delete/{file_id}")
+async def delete_uploaded_video(file_id: str):
+ path = UPLOAD_DIR / file_id
+
+ if path.exists():
+ os.remove(path)
+
+ return {"status": "deleted"}
+
+# ---------------- CONVERT VIDEO ----------------
+# ---------------- CONVERT / COMPRESS VIDEO (KEEP ORIGINAL FORMAT) ----------------
+@router.post("/compress")
+async def compress_video(
+ request: Request,
+ video: UploadFile = File(...),
+ quality: float = Form(0.7),
+ resolution: str = Form("original"),
+ removeAudio: bool = Form(False)
+):
+ source = Path(save_upload_file(video))
+
+ # detect original format
+ ext = source.suffix.lower().lstrip(".") or "mp4"
+ out_file = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ # CRF based on quality
+ crf = int(max(10, min(35, 30 - (quality * 15))))
+
+ # codec mapping based on container
+ codec_map = {
+ "mp4": ("libx264", "aac", ["-movflags","+faststart"], "video/mp4"),
+ "mov": ("libx264", "aac", [], "video/quicktime"),
+ "mkv": ("libx264", "aac", [], "video/x-matroska"),
+ "avi": ("mpeg4", "mp3", [], "video/x-msvideo"),
+ "webm": ("libvpx-vp9", "libopus", [], "video/webm")
+ }
+
+ vcodec, acodec, extra_flags, mime = codec_map.get(
+ ext, ("libx264","aac",[],"video/mp4")
+ )
+
+ cmd = [
+ "ffmpeg","-y",
+ "-i", str(source),
+ "-map","0:v:0",
+ "-map","0:a?",
+ "-c:v", vcodec,
+ "-preset","medium",
+ "-crf", str(crf)
+ ]
+
+ # resolution scaling
+ if resolution == "1080p":
+ cmd += ["-vf","scale=-2:1080"]
+ elif resolution == "720p":
+ cmd += ["-vf","scale=-2:720"]
+ elif resolution == "480p":
+ cmd += ["-vf","scale=-2:480"]
+
+ if removeAudio:
+ cmd += ["-an"]
+ else:
+ cmd += ["-c:a", acodec]
+
+ cmd += [*extra_flags, str(out_file)]
+
+ process = await asyncio.create_subprocess_exec(
+ *cmd,
+ stdout=asyncio.subprocess.DEVNULL,
+ stderr=asyncio.subprocess.DEVNULL
+ )
+
+ await process.wait()
+
+ if not out_file.exists():
+ raise HTTPException(500, "Compression failed")
+
+ return FileResponse(
+ str(out_file),
+ filename=f"compressed.{ext}",
+ media_type=mime,
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Length": str(os.path.getsize(out_file)),
+ "Access-Control-Expose-Headers": "Content-Length"
+ }
+ )
+# ---------------- SERVE RESULT ----------------
+@router.get("/result/{file}")
+async def get_result(file: str):
+ path = OUTPUT_DIR / file
+ if not path.exists():
+ raise HTTPException(404, "Result not found")
+
+ return FileResponse(
+ path,
+ media_type="video/mp4",
+ headers={"Accept-Ranges":"bytes"}
+ )
+# ---------------- VEDIO-GIF ----------------
+@router.post("/gif")
+async def video_to_gif(
+ fileId: str = Form(...),
+ start: float = Form(...),
+ end: float = Form(...),
+ fps: int = Form(...),
+ width: int = Form(...)
+):
+ source = UPLOAD_DIR / fileId
+ if not source.exists():
+ raise HTTPException(404, "Video not found")
+
+ out_path = OUTPUT_DIR / f"{uuid.uuid4().hex}.gif"
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-ss", str(start),
+ "-to", str(end),
+ "-i", str(source),
+ "-vf", f"fps={fps},scale={width}:-1:flags=lanczos",
+ "-loop", "0",
+ str(out_path)
+ ]
+
+ subprocess.run(cmd, check=True)
+
+ return FileResponse(out_path, filename="output.gif", media_type="image/gif")
+# ---------------- VEDIO-TRIM ----------------
+@router.post("/trim")
+async def trim_video(
+ fileId: str = Form(...),
+ start: float = Form(...),
+ end: float = Form(...),
+ quality: str = Form("medium")
+):
+ source = UPLOAD_DIR / fileId
+ if not source.exists():
+ raise HTTPException(404, "Video not found")
+
+ # 🚨 validate trim range
+ if end <= start:
+ raise HTTPException(400, "End time must be greater than start time")
+
+ # ✅ detect original extension automatically
+ format = source.suffix.lstrip(".").lower()
+
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{format}"
+
+ # choose encoder based on format
+ video_codec = "libx264"
+ audio_codec = "aac"
+
+ if format == "webm":
+ video_codec = "libvpx-vp9"
+ audio_codec = "libopus"
+ elif format == "avi":
+ video_codec = "mpeg4"
+ audio_codec = "mp3"
+ elif format == "mov":
+ video_codec = "libx264"
+ audio_codec = "aac"
+ elif format == "mkv":
+ video_codec = "libx264"
+ audio_codec = "aac"
+
+ # quality presets
+ crf_map = {"high": "18", "medium": "23", "low": "30"}
+ crf = crf_map.get(quality, "23")
+
+ duration = end - start
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-ss", str(start),
+ "-i", str(source),
+ "-t", str(duration), # safer than -to
+ "-c:v", video_codec,
+ "-crf", crf,
+ "-preset", "medium",
+ "-c:a", audio_codec,
+ "-movflags", "+faststart",
+ str(out)
+ ]
+
+ subprocess.run(cmd, check=True)
+
+ return FileResponse(
+ out,
+ filename=f"trimmed.{format}",
+ media_type=f"video/{format if format!='avi' else 'x-msvideo'}"
+ )
+
+
+# ---------------- VEDIO-STABLIZER ----------------
+@router.post("/stabilize")
+async def stabilize_video(
+ fileId: str = Form(...),
+ level: str = Form("medium")
+):
+
+ source = UPLOAD_DIR / fileId
+ if not source.exists():
+ raise HTTPException(404, "Video not found")
+
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
+
+ # detect original extension
+ ext = source.suffix.lower().lstrip(".") # e.g. mp4, mov, mkv
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+ trans = OUTPUT_DIR / f"{uuid.uuid4().hex}.trf"
+
+ shakemap = {
+ "low": "5",
+ "medium": "10",
+ "high": "20"
+ }
+
+ try:
+ # 1️⃣ detect shake
+ detect_cmd = [
+ "ffmpeg", "-y",
+ "-i", str(source),
+ "-vf", f"vidstabdetect=shakiness=5:result={trans}",
+ "-f", "null", "-"
+ ]
+ subprocess.run(detect_cmd, check=True)
+
+ # 2️⃣ pick correct encoding based on format
+ video_codec = "libx264"
+ audio_codec = "aac"
+ media_type = "video/mp4"
+
+ if ext in ["webm"]:
+ video_codec = "libvpx-vp9"
+ audio_codec = "libopus"
+ media_type = "video/webm"
+
+ elif ext in ["mkv"]:
+ video_codec = "libx264"
+ audio_codec = "aac"
+ media_type = "video/x-matroska"
+
+ elif ext in ["avi"]:
+ video_codec = "mpeg4"
+ audio_codec = "mp3"
+ media_type = "video/x-msvideo"
+
+ elif ext in ["mov"]:
+ video_codec = "libx264"
+ audio_codec = "aac"
+ media_type = "video/quicktime"
+
+ transform_cmd = [
+ "ffmpeg", "-y",
+ "-i", str(source),
+ "-vf", f"vidstabtransform=input={trans}:smoothing={shakemap.get(level,'10')}",
+ "-c:v", video_codec,
+ "-preset", "medium",
+ "-crf", "22",
+ "-c:a", audio_codec,
+ "-movflags", "+faststart",
+ str(out)
+ ]
+
+ subprocess.run(transform_cmd, check=True)
+
+ except subprocess.CalledProcessError as e:
+ raise HTTPException(500, f"FFmpeg failed: {e}")
+
+ finally:
+ if trans.exists():
+ trans.unlink(missing_ok=True)
+
+ return FileResponse(
+ out,
+ filename=f"stabilized.{ext}",
+ media_type=media_type
+ )
+
+# ---------------- VIDEO CROP ----------------
+@router.post("/crop")
+async def crop_video(
+ fileId: str = Form(...),
+ x: int = Form(...),
+ y: int = Form(...),
+ width: int = Form(...),
+ height: int = Form(...)
+):
+ source = UPLOAD_DIR / fileId
+
+ if not source.exists():
+ raise HTTPException(404, "Video not found")
+
+ if width <= 0 or height <= 0:
+ raise HTTPException(400, "Invalid crop size")
+
+ ext = source.suffix.lstrip(".").lower() or "mp4"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ # choose codecs & mime type based on format
+ codec_map = {
+ "mp4": ("libx264", "aac", "video/mp4", ["-movflags", "+faststart"]),
+ "mov": ("libx264", "aac", "video/quicktime", []),
+ "mkv": ("libx264", "aac", "video/x-matroska", []),
+ "avi": ("mpeg4", "mp3", "video/x-msvideo", []),
+ "webm": ("libvpx-vp9", "libopus", "video/webm", [])
+ }
+
+ video_codec, audio_codec, mime, extra_flags =codec_map.get(
+ ext, ("libx264", "aac", f"video/{ext}", []))
+
+ try:
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(source),
+ "-filter:v", f"crop={width}:{height}:{x}:{y}",
+ "-c:v", video_codec,
+ "-preset", "medium",
+ "-crf", "22",
+ "-c:a", audio_codec,
+ *extra_flags,
+ str(out)
+ ]
+
+ subprocess.run(cmd, check=True)
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(500, "Cropping failed")
+
+ return FileResponse(
+ out,
+ filename=f"cropped.{ext}",
+ media_type=mime,
+ headers={"Accept-Ranges": "bytes"}
+ )
+
+# ---------------- VIDEO FILTER ----------------
+# ---------------- VIDEO FILTER ----------------
+@router.post("/filter")
+async def apply_filter(
+ fileId: str = Form(...),
+ filter: str = Form(...)
+):
+ source = UPLOAD_DIR / fileId
+ if not source.exists():
+ raise HTTPException(404, "Video not found")
+
+ ext = source.suffix.lstrip(".").lower() or "mp4"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ # choose codecs based on format
+ codec_map = {
+ "mp4": ("libx264", "aac", "video/mp4"),
+ "mov": ("libx264", "aac", "video/quicktime"),
+ "mkv": ("libx264", "aac", "video/x-matroska"),
+ "avi": ("mpeg4", "mp3", "video/x-msvideo"),
+ "webm": ("libvpx-vp9", "libopus", "video/webm")
+ }
+
+ vcodec, acodec, mime = codec_map.get(
+ ext, ("libx264", "aac", "video/mp4")
+ )
+
+ filter_map = {
+ "grayscale": "format=gray",
+ "sepia": "colorchannelmixer=.393:.769:.189:.349:.686:.168:.272:.534:.131",
+ "invert": "negate",
+ "vintage": "curves=vintage",
+ "cool": "eq=saturation=1.3:contrast=1.1:brightness=0.03",
+ "warm": "colorbalance=rs=.2",
+ "none": "null"
+ }
+
+ vf = filter_map.get(filter, "null")
+
+ subprocess.run([
+ "ffmpeg","-y",
+ "-i", str(source),
+ "-vf", vf,
+ "-c:v", vcodec,
+ "-preset", "medium",
+ "-crf", "22",
+ "-c:a", acodec,
+ str(out)
+ ], check=True)
+
+ return FileResponse(out, filename=f"filtered.{ext}", media_type=mime)
+
+
+# ---------------- VIDEO MUTE ----------------
+@router.post("/mute")
+async def mute_video(fileId: str = Form(...)):
+ source = UPLOAD_DIR / fileId
+
+ if not source.exists():
+ raise HTTPException(404, "Video not found")
+
+ ext = source.suffix.lstrip(".") or "mp4"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ try:
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(source),
+ "-c:v", "copy",
+ "-an", # <— remove audio
+ "-movflags", "+faststart",
+ str(out)
+ ]
+
+ subprocess.run(cmd, check=True)
+
+ except subprocess.CalledProcessError:
+ raise HTTPException(500, "Muting failed")
+
+ return FileResponse(
+ out,
+ filename=f"muted.{ext}",
+ media_type=f"video/{ext}",
+ headers={"Accept-Ranges": "bytes"}
+ )
+
+# ---------------- VIDEO-REVERSER ----------------
+@router.post("/reverse")
+async def reverse_video(fileId: str = Form(...)):
+ source = UPLOAD_DIR / fileId
+
+ if not source.exists():
+ raise HTTPException(404, "Video not found")
+
+ ext = source.suffix.lower().lstrip(".") or "mp4"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ # container-specific codec mapping
+ codec_map = {
+ "mp4": ("libx264", "aac", ["-movflags", "+faststart"], "video/mp4"),
+ "mov": ("libx264", "aac", [], "video/quicktime"),
+ "mkv": ("libx264", "aac", [], "video/x-matroska"),
+ "avi": ("mpeg4", "mp3", [], "video/x-msvideo"),
+ "webm": ("libvpx-vp9", "libopus", [], "video/webm"),
+ }
+
+ vcodec, acodec, extra_flags, mime = codec_map.get(
+ ext, ("libx264", "aac", [], f"video/{ext}")
+ )
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(source),
+ "-filter_complex", "[0:v]reverse[v]",
+ "-map", "[v]",
+ "-map", "0:a?",
+ "-c:v", vcodec,
+ "-preset", "medium",
+ "-crf", "22",
+ "-c:a", acodec,
+ *extra_flags,
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0:
+ print(result.stderr)
+ raise HTTPException(500, "FFmpeg failed")
+
+ return FileResponse(
+ out,
+ filename=f"reversed.{ext}",
+ media_type=mime,
+ headers={"Accept-Ranges": "bytes"}
+ )
+
+# ---------------- VIDEO-ROTATE ----------------
+@router.post("/rotate")
+async def rotate_video(
+ video: UploadFile = File(...),
+ rotation: int = Form(...),
+ flipH: bool = Form(...),
+ flipV: bool = Form(...)
+):
+ source_path = save_upload_file(video)
+
+ ext = Path(source_path).suffix.lstrip(".") or "mp4"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ # build filter chain
+ filters = []
+
+ # rotation (normalized)
+ r = rotation % 360
+ if r == 90:
+ filters.append("transpose=1")
+ elif r == 180:
+ filters.append("transpose=1,transpose=1")
+ elif r == 270:
+ filters.append("transpose=2")
+
+ if flipH:
+ filters.append("hflip")
+ if flipV:
+ filters.append("vflip")
+
+ filter_chain = ",".join(filters) if filters else "null"
+
+ cmd = [
+ "ffmpeg","-y",
+ "-i", source_path,
+ "-vf", filter_chain,
+ "-c:v","libx264","-preset","medium","-crf","22",
+ "-c:a","copy",
+ "-movflags","+faststart",
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+ if result.returncode != 0:
+ raise HTTPException(500, f"FFmpeg failed:\n{result.stderr}")
+
+ return FileResponse(
+ out,
+ filename=f"rotated.{ext}",
+ media_type=f"video/{ext}",
+ headers={"Accept-Ranges": "bytes"}
+ )
+
+# ---------------- VIDEO-EXTRACT-THUMBNAIL ----------------
+@router.post("/extract-thumbnail")
+async def extract_thumbnail(
+ fileId: str = Form(...),
+ timestamp: float = Form(...),
+ format: str = Form("jpg")
+):
+ source = UPLOAD_DIR / fileId
+
+ if not source.exists():
+ raise HTTPException(404, "Video not found")
+
+ format = format.lower()
+ if format not in ("jpg", "png", "webp"):
+ format = "jpg"
+
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{format}"
+
+ cmd = [
+ "ffmpeg",
+ "-y",
+ "-ss", str(timestamp),
+ "-i", str(source),
+ "-frames:v", "1",
+ "-q:v", "2",
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0 or not out.exists():
+ print(result.stderr)
+ raise HTTPException(500, "Thumbnail extraction failed")
+
+ return FileResponse(
+ out,
+ filename=f"thumbnail.{format}",
+ media_type=f"image/{format}"
+ )
+# ---------------- VIDEO-VOLUME ----------------
+@router.post("/volume")
+async def adjust_volume(
+ video: UploadFile = File(...),
+ volume: float = Form(...)
+):
+ source = save_upload_file(video)
+
+ # detect extension
+ ext = Path(source).suffix.lstrip(".") or "mp4"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ # FFmpeg filter: volume=1.5 (150%)
+ cmd = [
+ "ffmpeg",
+ "-y",
+ "-i", str(source),
+ "-filter:a", f"volume={volume}",
+ "-c:v", "copy", # KEEP VIDEO SAME
+ "-movflags", "+faststart",
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0:
+ raise HTTPException(500, f"FFmpeg failed:\n{result.stderr}")
+
+ return FileResponse(
+ out,
+ filename=f"volume_adjusted.{ext}",
+ media_type=f"video/{ext}",
+ headers={"Accept-Ranges": "bytes"}
+ )
+
+# ---------------- VIDEO-SPEED ----------------
+@router.post("/speed")
+async def speed_video(
+ fileId: str = Form(...),
+ speed: float = Form(...),
+ preservePitch: int = Form(1),
+ fadeIn: float = Form(0),
+ fadeOut: float = Form(0),
+):
+ src = UPLOAD_DIR / fileId
+ if not src.exists():
+ raise HTTPException(404, "File not found")
+
+ if speed <= 0:
+ raise HTTPException(400, "Invalid speed")
+
+ ext = src.suffix.lower().lstrip(".") or "mp4"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ # ------------------------------
+ # detect audio stream
+ # ------------------------------
+ try:
+ probe = ffmpeg.probe(str(src))
+ has_audio = any(s["codec_type"] == "audio" for s in probe["streams"])
+ except Exception:
+ has_audio = False
+
+ # ------------------------------
+ # codec selection
+ # ------------------------------
+ codec_map = {
+ "mp4": ("libx264", "aac", ["-movflags", "+faststart"], "video/mp4"),
+ "mov": ("libx264", "aac", [], "video/quicktime"),
+ "mkv": ("libx264", "aac", [], "video/x-matroska"),
+ "avi": ("mpeg4", "mp3", [], "video/x-msvideo"),
+ "webm": ("libvpx-vp9", "libopus", [], "video/webm"),
+ }
+
+ vcodec, acodec, extra_flags, mime = codec_map.get(
+ ext, ("libx264", "aac", [], f"video/{ext}")
+ )
+
+ # ------------------------------
+ # VIDEO speed
+ # ------------------------------
+ vf = f"setpts=PTS/{speed}"
+
+ # ------------------------------
+ # CASE 1️⃣ — VIDEO ONLY (NO AUDIO)
+ # ------------------------------
+ if not has_audio:
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vf", vf,
+ "-c:v", vcodec,
+ "-crf", "22",
+ "-preset", "medium",
+ *extra_flags,
+ str(out)
+ ]
+
+ # ------------------------------
+ # CASE 2️⃣ — VIDEO + AUDIO
+ # ------------------------------
+ else:
+ afilters = []
+
+ if preservePitch:
+ tempo = speed
+ while tempo > 2.0:
+ afilters.append("atempo=2.0")
+ tempo /= 2.0
+ while tempo < 0.5:
+ afilters.append("atempo=0.5")
+ tempo /= 0.5
+ afilters.append(f"atempo={tempo}")
+ else:
+ afilters.append(f"atempo={speed}")
+
+ if fadeIn > 0:
+ afilters.append(f"afade=t=in:st=0:d={fadeIn}")
+
+ if fadeOut > 0:
+ afilters.append(f"afade=t=out:d={fadeOut}")
+
+ af = ",".join(afilters)
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-filter_complex",
+ f"[0:v]{vf}[v];[0:a]{af}[a]",
+ "-map", "[v]",
+ "-map", "[a]",
+ "-c:v", vcodec,
+ "-c:a", acodec,
+ "-crf", "22",
+ "-preset", "medium",
+ *extra_flags,
+ str(out)
+ ]
+
+ # ------------------------------
+ # run ffmpeg
+ # ------------------------------
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0:
+ print("\n===== FFMPEG ERROR =====")
+ print(result.stderr)
+ print("========================\n")
+ raise HTTPException(500, "FFmpeg failed")
+
+ return FileResponse(
+ out,
+ filename=f"speed_{speed}x.{ext}",
+ media_type=mime,
+ headers={"Accept-Ranges": "bytes"}
+ )
+
+# ---------------- VIDEO-TRIMADVANCED ----------------
+@router.post("/trim-advanced")
+async def trim_advanced(
+ fileId: str = Form(...),
+ start: float = Form(...),
+ end: float = Form(...),
+ fadeIn: int = Form(0),
+ fadeOut: int = Form(0)
+):
+ src = UPLOAD_DIR / fileId
+ if not src.exists():
+ raise HTTPException(404, "File not found")
+
+ if end <= start:
+ raise HTTPException(400, "End must be greater than start")
+
+ ext = src.suffix.lower().lstrip(".") or "mp4"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ # ------------------------------
+ # codec selection per container
+ # ------------------------------
+ codec_map = {
+ "mp4": ("libx264", "aac", ["-movflags", "+faststart"], "video/mp4"),
+ "mov": ("libx264", "aac", [], "video/quicktime"),
+ "mkv": ("libx264", "aac", [], "video/x-matroska"),
+ "avi": ("mpeg4", "mp3", [], "video/x-msvideo"),
+ "webm": ("libvpx-vp9", "libopus", [], "video/webm"),
+ }
+
+ vcodec, acodec, extra_flags, mime = codec_map.get(
+ ext, ("libx264", "aac", [], f"video/{ext}")
+ )
+
+ # ------------------------------
+ # fade filters
+ # ------------------------------
+ vf_filters = []
+
+ if fadeIn:
+ vf_filters.append("fade=t=in:st=0:d=1")
+
+ if fadeOut:
+ fade_start = max(0, (end - start) - 1)
+ vf_filters.append(f"fade=t=out:st={fade_start}:d=1")
+
+ vf = ",".join(vf_filters) if vf_filters else "null"
+
+ # ------------------------------
+ # ffmpeg command
+ # ------------------------------
+ cmd = [
+ "ffmpeg", "-y",
+ "-ss", str(start),
+ "-to", str(end),
+ "-i", str(src),
+ "-vf", vf,
+ "-map", "0:v:0",
+ "-map", "0:a?",
+ "-c:v", vcodec,
+ "-c:a", acodec,
+ "-crf", "22",
+ "-preset", "medium",
+ *extra_flags,
+ str(out)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0:
+ print("\n===== FFMPEG ERROR =====")
+ print(result.stderr)
+ print("========================\n")
+ raise HTTPException(500, "FFmpeg failed")
+
+ return FileResponse(
+ out,
+ filename=f"trimmed.{ext}",
+ media_type=mime,
+ headers={"Accept-Ranges": "bytes"}
+ )
+
+
+# ---------------- VIDEO-WATERMARK ----------------
+@router.post("/watermark")
+async def watermark_video(
+ fileId: str = Form(...),
+ type: str = Form(...),
+ posX: float = Form(...),
+ posY: float = Form(...),
+ opacity: float = Form(...),
+ text: str = Form(None),
+ color: str = Form(None),
+ fontFamily: str = Form(None),
+ fontSizePct: float = Form(None),
+ image: UploadFile = File(None),
+ imageSizePct: float = Form(None),
+):
+ src = UPLOAD_DIR / fileId
+ if not src.exists():
+ raise HTTPException(404, "Video not found")
+
+ # -----------------------------
+ # detect format & codecs
+ # -----------------------------
+ ext = src.suffix.lower().lstrip(".") or "mp4"
+ out = OUTPUT_DIR / f"{uuid.uuid4().hex}.{ext}"
+
+ codec_map = {
+ "mp4": ("libx264", "aac", ["-movflags", "+faststart"], "video/mp4"),
+ "mov": ("libx264", "aac", [], "video/quicktime"),
+ "mkv": ("libx264", "aac", [], "video/x-matroska"),
+ "avi": ("mpeg4", "mp3", [], "video/x-msvideo"),
+ "webm": ("libvpx-vp9", "libopus", [], "video/webm"),
+ }
+
+ vcodec, acodec, extra_flags, mime = codec_map.get(
+ ext, ("libx264", "aac", [], f"video/{ext}")
+ )
+
+ # -----------------------------
+ # get video resolution
+ # -----------------------------
+ probe = subprocess.check_output([
+ "ffprobe", "-v", "error",
+ "-select_streams", "v:0",
+ "-show_entries", "stream=width,height",
+ "-of", "csv=p=0",
+ str(src)
+ ]).decode().strip()
+
+ video_w, video_h = map(int, probe.split(","))
+
+ x = int((posX / 100) * video_w)
+ y = int((posY / 100) * video_h)
+
+ # -----------------------------
+ # TEXT WATERMARK
+ # -----------------------------
+ if type == "text":
+ font_size = int(video_w * (fontSizePct or 0.04))
+ font_map = {
+ "Arial": "/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf",
+ "Helvetica": "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
+ "Times New Roman": "/usr/share/fonts/truetype/msttcorefonts/Times_New_Roman_Bold.ttf",
+ "Courier New": "/usr/share/fonts/truetype/msttcorefonts/Courier_New_Bold.ttf",
+ "Verdana": "/usr/share/fonts/truetype/msttcorefonts/Verdana_Bold.ttf",
+ "Georgia": "/usr/share/fonts/truetype/msttcorefonts/Georgia_Bold.ttf",
+ }
+
+ fontfile = font_map.get(
+ fontFamily,
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
+ )
+ draw = (
+ f"drawtext=fontfile={fontfile}:"
+ f"text='{text}':"
+ f"x={x}:y={y}+text_h*0.75:"
+ f"fontsize={font_size}:"
+ f"fontcolor={color}@{opacity}"
+ )
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-vf", draw,
+ "-c:v", vcodec,
+ "-preset", "medium",
+ "-crf", "22",
+ "-c:a", acodec,
+ *extra_flags,
+ str(out)
+ ]
+
+ # -----------------------------
+ # IMAGE WATERMARK
+ # -----------------------------
+ else:
+ if not image:
+ raise HTTPException(400, "Image watermark missing")
+
+ wm_path = OUTPUT_DIR / f"{uuid.uuid4().hex}.png"
+ with open(wm_path, "wb") as f:
+ f.write(await image.read())
+
+ wm_width = int(video_w * (imageSizePct or 0.15))
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", str(src),
+ "-i", str(wm_path),
+ "-filter_complex",
+ f"[1:v]scale={wm_width}:-1,format=rgba,colorchannelmixer=aa={opacity}[wm];"
+ f"[0:v][wm]overlay={x}:{y}",
+ "-c:v", vcodec,
+ "-preset", "medium",
+ "-crf", "22",
+ "-c:a", acodec,
+ *extra_flags,
+ str(out)
+ ]
+
+ # -----------------------------
+ # run ffmpeg
+ # -----------------------------
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0:
+ print("\n===== FFMPEG ERROR =====")
+ print(result.stderr)
+ print("========================\n")
+ raise HTTPException(500, "FFmpeg failed")
+
+ return FileResponse(
+ out,
+ filename=f"watermarked.{ext}",
+ media_type=mime,
+ headers={"Accept-Ranges": "bytes"}
+ )
+
+
+# ---------------- VIDEO-CONVERT ----------------
+@router.post("/convert")
+async def convert_video(
+ video: UploadFile = File(...),
+ format: str = Form(...)
+):
+ source_path = save_upload_file(video)
+
+ format = format.lower()
+ if format not in ["mp4", "mov", "avi", "webm", "mkv", "gif"]:
+ raise HTTPException(400, "Unsupported format")
+
+ out_file = OUTPUT_DIR / f"{uuid.uuid4().hex}.{format}"
+
+ # codec mapping
+ codec_map = {
+ "mp4": ("libx264", "aac", ["-movflags", "+faststart"], "video/mp4"),
+ "mov": ("libx264", "aac", [], "video/quicktime"),
+ "avi": ("mpeg4", "mp3", [], "video/x-msvideo"),
+ "webm": ("libvpx-vp9", "libopus", [], "video/webm"),
+ "mkv": ("libx264", "aac", [], "video/x-matroska"),
+ }
+
+ # GIF handled separately
+ if format == "gif":
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", source_path,
+ "-vf", "fps=15,scale=640:-1:flags=lanczos",
+ "-loop", "0",
+ str(out_file)
+ ]
+ mime = "image/gif"
+
+ else:
+ vcodec, acodec, extra_flags, mime = codec_map[format]
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", source_path,
+ "-c:v", vcodec,
+ "-preset", "medium",
+ "-crf", "22",
+ "-c:a", acodec,
+ *extra_flags,
+ str(out_file)
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0:
+ print(result.stderr)
+ raise HTTPException(500, "Conversion failed")
+
+ return FileResponse(
+ out_file,
+ filename=f"converted.{format}",
+ media_type=mime,
+ headers={
+ "Accept-Ranges": "bytes",
+ "Content-Length": str(os.path.getsize(out_file)),
+ "Access-Control-Expose-Headers": "Content-Length"
+ }
+ )
+
diff --git a/security.sh b/security.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9b1c10c8e9ec76361ccc7e3f8ac77bb626873aef
--- /dev/null
+++ b/security.sh
@@ -0,0 +1,3 @@
+sudo apt install fail2ban
+sudo systemctl enable fail2ban
+sudo systemctl start fail2ban
diff --git a/services/__pycache__/ads_service.cpython-312.pyc b/services/__pycache__/ads_service.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c0a24267401d272b9f039c7913083ec66f4cd975
Binary files /dev/null and b/services/__pycache__/ads_service.cpython-312.pyc differ
diff --git a/services/__pycache__/ads_service.cpython-39.pyc b/services/__pycache__/ads_service.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa4c8d3eab72ef8c6a9ce84101bcafeb0168f143
Binary files /dev/null and b/services/__pycache__/ads_service.cpython-39.pyc differ
diff --git a/services/__pycache__/audio_service.cpython-312.pyc b/services/__pycache__/audio_service.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..89b3598af752c00638be8981f70db1ade334296e
Binary files /dev/null and b/services/__pycache__/audio_service.cpython-312.pyc differ
diff --git a/services/__pycache__/audio_service.cpython-39.pyc b/services/__pycache__/audio_service.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..96cb2848a40a1e27306b45b1ccbe1f369887cb3c
Binary files /dev/null and b/services/__pycache__/audio_service.cpython-39.pyc differ
diff --git a/services/__pycache__/business_service.cpython-312.pyc b/services/__pycache__/business_service.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e07ce180b023bc9570b7f9e9790ea1d8d814434e
Binary files /dev/null and b/services/__pycache__/business_service.cpython-312.pyc differ
diff --git a/services/__pycache__/business_service.cpython-39.pyc b/services/__pycache__/business_service.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ab26f0b35b3100800eb79ca0d70a30b446214d2
Binary files /dev/null and b/services/__pycache__/business_service.cpython-39.pyc differ
diff --git a/services/__pycache__/converter_tools_service.cpython-312.pyc b/services/__pycache__/converter_tools_service.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5fc8706b978f955330ed960059db394cc7fe39b
Binary files /dev/null and b/services/__pycache__/converter_tools_service.cpython-312.pyc differ
diff --git a/services/__pycache__/converter_tools_service.cpython-39.pyc b/services/__pycache__/converter_tools_service.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59a0afb06f407c179e396213f31645ad6af11a7c
Binary files /dev/null and b/services/__pycache__/converter_tools_service.cpython-39.pyc differ
diff --git a/services/__pycache__/developer_service.cpython-312.pyc b/services/__pycache__/developer_service.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b651ed2b9e4bef6ea4304011d6435ebec9bd6809
Binary files /dev/null and b/services/__pycache__/developer_service.cpython-312.pyc differ
diff --git a/services/__pycache__/developer_service.cpython-39.pyc b/services/__pycache__/developer_service.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f57305f28b5613e9bea869f8ab6cd91388f0310
Binary files /dev/null and b/services/__pycache__/developer_service.cpython-39.pyc differ
diff --git a/services/__pycache__/image_service.cpython-312.pyc b/services/__pycache__/image_service.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9bf6768fb13829a0a60edd1daf2aede506f067c4
Binary files /dev/null and b/services/__pycache__/image_service.cpython-312.pyc differ
diff --git a/services/__pycache__/image_service.cpython-39.pyc b/services/__pycache__/image_service.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ff1607fc1e2715a8dcd9a69e8bd255e88a82ce90
Binary files /dev/null and b/services/__pycache__/image_service.cpython-39.pyc differ
diff --git a/services/__pycache__/pdf_service.cpython-312.pyc b/services/__pycache__/pdf_service.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..255b8970651c9d6fc139b6f110e63ed699df6898
Binary files /dev/null and b/services/__pycache__/pdf_service.cpython-312.pyc differ
diff --git a/services/__pycache__/pdf_service.cpython-39.pyc b/services/__pycache__/pdf_service.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..66b9a698ab97ba3ef819de7fe3821747d30a061a
Binary files /dev/null and b/services/__pycache__/pdf_service.cpython-39.pyc differ
diff --git a/services/__pycache__/stats_service.cpython-312.pyc b/services/__pycache__/stats_service.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f225411e001f53567878ff31b7b5e0b478300d0
Binary files /dev/null and b/services/__pycache__/stats_service.cpython-312.pyc differ
diff --git a/services/__pycache__/stats_service.cpython-39.pyc b/services/__pycache__/stats_service.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..39d5081b79faf673d88b35984f54ca00fd4586e5
Binary files /dev/null and b/services/__pycache__/stats_service.cpython-39.pyc differ
diff --git a/services/__pycache__/universal_converter_service.cpython-312.pyc b/services/__pycache__/universal_converter_service.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1b94f6fa3a7d1bb3a3450de88f365ad320bcf963
Binary files /dev/null and b/services/__pycache__/universal_converter_service.cpython-312.pyc differ
diff --git a/services/__pycache__/universal_converter_service.cpython-39.pyc b/services/__pycache__/universal_converter_service.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45585c004fe2967aac24bd972621a92dae4daf77
Binary files /dev/null and b/services/__pycache__/universal_converter_service.cpython-39.pyc differ
diff --git a/services/__pycache__/utility_service.cpython-312.pyc b/services/__pycache__/utility_service.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..65767c138f39733094140b989b8a73fdff4ca620
Binary files /dev/null and b/services/__pycache__/utility_service.cpython-312.pyc differ
diff --git a/services/__pycache__/utility_service.cpython-39.pyc b/services/__pycache__/utility_service.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..830a2d6802a42ba283b6ec0297bf6987da344175
Binary files /dev/null and b/services/__pycache__/utility_service.cpython-39.pyc differ
diff --git a/services/__pycache__/video_service.cpython-312.pyc b/services/__pycache__/video_service.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9534feb0d9dd552c2c39be73c0a7eadd020be864
Binary files /dev/null and b/services/__pycache__/video_service.cpython-312.pyc differ
diff --git a/services/__pycache__/video_service.cpython-39.pyc b/services/__pycache__/video_service.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aceb3896123eca6263f42f0a7ba40c81586243bf
Binary files /dev/null and b/services/__pycache__/video_service.cpython-39.pyc differ
diff --git a/services/ads_service.py b/services/ads_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..579f167afd27e03a9cad95e8177063ffe42efde6
--- /dev/null
+++ b/services/ads_service.py
@@ -0,0 +1,411 @@
+# services/ads_service.py
+import uuid
+import random
+from datetime import datetime
+from typing import Optional, Dict, Any, List
+
+from sqlalchemy.orm import Session
+from sqlalchemy import func
+
+from core.models import AdUnit, AdPlacement, AdStat, AdImpression, AdGlobalSettings
+
+BASE_URL = "https://api.cloudaipdf.com"
+
+def whisper_stt(input_path: str, language: str = "en-US") -> str:
+ """
+ Runs Whisper transcription matching SpeechToTextTool frontend.
+
+ If required runtime packages (numpy / torch / whisper) are missing this will raise
+ a RuntimeError with explicit install instructions.
+ """
+ try:
+ import whisper
+ except Exception as e:
+ raise RuntimeError(
+ "Whisper package is not available in this environment. "
+ "Install it with:\n\n"
+ " python -m pip install -U openai-whisper\n\n"
+ f"(original error: {e})"
+ )
+
+ # defensive checks for heavy deps that Whisper expects
+ try:
+ import numpy # just to check availability
+ except Exception as e:
+ raise RuntimeError(
+ "NumPy is not available. Whisper requires NumPy. "
+ "Install it with:\n\n"
+ " python -m pip install numpy\n\n"
+ f"(original error: {e})"
+ )
+
+ # optional: check for torch (whisper uses torch for model execution)
+ try:
+ import torch # noqa: F401
+ except Exception:
+ # Not fatal — whisper may still run if another backend exists, but recommend torch
+ # We won't block here; warn by raising a helpful message instead if you want strict behavior.
+ pass
+
+ try:
+ # Choose model size you want; keep "medium" if you prefer better accuracy,
+ # but "small"/"base" are faster and use less RAM/VRAM.
+ model = whisper.load_model("medium")
+ result = model.transcribe(input_path, language=language)
+ return result.get("text", "")
+ except Exception as e:
+ # bubble up with a friendly message
+ raise RuntimeError(
+ "Whisper transcription failed. Ensure numpy and a compatible torch are installed. "
+ "Try:\n\n"
+ " python -m pip install --upgrade pip setuptools wheel\n"
+ " python -m pip install numpy\n"
+ " python -m pip install --index-url https://download.pytorch.org/whl/cpu torch\n\n"
+ f"(original error: {e})"
+ )
+
+
+
+
+def issue_client_id() -> str:
+ return uuid.uuid4().hex
+
+
+def _csv_contains(csv: Optional[str], value: str) -> bool:
+ if not csv:
+ return True # treat empty as "all"
+ parts = [p.strip().lower() for p in csv.split(",") if p.strip()]
+ return value.strip().lower() in parts or "all" in parts
+
+
+def _build_url(path: Optional[str]) -> Optional[str]:
+ if not path:
+ return None
+ if path.startswith("http://") or path.startswith("https://"):
+ return path
+ if not path.startswith("/"):
+ path = "/" + path
+ return BASE_URL + path
+
+
+def select_ad_for_placement(
+ db: Session,
+ placement: str,
+ device: Optional[str],
+ category: Optional[str],
+ country: Optional[str],
+ client_id: Optional[str],
+ size: Optional[str]
+) -> Dict[str, Any]:
+
+ placement = placement.strip().lower()
+
+ # ---------------------------
+ # STEP 1 — Get all candidates
+ # ---------------------------
+ units = db.query(AdUnit).filter(AdUnit.enabled == True).all()
+
+ final = []
+ for ad in units:
+
+ # Filter by placement
+ if ad.placement and ad.placement.lower() != placement:
+ continue
+
+ # Device
+ if device and not _csv_contains(ad.target_devices, device):
+ continue
+
+ # Category
+ if category and not _csv_contains(ad.target_categories, category):
+ continue
+
+ # Country
+ if country and not _csv_contains(ad.target_countries, country):
+ continue
+
+ # Size match check
+ if size:
+ custom = f"{ad.custom_width}x{ad.custom_height}" if ad.custom_width and ad.custom_height else None
+ if size != ad.preset_size and size != custom:
+ continue
+
+ final.append(ad)
+
+ # No ads matched
+ if not final:
+ return {"ads": []}
+
+ # ---------------------------
+ # STEP 2 — sort by priority
+ # ---------------------------
+ final = sorted(final, key=lambda x: x.priority or 0, reverse=True)
+
+ # ---------------------------
+ # STEP 3 — always return LIST
+ # ---------------------------
+ ads_payload = []
+
+ for ad in final:
+ url = _build_url(ad.file_path)
+
+ # ---------------------------
+ # NEW: Determine width/height
+ # ---------------------------
+ width = ad.custom_width
+ height = ad.custom_height
+
+ # If custom size not set → use preset size
+ if (not width or not height) and ad.preset_size:
+ try:
+ # normalize: "728 x 90", "728×90", "728 X 90"
+ clean = ad.preset_size.lower().replace(" ", "").replace("×", "x")
+ parts = clean.split("x")
+ if len(parts) == 2:
+ width = int(parts[0])
+ height = int(parts[1])
+ except:
+ pass
+
+ ads_payload.append({
+ "id": ad.id,
+ "name": ad.name,
+ "ad_type": ad.ad_type,
+ "content_url": url,
+ "file_path": url,
+ "html_code": ad.html_code,
+ "vast_url": ad.vast_url,
+ "click_url": ad.click_url,
+
+ # FINAL width/height returned to frontend
+ "width": width,
+ "height": height,
+
+ "skippable_after": ad.skippable_after
+ })
+
+ return {"ads": ads_payload}
+
+
+def record_impression(db: Session, ad_unit_id: int, placement: str, client_id: Optional[str] = None):
+ # 1. Skip if ad was deleted
+ ad_exists = db.query(AdUnit.id).filter(AdUnit.id == ad_unit_id).first()
+ if not ad_exists:
+ return # silently ignore and avoid FK crash
+
+ now = datetime.utcnow()
+
+ stat = (
+ db.query(AdStat)
+ .filter(AdStat.ad_unit_id == ad_unit_id, AdStat.placement == placement)
+ .first()
+ )
+
+ if not stat:
+ stat = AdStat(
+ ad_unit_id=ad_unit_id,
+ placement=placement,
+ impressions=1,
+ clicks=0,
+ last_served_at=now,
+ )
+ db.add(stat)
+ else:
+ stat.impressions = (stat.impressions or 0) + 1
+ stat.last_served_at = now
+
+ if client_id:
+ db.add(
+ AdImpression(
+ ad_unit_id=ad_unit_id,
+ placement=placement,
+ client_id=client_id,
+ timestamp=now,
+ )
+ )
+
+ db.commit()
+ db.refresh(stat)
+ return stat
+def record_click(db: Session, ad_unit_id: int, placement: str, client_id: Optional[str] = None):
+ # 1. Skip if ad was deleted
+ ad_exists = db.query(AdUnit.id).filter(AdUnit.id == ad_unit_id).first()
+ if not ad_exists:
+ return # silently ignore and avoid FK crash
+
+ now = datetime.utcnow()
+
+ stat = (
+ db.query(AdStat)
+ .filter(AdStat.ad_unit_id == ad_unit_id, AdStat.placement == placement)
+ .first()
+ )
+
+ if not stat:
+ stat = AdStat(
+ ad_unit_id=ad_unit_id,
+ placement=placement,
+ impressions=0,
+ clicks=1,
+ last_served_at=now,
+ )
+ db.add(stat)
+ else:
+ stat.clicks = (stat.clicks or 0) + 1
+ stat.last_served_at = now
+
+ if client_id:
+ db.add(
+ AdImpression(
+ ad_unit_id=ad_unit_id,
+ placement=placement,
+ client_id=client_id,
+ timestamp=now,
+ )
+ )
+
+ db.commit()
+ db.refresh(stat)
+ return stat
+
+# add this to backend/services/audio_service.py at top-level (not indented)
+def detect_bpm(input_path: str) -> float:
+ """
+ Detect BPM (tempo) of the audio file.
+ Tries librosa first, falls back to aubio. Returns a float (rounded to 2 decimals).
+ Raises RuntimeError with install instructions if neither library is available.
+ """
+ # try librosa
+ try:
+ import librosa
+ y, sr = librosa.load(input_path, sr=None)
+ tempo, _ = librosa.beat.beat_track(y=y, sr=sr)
+ return float(round(float(tempo), 2))
+ except Exception as e_librosa:
+ # try aubio
+ try:
+ from aubio import tempo, source
+ win_s = 1024
+ hop_s = win_s // 2
+ s = source(input_path, 0, hop_s)
+ samplerate = s.samplerate
+ if samplerate == 0:
+ raise RuntimeError("aubio failed to read sample rate from file")
+
+ o = tempo("default", win_s, hop_s, samplerate)
+ beats = []
+ while True:
+ samples, read = s()
+ is_beat = o(samples)
+ if is_beat:
+ this_beat = o.get_last_s()
+ beats.append(this_beat)
+ if read < hop_s:
+ break
+ if len(beats) < 2:
+ raise RuntimeError("Not enough beats detected to estimate BPM")
+ # compute BPM from inter-beat intervals
+ intervals = [t2 - t1 for t1, t2 in zip(beats[:-1], beats[1:])]
+ avg_interval = sum(intervals) / len(intervals)
+ bpm = 60.0 / avg_interval
+ return float(round(bpm, 2))
+ except Exception as e_aubio:
+ # neither available or both failed
+ raise RuntimeError(
+ "BPM detection requires 'librosa' or 'aubio'.\n"
+ "Install one of them:\n\n"
+ " pip install librosa soundfile\n"
+ " # or (lighter) pip install aubio\n\n"
+ f"librosa error: {e_librosa}\n\naubio error: {e_aubio}"
+ )
+import os
+import subprocess
+from typing import List
+from uuid import uuid4
+
+AUDIO_OUTPUT_DIR = "static/processed_audio"
+os.makedirs(AUDIO_OUTPUT_DIR, exist_ok=True)
+
+
+def merge_audio_ffmpeg(input_paths: List[str], silence_gap: float = 0, crossfade: float = 0) -> str:
+ """
+ Merge multiple audio tracks in order, optionally apply silence gap and crossfade.
+
+ silence_gap (float): Seconds of silence between tracks
+ crossfade (float): Seconds of crossfade between tracks
+
+ Returns path to merged output file.
+ """
+ if len(input_paths) < 2:
+ raise ValueError("At least 2 audio files required to merge.")
+
+ # Build FFmpeg filter chain
+ filter_commands = []
+ inputs = []
+ for path in input_paths:
+ inputs.append("-i")
+ inputs.append(path)
+
+ # Silence gap
+ silence_filter = ""
+ if silence_gap > 0:
+ silence_filter = f"apad=pad_dur={silence_gap}"
+
+ # Create filter complex
+ filter_parts = []
+ stream_labels = []
+
+ for i in range(len(input_paths)):
+ label = f"[a{i}]"
+ stream_labels.append(label)
+ if silence_gap > 0:
+ filter_parts.append(f"[{i}:a]{silence_filter}{label}")
+ else:
+ filter_parts.append(f"[{i}:a]{label}")
+
+ # Build concatenation / crossfade logic
+ if crossfade > 0:
+ # Crossfade between each adjacent pair
+ filter_process = ""
+ last_stream = stream_labels[0]
+
+ for i in range(1, len(stream_labels)):
+ next_stream = stream_labels[i]
+ out_label = f"[mx{i}]"
+ filter_process += (
+ f"{last_stream}{next_stream}"
+ f"acrossfade=d={crossfade}:c1=tri:c2=tri{out_label};"
+ )
+ last_stream = out_label
+
+ final_output = last_stream
+
+ else:
+ # Simple concat
+ concat_inputs = ''.join(stream_labels)
+ final_output = "[merged]"
+ filter_process = (
+ f"{concat_inputs}concat=n={len(stream_labels)}:v=0:a=1{final_output}"
+ )
+
+ filter_complex = ";".join(filter_parts) + ";" + filter_process
+
+ # Output file
+ out_name = f"merged_{uuid4().hex}.wav"
+ out_path = os.path.join(AUDIO_OUTPUT_DIR, out_name)
+
+ command = [
+ "ffmpeg",
+ "-y",
+ *inputs,
+ "-filter_complex", filter_complex,
+ "-map", final_output,
+ out_path
+ ]
+
+ print("FFMPEG MERGE COMMAND:", " ".join(command))
+
+ subprocess.run(command, check=True)
+
+ return out_path
+
diff --git a/services/audio_service.py b/services/audio_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..72f3c934b3d8ce06c4599f2606ef74766a11029a
--- /dev/null
+++ b/services/audio_service.py
@@ -0,0 +1,708 @@
+# backend/services/audio_service.py
+import os
+import uuid
+import subprocess
+from typing import List, Tuple, Optional
+from uuid import uuid4
+from faster_whisper import WhisperModel
+
+print("Loading Faster Whisper model...")
+
+# Load once globally (BEST PRACTICE)
+FWHISPER_MODEL = WhisperModel(
+ "medium",
+ device="cpu",
+ compute_type="int8"
+)
+
+print("Faster Whisper model loaded successfully!")
+
+# optional high-level helpers
+try:
+ from pydub import AudioSegment
+except Exception:
+ AudioSegment = None
+
+# optional heavy libs (lazy)
+try:
+ import librosa
+ import soundfile as sf
+except Exception:
+ librosa = None
+ sf = None
+
+# try to import your core config; fallback to local defaults
+try:
+ from core.config import settings
+ OUTPUT_DIR = getattr(settings, "OUTPUT_DIR", "temp")
+ TEMP_DIR = getattr(settings, "TEMP_DIR", "temp")
+except Exception:
+ OUTPUT_DIR = "temp"
+ TEMP_DIR = "temp"
+
+os.makedirs(OUTPUT_DIR, exist_ok=True)
+os.makedirs(TEMP_DIR, exist_ok=True)
+
+
+# -------------------------
+# Helpers
+# -------------------------
+def _unique_path(ext: str) -> str:
+ ext = ext.lstrip(".")
+ return os.path.join(OUTPUT_DIR, f"{uuid.uuid4().hex}.{ext}")
+
+
+def _run_ffmpeg(cmd: List[str]):
+ """Run ffmpeg command (list form). Raises on non-zero exit with stderr."""
+ proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ if proc.returncode != 0:
+ stderr = proc.stderr.decode(errors="ignore")
+ raise Exception(f"ffmpeg failed: {stderr}")
+ return proc
+
+# -------------------------
+# CUT (router expects cut_audio(input_path, start_ms, end_ms))
+# -------------------------
+def cut_audio(input_path: str, start_ms: int, end_ms: int) -> str:
+ """
+ Trim audio between start_ms and end_ms (integers, milliseconds).
+ Produces a WAV file and returns its path.
+ """
+ if end_ms <= start_ms:
+ raise Exception("end_ms must be greater than start_ms")
+
+ start_s = start_ms / 1000.0
+ duration_s = (end_ms - start_ms) / 1000.0
+ out_path = _unique_path("wav")
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-ss", str(start_s),
+ "-i", input_path,
+ "-t", str(duration_s),
+ "-vn",
+ "-acodec", "pcm_s16le",
+ "-ar", "44100",
+ out_path
+ ]
+ _run_ffmpeg(cmd)
+ return out_path
+
+
+
+import os
+import uuid
+import subprocess
+
+OUTPUT_DIR = "outputs/audio"
+os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+def merge_channels_ffmpeg_pro(
+ left_path: str,
+ right_path: str,
+ left_pan: float = -1.0, # kept for frontend compatibility
+ right_pan: float = 1.0, # kept for frontend compatibility
+ left_gain: float = 1.0,
+ right_gain: float = 1.0,
+ master_gain: float = 1.0,
+):
+ out = os.path.join(OUTPUT_DIR, f"merged_{uuid.uuid4().hex}.wav")
+
+ filter_graph = (
+ # ✅ Force resample + mono extract
+ f"[0:a]aresample=44100,pan=mono|c0=FL,volume={left_gain}[l];"
+ f"[1:a]aresample=44100,pan=mono|c0=FR,volume={right_gain}[r];"
+
+ # ✅ True stereo merge
+ f"[l][r]amerge=inputs=2[a];"
+
+ # ✅ Master volume + final label
+ f"[a]volume={master_gain}[out]"
+ )
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", left_path,
+ "-i", right_path,
+ "-filter_complex", filter_graph,
+ "-map", "[out]",
+ "-ac", "2",
+ out
+ ]
+
+ print("MERGE CMD:", " ".join(cmd))
+ subprocess.run(cmd, check=True)
+ return out
+
+
+# keep an alias for previous name if some code uses cut_audio_ffmpeg
+def cut_audio_ffmpeg(input_path: str, start: float, end: float, fade_in: float = 0, fade_out: float = 0) -> str:
+ """
+ Alternate helper that takes seconds (float) + optional fades and returns WAV.
+ """
+ duration = end - start
+ if duration <= 0:
+ raise Exception("Invalid trim selection.")
+
+ out_path = _unique_path("wav")
+ filters = [f"atrim=start={start}:end={end}", "asetpts=PTS-STARTPTS"]
+ if fade_in > 0:
+ filters.append(f"afade=t=in:st=0:d={fade_in}")
+ if fade_out > 0:
+ fade_out_start = max(0, duration - fade_out)
+ filters.append(f"afade=t=out:st={fade_out_start}:d={fade_out}")
+
+ filter_expr = ",".join(filters)
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", input_path,
+ "-vn",
+ "-af", filter_expr,
+ "-ar", "44100",
+ "-ac", "2",
+ out_path
+ ]
+ _run_ffmpeg(cmd)
+ return out_path
+
+
+# -------------------------
+# MERGE
+# -------------------------
+
+AUDIO_OUTPUT_DIR = "static/processed_audio"
+os.makedirs(AUDIO_OUTPUT_DIR, exist_ok=True)
+
+
+def merge_audio_ffmpeg(input_paths: List[str], silence_gap: float = 0, crossfade: float = 0) -> str:
+ """
+ Merge multiple audio tracks in order, applying optional silence gap and crossfade.
+ Returns a path to the final output WAV file.
+ """
+
+ if len(input_paths) < 2:
+ raise ValueError("At least 2 audio files are required.")
+
+ # Prepare input mapping
+ inputs = []
+ for p in input_paths:
+ inputs += ["-i", p]
+
+ # Label all input streams: [0:a] → [a0], etc.
+ stream_labels = []
+ filter_parts = []
+
+ for i in range(len(input_paths)):
+ labeled = f"[a{i}]"
+ stream_labels.append(labeled)
+
+ if silence_gap > 0:
+ filter_parts.append(f"[{i}:a]apad=pad_dur={silence_gap}{labeled}")
+ else:
+ filter_parts.append(f"[{i}:a]{labeled}")
+
+ # Build crossfade OR concat
+ if crossfade > 0:
+ last = stream_labels[0]
+ proc = ""
+
+ for i in range(1, len(stream_labels)):
+ nxt = stream_labels[i]
+ out = f"[mx{i}]"
+
+ proc += (
+ f"{last}{nxt}"
+ f"acrossfade=d={crossfade}:c1=tri:c2=tri{out};"
+ )
+ last = out
+
+ final_output_label = last
+
+ else:
+ # Normal concatenation
+ joined = "".join(stream_labels)
+ final_output_label = "[merged]"
+ proc = f"{joined}concat=n={len(stream_labels)}:v=0:a=1{final_output_label}"
+
+ filter_complex = ";".join(filter_parts) + ";" + proc
+
+ out_name = f"merged_{uuid.uuid4().hex}.wav"
+ out_path = os.path.join(AUDIO_OUTPUT_DIR, out_name)
+
+ cmd = [
+ "ffmpeg", "-y",
+ *inputs,
+ "-filter_complex", filter_complex,
+ "-map", final_output_label,
+ out_path
+ ]
+
+ print("MERGE CMD:", " ".join(cmd))
+
+ subprocess.run(cmd, check=True)
+
+ return out_path
+
+# -------------------------
+# COMPRESS -> mp3
+# -------------------------
+def compress_audio(input_path: str, bitrate: str = "96k") -> str:
+ """
+ Compress input audio to MP3 with given bitrate (e.g. "128k" or "128").
+ Returns path to the MP3 file.
+ """
+ if isinstance(bitrate, str) and bitrate.isdigit():
+ bitrate = f"{bitrate}k"
+ out_path = _unique_path("mp3")
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", input_path,
+ "-vn",
+ "-b:a", str(bitrate),
+ "-map_metadata", "-1",
+ out_path
+ ]
+ _run_ffmpeg(cmd)
+ return out_path
+
+
+# -------------------------
+# CONVERT FORMAT
+# -------------------------
+# -------------------------
+# PURE FFMPEG CONVERT FORMAT
+# -------------------------
+def convert_format(input_path: str, target_ext: str) -> str:
+ target_ext = target_ext.lower().lstrip(".")
+
+ # AAC must be inside .m4a
+ if target_ext == "aac":
+ target_ext = "m4a"
+
+ out_path = _unique_path(target_ext)
+
+ # select codec
+ if target_ext == "mp3":
+ codec = "libmp3lame"
+ opts = ["-b:a", "192k"]
+
+ elif target_ext in ("m4a", "mp4"):
+ codec = "aac"
+ opts = ["-b:a", "192k"]
+
+ elif target_ext in ("ogg", "opus"):
+ codec = "libopus"
+ opts = ["-b:a", "128k"]
+
+ elif target_ext == "wav":
+ codec = "pcm_s16le"
+ opts = []
+
+ elif target_ext == "flac":
+ codec = "flac"
+ opts = []
+
+ else:
+ raise RuntimeError(f"Unsupported output format: {target_ext}")
+
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-vn", "-acodec", codec, *opts, out_path]
+ _run_ffmpeg(cmd)
+
+ return out_path
+
+
+# -------------------------
+# ADVANCED TRIM (router sometimes calls advanced_trim with ms args)
+# -------------------------
+def advanced_trim(input_path: str, start_ms: int, end_ms: int, fade_in: int = 0, fade_out: int = 0) -> str:
+ """
+ start_ms, end_ms in milliseconds. fade_in, fade_out in seconds.
+ Returns WAV path.
+ """
+ return cut_audio(input_path, start_ms, end_ms) if (fade_in == 0 and fade_out == 0) else _advanced_trim_with_fades(input_path, start_ms, end_ms, fade_in, fade_out)
+
+
+def _advanced_trim_with_fades(input_path: str, start_ms: int, end_ms: int, fade_in_s: int = 0, fade_out_s: int = 0) -> str:
+ start_s = start_ms / 1000.0
+ duration_s = (end_ms - start_ms) / 1000.0
+ out_path = _unique_path("wav")
+ filters = [f"atrim=start={start_s}:duration={duration_s}", "asetpts=PTS-STARTPTS"]
+ if fade_in_s > 0:
+ filters.append(f"afade=t=in:st=0:d={fade_in_s}")
+ if fade_out_s > 0:
+ fade_out_start = max(0, duration_s - fade_out_s)
+ filters.append(f"afade=t=out:st={fade_out_start}:d={fade_out_s}")
+ filter_expr = ",".join(filters)
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", input_path,
+ "-vn",
+ "-af", filter_expr,
+ "-ar", "44100",
+ "-ac", "2",
+ out_path
+ ]
+ _run_ffmpeg(cmd)
+ return out_path
+
+
+# -------------------------
+# SPEED CHANGE
+# -------------------------
+def change_speed(input_path: str, factor: float = 1.0) -> str:
+ if factor <= 0:
+ raise Exception("factor must be positive")
+ out_path = _unique_path("wav")
+ # Use atempo: supports 0.5-2.0 per filter; chain if needed
+ atempo_vals: List[float] = []
+ rem = factor
+ if rem == 1.0:
+ # copy
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-vn", out_path]
+ _run_ffmpeg(cmd)
+ return out_path
+
+ # make chain
+ while rem > 2.0:
+ atempo_vals.append(2.0)
+ rem /= 2.0
+ while rem < 0.5:
+ atempo_vals.append(0.5)
+ rem /= 0.5
+ if abs(rem - 1.0) > 1e-9:
+ atempo_vals.append(rem)
+
+ afilt = ",".join([f"atempo={v}" for v in atempo_vals])
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-vn", "-af", afilt, out_path]
+ _run_ffmpeg(cmd)
+ return out_path
+
+
+# -------------------------
+# PITCH SHIFT (requires librosa)
+# -------------------------
+def pitch_shift(input_path: str, semitones: float) -> str:
+ if not librosa or not sf:
+ raise RuntimeError("librosa/soundfile not available. Install 'librosa soundfile' to use pitch shifting.")
+ y, sr = librosa.load(input_path, sr=None)
+ shifted = librosa.effects.pitch_shift(y, sr, n_steps=semitones)
+ out_path = _unique_path("wav")
+ sf.write(out_path, shifted, sr)
+ return out_path
+
+
+# -------------------------------------------------
+# HYBRID NOISE REDUCTION (used by NoiseReducerTool)
+# -------------------------------------------------
+def reduce_noise_filter(input_path: str, frequency: str, filter_type: str) -> str:
+ """
+ Uses FFmpeg filter to reduce noise using lowpass/highpass.
+ Matches React NoiseReducerTool perfectly.
+ """
+ try:
+ freq = int(frequency)
+ except:
+ raise Exception("Invalid frequency value")
+
+ ff_filter = "lowpass" if filter_type == "lowpass" else "highpass"
+
+ out_path = _unique_path("wav")
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", input_path,
+ "-af", f"{ff_filter}=f={freq}",
+ out_path
+ ]
+
+ proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ if proc.returncode != 0:
+ raise Exception(proc.stderr.decode())
+
+ return out_path
+
+
+
+
+# -------------------------
+# NORMALIZE
+# -------------------------
+def normalize_audio(input_path: str) -> str:
+ if AudioSegment:
+ audio = AudioSegment.from_file(input_path)
+ change = -audio.max_dBFS
+ normalized = audio.apply_gain(change)
+ out_path = _unique_path("mp3")
+ normalized.export(out_path, format="mp3")
+ return out_path
+
+ out_path = _unique_path("wav")
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-af", "loudnorm", out_path]
+ _run_ffmpeg(cmd)
+ return out_path
+
+
+# -------------------------
+# REVERSE
+# -------------------------
+def reverse_audio(input_path: str) -> str:
+ out_path = _unique_path("wav")
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-af", "areverse", out_path]
+ _run_ffmpeg(cmd)
+ return out_path
+
+
+# -------------------------
+# CHANNEL SPLIT / MERGE
+# -------------------------
+def split_channels(input_path: str) -> Tuple[str, str]:
+ """
+ Returns (left_path, right_path). Raises if not stereo.
+ """
+ # attempt using ffmpeg map_channel
+ left = _unique_path("wav")
+ right = _unique_path("wav")
+ cmd_left = ["ffmpeg", "-y", "-i", input_path, "-map_channel", "0.0.0", left]
+ cmd_right = ["ffmpeg", "-y", "-i", input_path, "-map_channel", "0.0.1", right]
+ try:
+ _run_ffmpeg(cmd_left)
+ _run_ffmpeg(cmd_right)
+ except Exception as e:
+ # fallback: if mono, duplicate
+ if AudioSegment:
+ audio = AudioSegment.from_file(input_path)
+ channels = audio.split_to_mono()
+ if len(channels) == 1:
+ channels[0].export(left, format="wav")
+ channels[0].export(right, format="wav")
+ return left, right
+ raise Exception(f"split_channels failed: {e}")
+ return left, right
+
+
+def merge_channels(left_path: str, right_path: str) -> str:
+ out_path = _unique_path("wav")
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", left_path,
+ "-i", right_path,
+ "-filter_complex", "join=inputs=2:channel_layout=stereo[a]",
+ "-map", "[a]",
+ out_path
+ ]
+ _run_ffmpeg(cmd)
+ return out_path
+
+
+# -------------------------
+# SPECTROGRAM (requires librosa)
+# -------------------------
+def generate_spectrogram(input_path: str) -> str:
+ if not librosa or not sf:
+ # fallback: try ffmpeg showspectrumpic
+ out_path = _unique_path("png")
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-lavfi", "showspectrumpic=s=1024x256:legend=disabled", out_path]
+ _run_ffmpeg(cmd)
+ return out_path
+
+ import matplotlib
+ matplotlib.use("Agg")
+ import matplotlib.pyplot as plt
+ import librosa.display
+ y, sr = librosa.load(input_path, sr=None)
+ S = librosa.stft(y)
+ S_db = librosa.amplitude_to_db(abs(S))
+ plt.figure(figsize=(10, 4))
+ librosa.display.specshow(S_db, sr=sr, x_axis="time", y_axis="log")
+ plt.colorbar(format="%+2.0f dB")
+ plt.title("Spectrogram")
+ plt.tight_layout()
+ out_path = _unique_path("png")
+ plt.savefig(out_path)
+ plt.close()
+ return out_path
+
+
+# -------------------------
+# VOCAL ISOLATION (lazy)
+# -------------------------
+def isolate_vocals(input_path: str, stems: int = 2) -> Tuple[str, str]:
+ try:
+ from spleeter.separator import Separator
+ except Exception:
+ raise RuntimeError("Spleeter not available. Install 'spleeter' or use demucs for vocal isolation.")
+ tmp_output = os.path.join(TEMP_DIR, f"{uuid.uuid4().hex}")
+ os.makedirs(tmp_output, exist_ok=True)
+ separator = Separator(f"{stems}stems")
+ separator.separate_to_file(input_path, tmp_output)
+ base = os.path.splitext(os.path.basename(input_path))[0]
+ folder = os.path.join(tmp_output, base)
+ vocals = os.path.join(folder, "vocals.wav")
+ accom = os.path.join(folder, "accompaniment.wav")
+ out_v = _unique_path("wav")
+ out_a = _unique_path("wav")
+ os.rename(vocals, out_v)
+ os.rename(accom, out_a)
+ return out_v, out_a
+
+
+# -------------------------
+# WHISPER TRANSCRIBE (lazy)
+# -------------------------
+def transcribe_whisper(input_path: str, model: str = "large") -> str:
+ try:
+ import whisper
+ except Exception as e:
+ raise RuntimeError(
+ "Whisper not installed. Install 'openai-whisper' and dependencies to enable transcription."
+ )
+ w = whisper.load_model(model)
+ res = w.transcribe(input_path)
+ return res.get("text", "")
+
+
+# -------------------------
+# TTS (lazy)
+# -------------------------
+def synthesize_tts(text: str, voice: Optional[str] = None) -> str:
+ try:
+ from TTS.api import TTS
+ except Exception:
+ raise RuntimeError("Coqui TTS not installed. Install 'TTS' to enable local TTS.")
+ try:
+ tts = TTS(model_name=voice) if voice else TTS()
+ except Exception:
+ tts = TTS()
+ out_path = _unique_path("wav")
+ tts.tts_to_file(text=text, file_path=out_path)
+ return out_path
+
+# -------------------------------
+# Whisper STT FIXED VERSION
+# -------------------------------
+# -------------------------------------------------------------
+# Whisper Language Support (ALL 99 languages)
+# -------------------------------------------------------------
+
+WHISPER_LANGUAGES = {
+ "af","am","ar","as","az","ba","be","bg","bn","bo","br","bs","ca","cs","cy","da","de",
+ "el","en","es","et","eu","fa","fi","fo","fr","gl","gu","ha","haw","he","hi","hr","ht",
+ "hu","hy","id","is","it","ja","jw","ka","kk","km","kn","ko","la","lb","ln","lo","lt",
+ "lv","mg","mi","mk","ml","mn","mr","ms","mt","my","ne","nl","nn","no","oc","pa","pl",
+ "ps","pt","ro","ru","sa","sd","si","sk","sl","sn","so","sq","sr","su","sv","sw","ta",
+ "te","tg","th","tk","tl","tr","tt","uk","ur","uz","vi","yi","yo","zh"
+}
+
+def normalize_language(lang: str) -> str:
+ if not lang:
+ return "auto"
+
+ lang = lang.lower().replace("_", "-")
+
+ # Locale format (en-US → en)
+ if "-" in lang:
+ primary = lang.split("-")[0]
+ if primary in WHISPER_LANGUAGES:
+ return primary
+
+ # Exact match
+ if lang in WHISPER_LANGUAGES:
+ return lang
+
+ # Try first 2 chars (e.g., english → en)
+ short = lang[:2]
+ if short in WHISPER_LANGUAGES:
+ return short
+
+ return "auto"
+from faster_whisper import WhisperModel
+
+def whisper_stt(input_path: str, language: str = "auto"):
+ language = normalize_language(language)
+ print(f"Faster-Whisper STT using language: {language}")
+
+ # Use preloaded global model
+ model = FWHISPER_MODEL
+
+ if language == "auto":
+ segments, info = model.transcribe(
+ input_path,
+ beam_size=5,
+ vad_filter=True
+ )
+ print("Detected language:", info.language)
+ else:
+ segments, info = model.transcribe(
+ input_path,
+ language=language,
+ beam_size=5,
+ vad_filter=True
+ )
+
+ text = "".join(seg.text for seg in segments).strip()
+ return text
+
+# -------------------------
+# three_band_eq wrapper
+# -------------------------
+def three_band_eq(input_path: str, bass_gain_db: float = 0.0, mid_gain_db: float = 0.0, treble_gain_db: float = 0.0) -> str:
+ out_path = _unique_path("wav")
+ cmd = [
+ "ffmpeg", "-y", "-i", input_path,
+ "-af",
+ f"equalizer=f=100:t=q:w=1:g={bass_gain_db},equalizer=f=1000:t=q:w=1:g={mid_gain_db},equalizer=f=8000:t=q:w=1:g={treble_gain_db}",
+ out_path
+ ]
+ _run_ffmpeg(cmd)
+ return out_path
+# add this to backend/services/audio_service.py at top-level (not indented)
+def detect_bpm(input_path: str) -> float:
+ """
+ Detect BPM (tempo) of the audio file.
+ Tries librosa first, falls back to aubio. Returns a float (rounded to 2 decimals).
+ Raises RuntimeError with install instructions if neither library is available.
+ """
+ # try librosa
+ try:
+ import librosa
+ y, sr = librosa.load(input_path, sr=None)
+ tempo, _ = librosa.beat.beat_track(y=y, sr=sr)
+ return float(round(float(tempo), 2))
+ except Exception as e_librosa:
+ # try aubio
+ try:
+ from aubio import tempo, source
+ win_s = 1024
+ hop_s = win_s // 2
+ s = source(input_path, 0, hop_s)
+ samplerate = s.samplerate
+ if samplerate == 0:
+ raise RuntimeError("aubio failed to read sample rate from file")
+
+ o = tempo("default", win_s, hop_s, samplerate)
+ beats = []
+ while True:
+ samples, read = s()
+ is_beat = o(samples)
+ if is_beat:
+ this_beat = o.get_last_s()
+ beats.append(this_beat)
+ if read < hop_s:
+ break
+ if len(beats) < 2:
+ raise RuntimeError("Not enough beats detected to estimate BPM")
+ # compute BPM from inter-beat intervals
+ intervals = [t2 - t1 for t1, t2 in zip(beats[:-1], beats[1:])]
+ avg_interval = sum(intervals) / len(intervals)
+ bpm = 60.0 / avg_interval
+ return float(round(bpm, 2))
+ except Exception as e_aubio:
+ # neither available or both failed
+ raise RuntimeError(
+ "BPM detection requires 'librosa' or 'aubio'.\n"
+ "Install one of them:\n\n"
+ " pip install librosa soundfile\n"
+ " # or (lighter) pip install aubio\n\n"
+ f"librosa error: {e_librosa}\n\naubio error: {e_aubio}"
+ )
diff --git a/services/business_service.py b/services/business_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..d83b91ad140518a6c8cc638d99a603f45581b7a1
--- /dev/null
+++ b/services/business_service.py
@@ -0,0 +1,136 @@
+# backend/services/business_service.py
+import os
+import uuid
+from core.config import settings
+from PIL import Image
+
+import qrcode
+import barcode
+from barcode.writer import ImageWriter
+from reportlab.pdfgen import canvas
+from reportlab.lib.pagesizes import A4
+from reportlab.lib.units import mm
+
+os.makedirs(settings.OUTPUT_DIR, exist_ok=True)
+
+def _out_name(ext):
+ return os.path.join(settings.OUTPUT_DIR, f"{uuid.uuid4()}.{ext.lstrip('.')}")
+
+# ---------------------------
+# QR CODE
+# ---------------------------
+
+def generate_qr(data: str, box_size: int = 10, border: int = 4, fmt: str = "png"):
+ qr = qrcode.QRCode(
+ version=1,
+ error_correction=qrcode.constants.ERROR_CORRECT_M,
+ box_size=box_size,
+ border=border,
+ )
+ qr.add_data(data)
+ qr.make(fit=True)
+
+ img = qr.make_image(fill_color="black", back_color="white")
+
+ out = _out_name(fmt)
+ img.save(out)
+ return out
+
+# ---------------------------
+# BARCODE GENERATOR
+# ---------------------------
+
+def generate_barcode(data: str, barcode_type: str = "code128", fmt: str = "png"):
+ """
+ barcode_type: code128, ean13, code39, isbn13, upca etc.
+ """
+ try:
+ BarcodeClass = barcode.get_barcode_class(barcode_type.lower())
+ except Exception:
+ raise RuntimeError("Unsupported barcode type")
+
+ out = _out_name(fmt)
+ bc = BarcodeClass(data, writer=ImageWriter())
+ bc.save(out.replace(f".{fmt}", "")) # library appends extension automatically
+
+ # fix naming (ensure final path is correct)
+ final = out
+ if not os.path.exists(final):
+ # barcode lib saves as {path}.png automatically
+ final = out.replace(f".{fmt}", "") + f".{fmt}"
+
+ return final
+
+# ---------------------------
+# INVOICE GENERATOR (PDF)
+# ---------------------------
+
+def generate_invoice(
+ invoice_number: str,
+ seller: str,
+ buyer: str,
+ items: list,
+ logo_path: str = None,
+ currency: str = "USD",
+):
+ """
+ items = [
+ {"name": "Product A", "qty": 2, "price": 30},
+ {"name": "Product B", "qty": 1, "price": 50}
+ ]
+ """
+ out = _out_name("pdf")
+ c = canvas.Canvas(out, pagesize=A4)
+ width, height = A4
+
+ y = height - 40
+
+ # Logo
+ if logo_path and os.path.exists(logo_path):
+ c.drawImage(logo_path, 40, y - 80, width=120, preserveAspectRatio=True)
+ c.setFont("Helvetica-Bold", 18)
+ c.drawString(200, y - 20, f"Invoice #{invoice_number}")
+
+ # Seller
+ c.setFont("Helvetica", 11)
+ c.drawString(40, y - 100, f"Seller: {seller}")
+
+ # Buyer
+ c.drawString(40, y - 120, f"Buyer: {buyer}")
+
+ # Table header
+ y -= 160
+ c.setFont("Helvetica-Bold", 12)
+ c.drawString(40, y, "Item")
+ c.drawString(260, y, "Qty")
+ c.drawString(320, y, "Price")
+ c.drawString(400, y, "Total")
+
+ c.setFont("Helvetica", 11)
+
+ total_amount = 0
+ y -= 25
+
+ for item in items:
+ name = item["name"]
+ qty = int(item["qty"])
+ price = float(item["price"])
+ subtotal = qty * price
+ total_amount += subtotal
+
+ c.drawString(40, y, name[:40])
+ c.drawString(260, y, str(qty))
+ c.drawString(320, y, f"{price:.2f}")
+ c.drawString(400, y, f"{subtotal:.2f}")
+
+ y -= 20
+
+ # Total
+ c.setFont("Helvetica-Bold", 14)
+ c.drawString(40, y - 20, f"Total: {currency} {total_amount:.2f}")
+
+ c.showPage()
+ c.save()
+
+ return out
+
diff --git a/services/converter_tools_service.py b/services/converter_tools_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed71246dfef11f3e21ebe23e502841f3063dfde9
--- /dev/null
+++ b/services/converter_tools_service.py
@@ -0,0 +1,77 @@
+# backend/services/converter_tools_service.py
+import base64
+import fitz
+from PIL import Image
+from markdown import markdown
+import os
+import uuid
+from core.config import settings
+
+
+def _out(ext):
+ return os.path.join(settings.OUTPUT_DIR, f"{uuid.uuid4()}.{ext}")
+
+
+# ---------------------------------------
+# IMAGE → WEBP
+# ---------------------------------------
+def image_to_webp(input_path: str, quality: int = 80) -> str:
+ out_path = _out("webp")
+ img = Image.open(input_path).convert("RGB")
+ img.save(out_path, "webp", quality=quality)
+ return out_path
+
+
+# ---------------------------------------
+# IMAGE → SVG (Embed)
+# ---------------------------------------
+def image_to_svg_embed(input_path: str) -> str:
+ out_path = _out("svg")
+
+ with open(input_path, "rb") as f:
+ data = base64.b64encode(f.read()).decode()
+
+ ext = os.path.splitext(input_path)[1].lstrip(".")
+ mime = f"image/{ext if ext != 'jpg' else 'jpeg'}"
+
+ svg_content = f"""
+
+
+
+ """
+
+ with open(out_path, "w") as f:
+ f.write(svg_content.strip())
+
+ return out_path
+
+
+# ---------------------------------------
+# PDF → TEXT
+# ---------------------------------------
+def pdf_to_text(input_path: str) -> str:
+ doc = fitz.open(input_path)
+ text = ""
+ for page in doc:
+ text += page.get_text()
+ doc.close()
+
+ out_path = _out("txt")
+ with open(out_path, "w", encoding="utf-8") as f:
+ f.write(text)
+
+ return out_path
+
+
+# ---------------------------------------
+# MARKDOWN → HTML
+# ---------------------------------------
+def markdown_to_html(md_text: str) -> str:
+ html = markdown(md_text, extensions=["fenced_code", "tables"])
+
+ out_path = _out("html")
+ with open(out_path, "w", encoding="utf-8") as f:
+ f.write(html)
+
+ return out_path
+
diff --git a/services/developer_service.py b/services/developer_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..7224714100a5c90b7e9f07a68a4455ffa3d19c6b
--- /dev/null
+++ b/services/developer_service.py
@@ -0,0 +1,222 @@
+# backend/services/developer_service.py
+import json
+import re
+import hashlib
+import base64
+import tempfile
+import csv
+import os
+from typing import Any, Dict, List, Tuple
+from urllib.parse import urlparse, parse_qs, unquote
+
+import sqlparse
+import xmltodict
+from pygments import highlight
+from pygments.lexers import get_lexer_by_name, guess_lexer, TextLexer
+from pygments.formatters import HtmlFormatter
+import requests
+
+# -------------------------
+# Code Formatter (raw + HTML)
+# -------------------------
+def format_code_raw(code: str, lang: str = None) -> str:
+ """
+ Return beautified code where possible (sql uses sqlparse).
+ For other languages we return original code (or trimmed) but still can apply simple indentation for JSON/XML.
+ """
+ if not lang:
+ # try to guess
+ try:
+ lexer = guess_lexer(code)
+ lang = lexer.aliases[0]
+ except Exception:
+ lang = None
+
+ if lang:
+ lang = lang.lower()
+ # SQL formatted via sqlparse
+ if lang and lang in ("sql", "pgsql", "mysql"):
+ return sqlparse.format(code, reindent=True, keyword_case="upper")
+ # JSON pretty if it is JSON
+ try:
+ parsed = json.loads(code)
+ return json.dumps(parsed, indent=4, ensure_ascii=False)
+ except Exception:
+ pass
+ # XML pretty if XML
+ try:
+ parsed = xmltodict.parse(code)
+ return xmltodict.unparse(parsed, pretty=True)
+ except Exception:
+ pass
+ # fallback: return code (cleaned)
+ return code.rstrip() + "\n"
+
+def format_code_html(code: str, lang: str = None) -> str:
+ """
+ Return HTML highlighted version using pygments.
+ If lang is None, attempt to guess.
+ """
+ try:
+ if lang:
+ lexer = get_lexer_by_name(lang)
+ else:
+ lexer = guess_lexer(code)
+ except Exception:
+ lexer = TextLexer()
+ formatter = HtmlFormatter(full=True, style="friendly")
+ return highlight(code, lexer, formatter)
+
+# -------------------------
+# JSON Utilities
+# -------------------------
+def json_pretty(text: str) -> str:
+ obj = json.loads(text)
+ return json.dumps(obj, indent=4, ensure_ascii=False)
+
+def json_minify(text: str) -> str:
+ obj = json.loads(text)
+ return json.dumps(obj, separators=(",", ":"), ensure_ascii=False)
+
+def json_validate(text: str) -> Tuple[bool, str]:
+ try:
+ json.loads(text)
+ return True, "Valid JSON"
+ except Exception as e:
+ return False, str(e)
+
+# -------------------------
+# XML Utilities
+# -------------------------
+def xml_pretty(text: str) -> str:
+ parsed = xmltodict.parse(text)
+ return xmltodict.unparse(parsed, pretty=True)
+
+def xml_validate(text: str) -> Tuple[bool, str]:
+ try:
+ xmltodict.parse(text)
+ return True, "Valid XML"
+ except Exception as e:
+ return False, str(e)
+
+# -------------------------
+# SQL Formatter
+# -------------------------
+def sql_format(text: str) -> str:
+ return sqlparse.format(text, reindent=True, keyword_case="upper")
+
+# -------------------------
+# Base64 Converter
+# -------------------------
+def base64_encode(text: str) -> str:
+ return base64.b64encode(text.encode()).decode()
+
+def base64_decode(text: str) -> str:
+ return base64.b64decode(text.encode()).decode("utf-8", "ignore")
+
+# -------------------------
+# JSON -> CSV Converter
+# -------------------------
+def json_to_csv(json_text: str) -> str:
+ """
+ Accepts a JSON array of objects. Returns a path to a CSV file.
+ """
+ data = json.loads(json_text)
+ if not isinstance(data, list):
+ raise ValueError("JSON must be an array of objects")
+ # collect all keys
+ keys = set()
+ for row in data:
+ if isinstance(row, dict):
+ keys.update(row.keys())
+ else:
+ raise ValueError("Each item in array must be an object")
+ keys = list(keys)
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
+ tmpname = tmp.name
+ tmp.close()
+ with open(tmpname, "w", newline="", encoding="utf-8") as cf:
+ writer = csv.DictWriter(cf, fieldnames=keys)
+ writer.writeheader()
+ for row in data:
+ writer.writerow({k: row.get(k, "") for k in keys})
+ return tmpname
+
+# -------------------------
+# URL Analyzer
+# -------------------------
+def analyze_url(url: str) -> Dict[str, Any]:
+ parsed = urlparse(url)
+ qs = parse_qs(parsed.query)
+ # decode query values
+ decoded_qs = {k: [unquote(v) for v in vals] for k, vals in qs.items()}
+ return {
+ "scheme": parsed.scheme,
+ "netloc": parsed.netloc,
+ "hostname": parsed.hostname,
+ "port": parsed.port,
+ "path": parsed.path,
+ "params": parsed.params,
+ "query": decoded_qs,
+ "fragment": parsed.fragment,
+ "username": parsed.username,
+ "password": parsed.password,
+ }
+
+# -------------------------
+# Regex Tester
+# -------------------------
+def regex_test(pattern: str, text: str) -> Dict[str, Any]:
+ try:
+ compiled = re.compile(pattern)
+ except re.error as e:
+ return {"valid": False, "error": str(e)}
+ matches = compiled.findall(text)
+ details = []
+ for m in compiled.finditer(text):
+ details.append({
+ "match": m.group(),
+ "start": m.start(),
+ "end": m.end(),
+ "groups": m.groups()
+ })
+ return {"valid": True, "matches": matches, "details": details}
+
+# -------------------------
+# Hash Generator
+# -------------------------
+def generate_hash(text: str, algo: str = "md5") -> str:
+ algo = algo.lower()
+ if algo not in ("md5", "sha1", "sha256", "sha512"):
+ raise ValueError("Unsupported algorithm")
+ h = getattr(hashlib, algo)()
+ h.update(text.encode())
+ return h.hexdigest()
+
+# -------------------------
+# API Tester
+# -------------------------
+def api_request(method: str, url: str, headers: dict = None, params: dict = None,
+ body: str = None, timeout: int = 20) -> Dict[str, Any]:
+ """
+ Simple API tester using requests. Returns status, headers, body (text), elapsed_ms.
+ """
+ method = method.upper()
+ headers = headers or {}
+ params = params or {}
+ try:
+ resp = requests.request(method, url, headers=headers, params=params, data=body, timeout=timeout)
+ # try to decode JSON
+ try:
+ resp_body = resp.json()
+ except Exception:
+ resp_body = resp.text
+ return {
+ "status_code": resp.status_code,
+ "headers": dict(resp.headers),
+ "body": resp_body,
+ "elapsed_ms": int(resp.elapsed.total_seconds() * 1000)
+ }
+ except Exception as e:
+ return {"error": str(e)}
+
diff --git a/services/image_service.py b/services/image_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..03d3101e5c8635b8dce0da9692cdafd8ccad3088
--- /dev/null
+++ b/services/image_service.py
@@ -0,0 +1,302 @@
+import os
+import uuid
+import subprocess
+from typing import List, Optional, Tuple
+from PIL import Image, ImageFilter, ImageEnhance, ImageOps, ImageDraw, ImageFont
+import piexif
+from core.config import settings
+import zipfile
+import base64
+import io # ✅ ADD THIS
+from fastapi import Response
+from pillow_heif import register_heif_opener
+from cairosvg import svg2png
+
+register_heif_opener()
+# ensure folders exist
+os.makedirs(settings.OUTPUT_DIR, exist_ok=True)
+os.makedirs(settings.TEMP_DIR, exist_ok=True)
+
+def _out_path(ext="png"):
+ return os.path.join(settings.OUTPUT_DIR, f"{uuid.uuid4()}.{ext.lstrip('.')}")
+
+def _run_imagemagick_command(args: List[str]):
+ # wrapper to call ImageMagick "magick" or "convert" depending on what's available
+ cmd = ["magick"] + args
+ try:
+ subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ except FileNotFoundError:
+ # fallback to convert
+ cmd = ["convert"] + args
+ subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ return True
+
+# -----------------------
+# Basic operations (Pillow)
+# -----------------------
+def resize_image(input_path: str, width: Optional[int] = None, height: Optional[int] = None, keep_aspect: bool = True) -> str:
+ img = Image.open(input_path)
+ if not width and not height:
+ raise ValueError("width or height required")
+ if keep_aspect:
+ img.thumbnail((width or img.width, height or img.height), Image.LANCZOS)
+ else:
+ img = img.resize((width or img.width, height or img.height), Image.LANCZOS)
+ out = _out_path(img.format.lower() if img.format else "png")
+ img.save(out, optimize=True, quality=95)
+ return out
+
+def crop_image(input_path: str, x: int, y: int, w: int, h: int) -> str:
+ img = Image.open(input_path)
+ crop = img.crop((x, y, x + w, y + h))
+ out = _out_path(img.format.lower() if img.format else "png")
+ crop.save(out, optimize=True, quality=95)
+ return out
+
+def rotate_image(input_path: str, degrees: float, expand: bool = True) -> str:
+ img = Image.open(input_path)
+ out_img = img.rotate(degrees, expand=expand, resample=Image.BICUBIC)
+ out = _out_path(img.format.lower() if img.format else "png")
+ out_img.save(out, optimize=True)
+ return out
+
+def flip_image(input_path: str, mode: str = "horizontal") -> str:
+ img = Image.open(input_path)
+ if mode == "horizontal":
+ out_img = ImageOps.mirror(img)
+ else:
+ out_img = ImageOps.flip(img)
+ out = _out_path(img.format.lower() if img.format else "png")
+ out_img.save(out, optimize=True)
+ return out
+
+def thumbnail_image(input_path: str, max_dim: int = 200) -> str:
+ img = Image.open(input_path)
+ img.thumbnail((max_dim, max_dim), Image.LANCZOS)
+ out = _out_path(img.format.lower() if img.format else "png")
+ img.save(out, optimize=True)
+ return out
+
+# -----------------------
+# Adjustments & Filters
+# -----------------------
+def adjust_brightness(input_path: str, factor: float) -> str:
+ img = Image.open(input_path)
+ enhancer = ImageEnhance.Brightness(img)
+ out_img = enhancer.enhance(factor)
+ out = _out_path(img.format.lower() if img.format else "png")
+ out_img.save(out, optimize=True)
+ return out
+
+def adjust_contrast(input_path: str, factor: float) -> str:
+ img = Image.open(input_path)
+ enhancer = ImageEnhance.Contrast(img)
+ out_img = enhancer.enhance(factor)
+ out = _out_path(img.format.lower() if img.format else "png")
+ out_img.save(out, optimize=True)
+ return out
+
+def adjust_saturation(input_path: str, factor: float) -> str:
+ img = Image.open(input_path).convert("RGB")
+ enhancer = ImageEnhance.Color(img)
+ out_img = enhancer.enhance(factor)
+ out = _out_path("png")
+ out_img.save(out, optimize=True)
+ return out
+
+def blur_image(input_path: str, radius: float = 2.0) -> str:
+ img = Image.open(input_path)
+ out_img = img.filter(ImageFilter.GaussianBlur(radius))
+ out = _out_path(img.format.lower() if img.format else "png")
+ out_img.save(out, optimize=True)
+ return out
+
+def sharpen_image(input_path: str, factor: float = 1.0) -> str:
+ img = Image.open(input_path)
+ # Pillow doesn't accept factor for sharpen directly; apply multiple times if factor > 1
+ out_img = img.filter(ImageFilter.UnsharpMask(radius=2, percent=int(150*factor), threshold=3))
+ out = _out_path(img.format.lower() if img.format else "png")
+ out_img.save(out, optimize=True)
+ return out
+
+def grayscale_image(input_path: str) -> str:
+ img = Image.open(input_path).convert("L")
+ out = _out_path("png")
+ img.save(out, optimize=True)
+ return out
+
+def sepia_image(input_path: str) -> str:
+ img = Image.open(input_path).convert("RGB")
+ width, height = img.size
+ pixels = img.load()
+ for py in range(height):
+ for px in range(width):
+ r, g, b = pixels[px, py]
+ tr = int(0.393 * r + 0.769 * g + 0.189 * b)
+ tg = int(0.349 * r + 0.686 * g + 0.168 * b)
+ tb = int(0.272 * r + 0.534 * g + 0.131 * b)
+ pixels[px, py] = (min(255, tr), min(255, tg), min(255, tb))
+ out = _out_path("jpg")
+ img.save(out, quality=90, optimize=True)
+ return out
+
+# -----------------------
+# Format & Compression
+# -----------------------
+def convert_format(input_path: str, target_format: str, quality: Optional[int] = 90) -> str:
+ # If target format is modern (webp, avif) use ImageMagick for best support
+ target_format = target_format.lower().lstrip(".")
+ ext = target_format if target_format != "jpeg" else "jpg"
+ if target_format in {"webp", "avif", "heic"}:
+ out = _out_path(ext)
+ # use ImageMagick for advanced encoders
+ args = [input_path, "-quality", str(quality), out]
+ _run_imagemagick_command(args)
+ return out
+ img = Image.open(input_path).convert("RGB")
+ out = _out_path(ext)
+ save_kwargs = {}
+ if ext in {"jpg", "jpeg"}:
+ save_kwargs["quality"] = quality
+ save_kwargs["optimize"] = True
+ img.save(out, **save_kwargs)
+ return out
+
+def compress_image(input_path: str, quality: int = 75, target_format: Optional[str] = None) -> str:
+ img = Image.open(input_path)
+ target = target_format.lower() if target_format else (img.format.lower() if img.format else "jpg")
+ return convert_format(input_path, target, quality=quality)
+
+def advanced_compress(input_path: str, max_size_kb: int = 200) -> str:
+ """
+ Iteratively reduce quality until under size target. Uses JPEG/WebP primarily.
+ """
+ img = Image.open(input_path).convert("RGB")
+ out = _out_path("jpg")
+ quality = 95
+ while quality >= 20:
+ img.save(out, quality=quality, optimize=True)
+ if os.path.getsize(out) <= max_size_kb * 1024:
+ return out
+ quality -= 5
+ return out # best-effort
+
+# -----------------------
+# Background removal (color key) - non-AI simple method
+# -----------------------
+def remove_background_colorkey(input_path: str, color: Tuple[int,int,int]=(255,255,255), tolerance: int = 30) -> str:
+ """
+ color: RGB tuple to remove (default white).
+ tolerance: how close a pixel must be to color to be removed.
+ """
+ img = Image.open(input_path).convert("RGBA")
+ datas = img.getdata()
+ newData = []
+ cr, cg, cb = color
+ for item in datas:
+ r,g,b,a = item
+ if abs(r-cr) <= tolerance and abs(g-cg) <= tolerance and abs(b-cb) <= tolerance:
+ newData.append((255,255,255,0))
+ else:
+ newData.append(item)
+ img.putdata(newData)
+ out = _out_path("png")
+ img.save(out, optimize=True)
+ return out
+
+# -----------------------
+# Border & Text overlay
+# -----------------------
+def add_border(input_path: str, border_px: int = 10, color: str = "#000000") -> str:
+ img = Image.open(input_path)
+ new_w = img.width + border_px*2
+ new_h = img.height + border_px*2
+ new_img = Image.new(img.mode, (new_w, new_h), color)
+ new_img.paste(img, (border_px, border_px))
+ out = _out_path(img.format.lower() if img.format else "png")
+ new_img.save(out, optimize=True)
+ return out
+
+def add_text_overlay(input_path: str, text: str, x: int = 10, y: int = 10, size: int = 24, color: str = "#ffffff") -> str:
+ img = Image.open(input_path).convert("RGBA")
+ txt_layer = Image.new("RGBA", img.size, (255,255,255,0))
+ draw = ImageDraw.Draw(txt_layer)
+ try:
+ font = ImageFont.truetype("arial.ttf", size)
+ except Exception:
+ font = ImageFont.load_default()
+ draw.text((x,y), text, font=font, fill=color)
+ combined = Image.alpha_composite(img, txt_layer)
+ out = _out_path("png")
+ combined.save(out, optimize=True)
+ return out
+
+# -----------------------
+# EXIF view & edit
+# -----------------------
+def read_exif(input_path: str) -> dict:
+ try:
+ data = piexif.load(input_path)
+ return data
+ except Exception:
+ return {}
+
+def write_exif(input_path: str, exif_dict: dict) -> str:
+ img = Image.open(input_path)
+ exif_bytes = piexif.dump(exif_dict)
+ out = _out_path(img.format.lower() if img.format else "jpg")
+ img.save(out, exif=exif_bytes)
+ return out
+def batch_thumbnails(image_paths: list, max_dim: int = 200) -> str:
+ """Generate thumbnails for multiple images and return a ZIP."""
+ out_zip = _out_path("zip")
+ temp_outputs = []
+
+ for p in image_paths:
+ img = Image.open(p)
+ img.thumbnail((max_dim, max_dim), Image.LANCZOS)
+ out_img = _out_path("png")
+ img.save(out_img)
+ temp_outputs.append(out_img)
+
+ with zipfile.ZipFile(out_zip, 'w') as z:
+ for f in temp_outputs:
+ z.write(f, os.path.basename(f))
+
+ # clean individual thumbs
+ for f in temp_outputs:
+ try: os.remove(f)
+ except: pass
+
+ return out_zip
+def ai_upscale_placeholder(input_path: str) -> str:
+ """
+ Placeholder for AI upscaling.
+ It does NOT upscale — only simulates response.
+ """
+ return {
+ "status": "not_implemented",
+ "message": "AI upscaling is not implemented yet. Placeholder endpoint working.",
+ "input_file": os.path.basename(input_path)
+ }
+async def convert_image_to_svg(image_file):
+ try:
+ # Read image
+ image_bytes = await image_file.read()
+ img = Image.open(io.BytesIO(image_bytes))
+
+ # Create an SVG wrapper (raster inside SVG)
+ buffered = io.BytesIO()
+ img.save(buffered, format="PNG") # Keep as PNG inside SVG
+ encoded = base64.b64encode(buffered.getvalue()).decode()
+
+ svg = f'''
+
+
+
+ '''.strip()
+
+ return Response(content=svg, media_type="image/svg+xml")
+
+ except Exception as e:
+ return Response(content=str(e), status_code=500)
diff --git a/services/job_store.py b/services/job_store.py
new file mode 100644
index 0000000000000000000000000000000000000000..6eef16936f0254661b8daed3626782b8bb280e57
--- /dev/null
+++ b/services/job_store.py
@@ -0,0 +1,43 @@
+import os
+import json
+import threading
+
+BASE_DIR = "static/jobs"
+os.makedirs(BASE_DIR, exist_ok=True)
+
+_lock = threading.Lock()
+
+
+def _path(job_id: str):
+ return os.path.join(BASE_DIR, f"{job_id}.json")
+
+
+def create_job(job_id: str, data: dict):
+ with _lock:
+ with open(_path(job_id), "w") as f:
+ json.dump(data, f)
+
+
+def update_job(job_id: str, **updates):
+ with _lock:
+ path = _path(job_id)
+ if not os.path.exists(path):
+ return
+
+ with open(path, "r") as f:
+ job = json.load(f)
+
+ job.update(updates)
+
+ with open(path, "w") as f:
+ json.dump(job, f)
+
+
+def get_job(job_id: str):
+ path = _path(job_id)
+ if not os.path.exists(path):
+ return None
+
+ with open(path, "r") as f:
+ return json.load(f)
+
diff --git a/services/onnx/RealESRGAN_x4plus.onnx b/services/onnx/RealESRGAN_x4plus.onnx
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/services/onnx/RealESRGAN_x4plus_anime_6B.onnx b/services/onnx/RealESRGAN_x4plus_anime_6B.onnx
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/services/pdf_service.py b/services/pdf_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e7c33425b11ec638b622f07d748cf5844b0c215
--- /dev/null
+++ b/services/pdf_service.py
@@ -0,0 +1,517 @@
+# backend/services/pdf_service.py
+import os
+import uuid
+import shutil
+import subprocess
+import tempfile
+from typing import List, Optional, Tuple, Dict, Any
+from core.config import settings
+
+import pikepdf
+import fitz # PyMuPDF
+from reportlab.pdfgen import canvas
+from reportlab.lib.pagesizes import letter
+from reportlab.lib.utils import ImageReader
+from pdf2image import convert_from_path
+import ocrmypdf
+from PIL import Image, ImageDraw
+
+# Ensure paths exist
+os.makedirs(settings.OUTPUT_DIR, exist_ok=True)
+os.makedirs(settings.TEMP_DIR, exist_ok=True)
+
+def _out_name(ext: str = "pdf") -> str:
+ return os.path.join(settings.OUTPUT_DIR, f"{uuid.uuid4()}.{ext.lstrip('.')}")
+
+def _temp_path(suffix: str = "") -> str:
+ return os.path.join(settings.TEMP_DIR, f"{uuid.uuid4()}{suffix}")
+
+# -------------------------
+# Basic PDF ops
+# -------------------------
+def merge_pdfs(paths: List[str]) -> str:
+ """
+ Rock-solid merge using PyMuPDF (fitz).
+ Preserves:
+ - Page order (drag/drop)
+ - Fonts
+ - Vector images
+ - Metadata
+ - Page rotation / orientation
+ """
+
+ out = _out_name("pdf")
+ merged = fitz.open()
+
+ for p in paths:
+ try:
+ src = fitz.open(p)
+ merged.insert_pdf(src)
+ src.close()
+ except Exception as e:
+ raise RuntimeError(f"Failed merging {p}: {e}")
+
+ merged.save(out)
+ merged.close()
+ return out
+
+
+def split_pdf(path: str, ranges: Optional[List[Tuple[int,int]]] = None) -> List[str]:
+ pdf = pikepdf.Pdf.open(path)
+ n = len(pdf.pages)
+ outputs = []
+ if not ranges:
+ for i in range(n):
+ new = pikepdf.Pdf.new()
+ new.pages.append(pdf.pages[i])
+ out = _out_name("pdf")
+ new.save(out)
+ outputs.append(out)
+ return outputs
+ for (s,e) in ranges:
+ s = max(1,s); e = min(n,e)
+ new = pikepdf.Pdf.new()
+ for i in range(s-1,e):
+ new.pages.append(pdf.pages[i])
+ out = _out_name("pdf")
+ new.save(out)
+ outputs.append(out)
+ return outputs
+
+def compress_pdf(path: str, preset: str = "ebook") -> str:
+ # Ghostscript presets: /screen /ebook /printer /prepress
+ ps_map = {"screen":"/screen","ebook":"/ebook","printer":"/printer","prepress":"/prepress","default":"/default"}
+ pset = ps_map.get(preset, "/ebook")
+ out = _out_name("pdf")
+ cmd = ["gs","-sDEVICE=pdfwrite","-dCompatibilityLevel=1.5",f"-dPDFSETTINGS={pset}",
+ "-dNOPAUSE","-dQUIET","-dBATCH",f"-sOutputFile={out}", path]
+ subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ return out
+
+def repair_pdf(input_path: str) -> str:
+ """
+ Fully repaired PDF output stored in a SAFE persistent folder:
+ settings.OUTPUT_DIR (never auto-deleted like /tmp).
+
+ Repair chain:
+ 1. QPDF structural repair
+ 2. Ghostscript rebuild
+ 3. PyMuPDF clean save (garbage collector)
+ """
+
+ import subprocess, os, uuid, fitz, pikepdf
+
+ # -------------------------------
+ # ALWAYS SAVE OUTPUTS IN PERSISTENT DIRECTORY
+ # -------------------------------
+ base = os.path.join(settings.OUTPUT_DIR, f"repair_{uuid.uuid4().hex}")
+ out_qpdf = base + "_qpdf.pdf"
+ out_gs = base + "_gs.pdf"
+ out_clean = base + "_clean.pdf"
+
+ os.makedirs(settings.OUTPUT_DIR, exist_ok=True)
+
+ # -------------------------------
+ # 1️⃣ QPDF STRUCTURE REPAIR
+ # -------------------------------
+ try:
+ subprocess.run(
+ ["qpdf", "--repair", input_path, out_qpdf],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ check=False
+ )
+
+ if os.path.exists(out_qpdf) and os.path.getsize(out_qpdf) > 1024:
+ input_path = out_qpdf # Continue repair chain with improved file
+ except Exception:
+ pass
+
+ # -------------------------------
+ # 2️⃣ GHOSTSCRIPT FULL OBJECT REBUILD
+ # -------------------------------
+ try:
+ subprocess.run([
+ "gs",
+ "-sDEVICE=pdfwrite",
+ "-dCompatibilityLevel=1.6",
+ "-dPDFSETTINGS=/prepress",
+ "-dNOPAUSE",
+ "-dBATCH",
+ "-dQUIET",
+ "-dDetectDuplicateImages=true",
+ "-dEmbedAllFonts=true",
+ "-sOutputFile=" + out_gs,
+ input_path
+ ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
+
+ if os.path.exists(out_gs) and os.path.getsize(out_gs) > 2048:
+ input_path = out_gs
+ except Exception:
+ pass
+
+ # -------------------------------
+ # 3️⃣ FINAL CLEAN NORMALIZATION (PyMuPDF)
+ # -------------------------------
+ try:
+ doc = fitz.open(input_path)
+ doc.save(out_clean, garbage=4, deflate=True)
+ doc.close()
+
+ if os.path.exists(out_clean) and os.path.getsize(out_clean) > 2048:
+ return out_clean
+ except Exception:
+ pass
+
+ # -------------------------------
+ # ❌ TOTAL FAILURE
+ # -------------------------------
+ raise RuntimeError(
+ "PDF is too severely damaged and could not be repaired."
+ )
+
+# -------------------------
+# Page manipulations
+# -------------------------
+def extract_pages(path: str, pages: List[int]) -> str:
+ out = _out_name("pdf")
+ pdf = pikepdf.Pdf.open(path)
+ new = pikepdf.Pdf.new()
+ for p in pages:
+ idx = p-1
+ if 0 <= idx < len(pdf.pages):
+ new.pages.append(pdf.pages[idx])
+ new.save(out)
+ return out
+
+def rotate_pages(path: str, rotations: List[Tuple[int,int]]) -> str:
+ pdf = pikepdf.Pdf.open(path)
+ for page_num, deg in rotations:
+ idx = page_num - 1
+ if 0 <= idx < len(pdf.pages):
+ pdf.pages[idx].Rotate = deg
+ out = _out_name("pdf")
+ pdf.save(out)
+ return out
+
+def reorder_pages(path: str, new_order: List[int]) -> str:
+ pdf = pikepdf.Pdf.open(path)
+ out = _out_name("pdf")
+ new = pikepdf.Pdf.new()
+ for p in new_order:
+ idx = p-1
+ if 0 <= idx < len(pdf.pages):
+ new.pages.append(pdf.pages[idx])
+ new.save(out)
+ return out
+
+def crop_pdf(path: str, page:int, rect:Tuple[float,float,float,float]) -> str:
+ doc = fitz.open(path)
+ p = doc[page-1]
+ p.set_cropbox(rect)
+ out = _out_name("pdf")
+ doc.save(out)
+ doc.close()
+ return out
+
+# -------------------------
+# Protect / Unlock / PDF-A
+# -------------------------
+def protect_pdf(path: str, password: str) -> str:
+ out = _out_name("pdf")
+ with pikepdf.Pdf.open(path) as pdf:
+ pdf.save(out, encryption=pikepdf.Encryption(owner=password, user=password, R=4))
+ return out
+
+def unlock_pdf(path: str, password: Optional[str] = None) -> str:
+ out = _out_name("pdf")
+ try:
+ if password:
+ with pikepdf.Pdf.open(path, password=password) as pdf:
+ pdf.save(out)
+ else:
+ with pikepdf.Pdf.open(path) as pdf:
+ pdf.save(out)
+ return out
+ except Exception as e:
+ raise RuntimeError("Unlock failed: " + str(e))
+
+def convert_to_pdfa(path: str) -> str:
+ out = _out_name("pdf")
+ cmd = ["gs","-dPDFA","-dBATCH","-dNOPAUSE","-sProcessColorModel=DeviceCMYK",
+ "-sDEVICE=pdfwrite","-dPDFACompatibilityPolicy=1", f"-sOutputFile={out}", path]
+ subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ return out
+
+# -------------------------
+# Watermarking (advanced)
+# -------------------------
+def add_advanced_watermark(path: str, text: Optional[str]=None, image_path: Optional[str]=None,
+ pos: Tuple[str,str]=("center","center"), fontsize:int=48, opacity:float=0.15) -> str:
+ tmp_wm = _temp_path(".pdf")
+ c = canvas.Canvas(tmp_wm, pagesize=letter)
+ if text:
+ c.setFont("Helvetica", fontsize)
+ c.saveState()
+ c.setFillAlpha(opacity)
+ c.translate(300,400); c.rotate(45)
+ c.drawCentredString(0,0,text)
+ c.restoreState()
+ if image_path and os.path.exists(image_path):
+ im = ImageReader(image_path)
+ c.drawImage(im, 100, 300, width=400, height=200, mask='auto')
+ c.save()
+ out = _out_name("pdf")
+ base = pikepdf.Pdf.open(path)
+ try:
+ wm = pikepdf.Pdf.open(tmp_wm)
+ for page in base.pages:
+ try:
+ page.add_overlay(wm.pages[0])
+ except Exception:
+ # fallback: append contents
+ for cobj in wm.pages[0].contents:
+ page.contents.append(cobj)
+ finally:
+ base.save(out)
+ try: os.remove(tmp_wm)
+ except: pass
+ return out
+
+# -------------------------
+# Editor: text, rectangle, highlight (PyMuPDF)
+# -------------------------
+def edit_add_text(path: str, page:int, x:float, y:float, text:str, fontsize:int=12) -> str:
+ doc = fitz.open(path)
+ p = doc[page-1]
+ p.insert_text((x,y), text, fontsize=fontsize, fontname="helv")
+ out = _out_name("pdf")
+ doc.save(out)
+ doc.close()
+ return out
+
+def edit_add_rect(path: str, page:int, rect:Tuple[float,float,float,float], color:Tuple[int,int,int]=(255,0,0), fill:bool=False) -> str:
+ doc = fitz.open(path)
+ p = doc[page-1]
+ shape = p.newShape()
+ shape.drawRect(rect)
+ if fill:
+ shape.finish(color=color, fill=color)
+ else:
+ shape.finish(color=color)
+ shape.commit()
+ out = _out_name("pdf")
+ doc.save(out)
+ doc.close()
+ return out
+
+def edit_highlight_text(path: str, page:int, search_text:str) -> str:
+ doc = fitz.open(path)
+ p = doc[page-1]
+ text_instances = p.search_for(search_text)
+ for inst in text_instances:
+ p.add_highlight_annot(inst)
+ out = _out_name("pdf")
+ doc.save(out)
+ doc.close()
+ return out
+
+# -------------------------
+# TRUE Redaction (secure)
+# - Uses PyMuPDF redact API to remove text/glyphs and images in region when destructive=True
+# - Non-destructive overlay available (draw black boxes)
+# -------------------------
+def redact_pdf(path: str,
+ rectangles: Optional[List[Tuple[int,float,float,float,float]]] = None,
+ search_terms: Optional[List[str]] = None,
+ destructive: bool = False) -> str:
+ """
+ rectangles: list of (page, x0, y0, x1, y1)
+ search_terms: list of strings to find and redact
+ destructive: if True uses apply_redactions() (removes text content permanently)
+ """
+ doc = fitz.open(path)
+ # Non-destructive: draw black rects and save
+ if not destructive:
+ if rectangles:
+ for (pnum,x0,y0,x1,y1) in rectangles:
+ page = doc[pnum-1]
+ shape = page.newShape()
+ shape.drawRect((x0,y0,x1,y1))
+ shape.finish(color=(0,0,0), fill=(0,0,0))
+ shape.commit()
+ if search_terms:
+ for pindex in range(len(doc)):
+ page = doc[pindex]
+ for term in search_terms:
+ for inst in page.search_for(term):
+ shape = page.newShape()
+ shape.drawRect(inst)
+ shape.finish(color=(0,0,0), fill=(0,0,0))
+ shape.commit()
+ out = _out_name("pdf")
+ doc.save(out)
+ doc.close()
+ return out
+
+ # Destructive redaction using PyMuPDF redact annotations and apply_redactions
+ for (pnum,x0,y0,x1,y1) in (rectangles or []):
+ page = doc[pnum-1]
+ page.add_redact_annot((x0,y0,x1,y1), fill=(0,0,0))
+ if search_terms:
+ for pindex in range(len(doc)):
+ page = doc[pindex]
+ for term in search_terms:
+ rects = page.search_for(term)
+ for r in rects:
+ page.add_redact_annot(r, fill=(0,0,0))
+ # apply redactions (removes content permanently)
+ doc.apply_redactions()
+ out = _out_name("pdf")
+ doc.save(out)
+ doc.close()
+ return out
+
+# -------------------------
+# OCR (ocrmypdf)
+# -------------------------
+def ocr_pdf(path: str, lang: str = "eng") -> str:
+ out = _out_name("pdf")
+ # ocrmypdf creates a searchable PDF overlaying text
+ ocrmypdf.ocr(path, out, language=lang, use_threads=True)
+ return out
+
+# -------------------------
+# Form filling (AcroForm best-effort)
+# -------------------------
+def fill_pdf_form(path: str, data: Dict[str,str]) -> str:
+ pdf = pikepdf.Pdf.open(path)
+ try:
+ root = pdf.root
+ if '/AcroForm' in root:
+ form = root['/AcroForm']
+ fields = form.get('/Fields', [])
+ for f in fields:
+ fld = f.get_object()
+ name = fld.get('/T')
+ if name and name in data:
+ fld.update({pikepdf.Name('/V'): pikepdf.String(data[name])})
+ out = _out_name("pdf")
+ pdf.save(out)
+ return out
+ except Exception as e:
+ raise RuntimeError("Form fill failed: " + str(e))
+
+# -------------------------
+# Bookmarks / Page numbers / Repair
+# -------------------------
+def add_bookmark(path: str, title: str, page:int) -> str:
+ out = _out_name("pdf")
+ doc = fitz.open(path)
+ # set_toc expects list of [level, title, pagenum]
+ doc.set_toc([[1, title, page]])
+ doc.save(out)
+ doc.close()
+ return out
+
+def add_page_numbers(path: str, start:int=1, position:str="bottom-right", fmt:str="{page}") -> str:
+ images = convert_from_path(path, dpi=150)
+ tmp_pdfs = []
+ for i, img in enumerate(images, start=1):
+ tmp_img = _temp_path(".png")
+ img.save(tmp_img, format="PNG")
+ tmp_pdf = _temp_path(".pdf")
+ c = canvas.Canvas(tmp_pdf, pagesize=letter)
+ c.drawImage(ImageReader(tmp_img), 0, 0, preserveAspectRatio=True)
+ text = fmt.format(page=i+start-1)
+ if position=="bottom-right":
+ c.drawString(500,20,text)
+ elif position=="bottom-left":
+ c.drawString(40,20,text)
+ else:
+ c.drawCentredString(300,20,text)
+ c.showPage()
+ c.save()
+ tmp_pdfs.append(tmp_pdf)
+ try: os.remove(tmp_img)
+ except: pass
+ # merge tmp_pdfs
+ return merge_pdfs(tmp_pdfs)
+
+# -------------------------
+# Document comparison (textual diff rendered into a PDF)
+# -------------------------
+def compare_documents(path_a: str, path_b: str) -> str:
+ def extract_text(pth: str) -> str:
+ d = fitz.open(pth)
+ texts = [pg.get_text() for pg in d]
+ d.close()
+ return "\n".join(texts)
+ a = extract_text(path_a)
+ b = extract_text(path_b)
+ import difflib
+ diff_lines = list(difflib.unified_diff(a.splitlines(), b.splitlines(), lineterm=""))
+ out = _out_name("pdf")
+ c = canvas.Canvas(out, pagesize=letter)
+ y = 750
+ for line in diff_lines:
+ c.drawString(10,y,line[:120])
+ y -= 10
+ if y < 60:
+ c.showPage()
+ y = 750
+ c.save()
+ return out
+
+# -------------------------
+# AI: local summarizer & translator (pluggable)
+# - Attempts to use transformers pipeline if available locally
+# - Otherwise raises clear error
+# -------------------------
+def _call_local_llm(prompt: str, mode: str = "summarize", max_length: int = 1024) -> str:
+ """
+ Try to run a local transformers pipeline for summarization/translation.
+ If transformers isn't present or no model downloaded, raise RuntimeError with instructions.
+ """
+ try:
+ from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
+ except Exception:
+ raise RuntimeError("Local transformers not installed. Install 'transformers' and download a local summarization/translation model.")
+
+ if mode == "summarize":
+ # example model: "facebook/bart-large-cnn" (download locally beforehand)
+ pipe = pipeline("summarization", model="facebook/bart-large-cnn", device=-1)
+ out = pipe(prompt, max_length=max_length, truncation=True)
+ return out[0]["summary_text"]
+ elif mode == "translate":
+ # example model: "Helsinki-NLP/opus-mt-xx-yy" - user should select proper model
+ pipe = pipeline("translation", model="Helsinki-NLP/opus-mt-en-ROMANCE", device=-1)
+ out = pipe(prompt, max_length=max_length, truncation=True)
+ return out[0]["translation_text"]
+ else:
+ raise RuntimeError("Unsupported LLM mode: " + str(mode))
+
+def summarize_document(path: str) -> str:
+ # extract first ~40k chars and call local llm
+ doc = fitz.open(path)
+ text = "".join([p.get_text() for p in doc])[:40000]
+ doc.close()
+ return _call_local_llm(text, mode="summarize")
+
+def translate_document(path: str, target_lang: str = "en") -> str:
+ doc = fitz.open(path)
+ text = "".join([p.get_text() for p in doc])[:40000]
+ doc.close()
+ prompt = f"Translate to {target_lang}:\n\n{text}"
+ translated = _call_local_llm(prompt, mode="translate")
+ # render translated text into a PDF
+ out_pdf = _out_name("pdf")
+ c = canvas.Canvas(out_pdf, pagesize=letter)
+ y = 750
+ for line in translated.splitlines():
+ c.drawString(40,y,line[:1000]); y -= 12
+ if y < 80:
+ c.showPage(); y = 750
+ c.save()
+ return out_pdf
+
diff --git a/services/stats_service.py b/services/stats_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..37af26264de91cb7e50f26eaa849e1b923f131f1
--- /dev/null
+++ b/services/stats_service.py
@@ -0,0 +1,120 @@
+# backend/services/stats_service.py
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.orm import Session
+from sqlalchemy import func
+from core.models import UsageStat
+from datetime import datetime
+from typing import List, Dict
+
+def increment_tool_usage(db: Session, tool_name: str, event_type: str):
+ normalized = (
+ tool_name.strip()
+ .lower()
+ .replace(" ", "_")
+ .replace("-", "_")
+ )
+
+ try:
+ stat = (
+ db.query(UsageStat)
+ .filter(UsageStat.tool_name == normalized)
+ .with_for_update() # ✅ LOCK ROW TO PREVENT RACE CONDITION
+ .first()
+ )
+
+ if not stat:
+ stat = UsageStat(
+ tool_name=normalized,
+ usage_count=0,
+ open_count=0,
+ process_count=0,
+ download_count=0,
+ last_used_at=datetime.utcnow(),
+ )
+ db.add(stat)
+ db.flush() # ✅ Forces INSERT now so we catch duplicates safely
+
+ # ✅ Master counter
+ stat.usage_count += 1
+
+ # ✅ Event counters
+ if event_type == "open":
+ stat.open_count += 1
+ elif event_type == "process":
+ stat.process_count += 1
+ elif event_type == "download":
+ stat.download_count += 1
+
+ stat.last_used_at = datetime.utcnow()
+ db.commit()
+ db.refresh(stat)
+
+ except IntegrityError:
+ # ✅ If duplicate happened anyway, recover safely
+ db.rollback()
+
+ stat = (
+ db.query(UsageStat)
+ .filter(UsageStat.tool_name == normalized)
+ .first()
+ )
+
+ if stat:
+ stat.usage_count += 1
+ if event_type == "open":
+ stat.open_count += 1
+ elif event_type == "process":
+ stat.process_count += 1
+ elif event_type == "download":
+ stat.download_count += 1
+
+ stat.last_used_at = datetime.utcnow()
+ db.commit()
+
+def get_all_tool_stats(db: Session) -> List[Dict]:
+ """
+ Returns list: [{"tool_name": "...", "count": ...}]
+ """
+ results = db.query(
+ UsageStat.tool_name,
+ UsageStat.usage_count
+ ).order_by(UsageStat.usage_count.desc()).all()
+
+ return [{"tool_name": r.tool_name, "count": r.usage_count} for r in results]
+
+
+def get_tool_usage_by_day(db: Session) -> List[Dict]:
+ """
+ Returns list aggregated by day: [{"date": "2025-11-20", "count": 250}]
+ """
+ results = db.query(
+ func.date(UsageStat.last_used_at).label("day"),
+ func.sum(UsageStat.usage_count).label("count")
+ ).group_by(func.date(UsageStat.last_used_at)).order_by(func.date(UsageStat.last_used_at)).all()
+
+ return [{"date": str(r.day), "count": r.count} for r in results]
+
+
+def get_tool_usage_by_month(db: Session) -> List[Dict]:
+ """
+ Returns list aggregated by month: [{"period": "2025-11", "count": 12000}]
+ """
+ results = db.query(
+ func.to_char(UsageStat.last_used_at, "YYYY-MM").label("period"),
+ func.sum(UsageStat.usage_count).label("count")
+ ).group_by("period").order_by("period").all()
+
+ return [{"period": r.period, "count": r.count} for r in results]
+
+
+def get_tool_usage_by_year(db: Session) -> List[Dict]:
+ """
+ Returns list aggregated by year: [{"period": "2025", "count": 100000}]
+ """
+ results = db.query(
+ func.to_char(UsageStat.last_used_at, "YYYY").label("period"),
+ func.sum(UsageStat.usage_count).label("count")
+ ).group_by("period").order_by("period").all()
+
+ return [{"period": r.period, "count": r.count} for r in results]
+
diff --git a/services/universal_converter_service.py b/services/universal_converter_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..16bd1fcb22462ef33bb56b80190a074db68894f5
--- /dev/null
+++ b/services/universal_converter_service.py
@@ -0,0 +1,254 @@
+import os
+import uuid
+import time
+import shutil
+import base64
+import subprocess
+import textwrap
+
+from core.config import settings
+from utils import (
+ ffmpeg_utils,
+ imagemagic_utils,
+ ghostscript_utils,
+ validate_utils,
+)
+
+from utils.pandoc_utils import convert_pandoc
+from utils.archive_utils import extract_archive, rezip_folder
+from PIL import Image, ImageDraw, ImageFont
+
+os.makedirs(settings.OUTPUT_DIR, exist_ok=True)
+
+# =================================================
+# MAIN CONVERTER
+# =================================================
+def convert_file(input_path: str, target_ext: str):
+ print("\n========== CONVERT FILE ==========")
+
+ if not os.path.exists(input_path):
+ raise RuntimeError("Input file not found")
+
+ size = os.path.getsize(input_path)
+ if size == 0:
+ raise RuntimeError("Uploaded file is empty")
+
+ input_ext = os.path.splitext(input_path)[1].lower().lstrip(".")
+ target_ext = target_ext.lower().lstrip(".")
+ mime = (validate_utils.get_mime_type(input_path) or "").lower()
+
+ print(f"INPUT: {input_ext} | TARGET: {target_ext} | MIME: {mime} | SIZE: {size}")
+
+ if target_ext == "doc":
+ target_ext = "docx"
+
+ # -------------------------------------------------
+ # SAME FORMAT RULES
+ # -------------------------------------------------
+ if input_ext == target_ext:
+ if input_ext == "pdf":
+ pass
+ elif mime.startswith(("audio/", "video/")):
+ pass
+ else:
+ raise RuntimeError("Input and output formats are the same")
+
+ # =================================================
+ # IMAGE → SVG (HQ EMBED)
+ # =================================================
+ if mime.startswith("image/") and target_ext == "svg":
+ output = image_to_svg_embed_hq(input_path)
+ _debug_output(output)
+ return output
+
+ # =================================================
+ # IMAGE → ICO
+ # =================================================
+ if mime.startswith("image/") and target_ext == "ico":
+ output = image_to_favicon(input_path)
+ _debug_output(output)
+ return output
+
+ # =================================================
+ # IMAGE → IMAGE
+ # =================================================
+ if mime.startswith("image/"):
+ output = imagemagic_utils.convert_image(input_path, target_ext)
+ _debug_output(output)
+ return output
+
+ # =================================================
+ # PDF
+ # =================================================
+ if mime == "application/pdf":
+ if target_ext == "pdf":
+ output = ghostscript_utils.compress_pdf(input_path)
+ elif target_ext == "docx":
+ from pdf2docx import Converter
+
+ output = os.path.join(settings.OUTPUT_DIR, f"{uuid.uuid4().hex}.docx")
+
+ try:
+ # ---- NORMAL CONVERSION ----
+ cv = Converter(input_path)
+ cv.convert(output)
+ cv.close()
+
+ except Exception as e:
+ print("PDF2DOCX failed — trying OCR:", repr(e))
+
+ # ---- CHECK PAGE COUNT FIRST ----
+ try:
+ pdfinfo = subprocess.check_output(["pdfinfo", input_path]).decode()
+ pages = next(int(line.split()[1]) for line in pdfinfo.splitlines() if line.startswith("Pages:"))
+ except Exception:
+ pages = 0
+
+ if pages == 0:
+ raise RuntimeError("PDF file contains no readable pages")
+
+ # ---- CLEAN/REPAIR PDF ----
+ clean_pdf = os.path.join(settings.OUTPUT_DIR, f"{uuid.uuid4().hex}_clean.pdf")
+ subprocess.run([
+ "gs",
+ "-sDEVICE=pdfwrite",
+ "-dNOPAUSE",
+ "-dBATCH",
+ "-dSAFER",
+ f"-sOutputFile={clean_pdf}",
+ input_path
+ ], check=True)
+
+ # ---- OCR LAYER ----
+ ocr_pdf = os.path.join(settings.OUTPUT_DIR, f"{uuid.uuid4().hex}_ocr.pdf")
+ subprocess.run([
+ "--force-ocr",
+ "ocrmypdf",
+ "--optimize", "3",
+ "--deskew",
+ "--rotate-pages",
+ clean_pdf,
+ ocr_pdf
+ ], check=True)
+
+ # ---- FINAL CONVERSION ----
+ cv = Converter(ocr_pdf)
+ cv.convert(output)
+ cv.close()
+
+ else:
+ output = imagemagic_utils.convert_image(input_path, target_ext)
+
+ _debug_output(output)
+ return output
+
+ # =================================================
+ # DOCUMENTS
+ # =================================================
+ if input_ext in {"txt", "md", "markdown", "html", "rtf", "docx"} or mime.startswith("text/"):
+ output = convert_pandoc(input_path, target_ext)
+ _debug_output(output)
+ return output
+
+ # =================================================
+ # ARCHIVES
+ # =================================================
+ if input_ext in {"zip", "tar", "gz", "tgz", "bz2", "7z", "rar"}:
+ folder = extract_archive(input_path)
+ output = rezip_folder(folder, target_ext)
+ _debug_output(output)
+ return output
+
+ # =================================================
+ # AUDIO / VIDEO (FIXED)
+ # =================================================
+ if mime.startswith(("audio/", "video/")):
+ output = ffmpeg_utils.run_ffmpeg(input_path, target_ext)
+ _debug_output(output)
+ return output
+
+ # =================================================
+ # OFFICE
+ # =================================================
+ if input_ext in {"doc", "docx", "ppt", "pptx", "xls", "xlsx", "odt", "ods", "odp"}:
+ output = _convert_libreoffice(input_path, target_ext)
+ _debug_output(output)
+ return output
+
+ raise RuntimeError(f"Conversion not supported: {input_ext} → {target_ext}")
+
+
+# =================================================
+# DEBUG
+# =================================================
+def _debug_output(path):
+ print("---- OUTPUT DEBUG ----")
+ print("OUTPUT:", path)
+ print("EXISTS:", os.path.exists(path))
+ print("SIZE:", os.path.getsize(path))
+ try:
+ print(subprocess.check_output(["file", path]).decode())
+ except:
+ pass
+ print("----------------------")
+
+
+# =================================================
+# IMAGE → SVG (HQ EMBED)
+# =================================================
+def image_to_svg_embed_hq(input_path):
+ uid = uuid.uuid4().hex
+ tmp = f"/tmp/{uid}.png"
+ out = os.path.join(settings.OUTPUT_DIR, f"{uid}.svg")
+
+ subprocess.run(["convert", input_path, "-resize", "2048x2048", tmp], check=True)
+
+ with open(tmp, "rb") as f:
+ b64 = base64.b64encode(f.read()).decode()
+
+ svg = f"""
+
+ """
+
+ with open(out, "w") as f:
+ f.write(svg)
+
+ os.remove(tmp)
+ return out
+
+
+# =================================================
+# IMAGE → FAVICON
+# =================================================
+def image_to_favicon(input_path):
+ out = os.path.join(settings.OUTPUT_DIR, f"{uuid.uuid4().hex}.ico")
+ subprocess.run(
+ ["convert", input_path, "-define", "icon:auto-resize=256,128,64,32,16", out],
+ check=True
+ )
+ return out
+
+
+# =================================================
+# LIBREOFFICE
+# =================================================
+def _convert_libreoffice(input_path, target_ext):
+ soffice = shutil.which("soffice") or shutil.which("libreoffice")
+ if not soffice:
+ raise RuntimeError("LibreOffice not installed")
+
+ subprocess.run([
+ soffice, "--headless",
+ "--convert-to", target_ext,
+ "--outdir", settings.OUTPUT_DIR,
+ input_path
+ ], check=True)
+
+ base = os.path.splitext(os.path.basename(input_path))[0]
+ out = os.path.join(settings.OUTPUT_DIR, f"{base}.{target_ext}")
+
+ time.sleep(0.5)
+ if not os.path.exists(out):
+ raise RuntimeError("LibreOffice failed")
+
+ return out
diff --git a/services/utility_service.py b/services/utility_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e7f3e82fae84cd8f9e0a150092a0d2da50fe4a5
--- /dev/null
+++ b/services/utility_service.py
@@ -0,0 +1,144 @@
+# backend/services/utility_service.py
+import base64
+import re
+import uuid
+import random
+import string
+import time
+import json
+from datetime import datetime
+from typing import Dict, Any
+from urllib.parse import quote, unquote
+
+import markdown as md
+
+
+# ----------------------------
+# TEXT TOOLS
+# ----------------------------
+
+def convert_case(text: str, mode: str) -> str:
+ mode = mode.lower()
+ if mode == "upper":
+ return text.upper()
+ elif mode == "lower":
+ return text.lower()
+ elif mode == "title":
+ return text.title()
+ elif mode == "sentence":
+ return text.capitalize()
+ elif mode == "alternating":
+ return "".join(c.upper() if i % 2 else c.lower() for i, c in enumerate(text))
+ else:
+ return text # raw return fallback
+
+
+def word_counter(text: str) -> Dict[str, Any]:
+ words = re.findall(r"\b\w+\b", text)
+ chars = len(text)
+ sentences = len(re.findall(r"[.!?]", text))
+ paragraphs = len([p for p in text.split("\n") if p.strip() != ""])
+ return {
+ "words": len(words),
+ "characters": chars,
+ "sentences": sentences,
+ "paragraphs": paragraphs,
+ }
+
+
+def lorem_ipsum(paragraphs: int = 1) -> str:
+ base = (
+ "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
+ "Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "
+ "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip."
+ )
+ return "\n\n".join([base for _ in range(max(1, paragraphs))])
+
+
+def markdown_preview(md_text: str) -> str:
+ return md.markdown(md_text, extensions=["fenced_code", "tables"])
+
+
+# ----------------------------
+# WEB & DATA TOOLS
+# ----------------------------
+
+def url_encode(text: str) -> str:
+ return quote(text)
+
+def url_decode(text: str) -> str:
+ return unquote(text)
+
+
+def hex_to_rgb(hex_color: str):
+ hex_color = hex_color.lstrip("#")
+ if len(hex_color) == 3:
+ hex_color = "".join([c*2 for c in hex_color])
+ r = int(hex_color[0:2], 16)
+ g = int(hex_color[2:4], 16)
+ b = int(hex_color[4:6], 16)
+ return {"r": r, "g": g, "b": b}
+
+
+def rgb_to_hex(r: int, g: int, b: int):
+ return "#{:02X}{:02X}{:02X}".format(r, g, b)
+
+
+def rgb_to_hsl(r, g, b):
+ r /= 255; g /= 255; b /= 255
+ mx = max(r,g,b); mn = min(r,g,b)
+ diff = mx - mn
+ l = (mx + mn) / 2
+
+ if diff == 0:
+ h = s = 0
+ else:
+ s = diff / (1 - abs(2*l - 1))
+ if mx == r:
+ h = 60 * (((g - b) / diff) % 6)
+ elif mx == g:
+ h = 60 * (((b - r) / diff) + 2)
+ else:
+ h = 60 * (((r - g) / diff) + 4)
+ return {"h": round(h,2), "s": round(s,2), "l": round(l,2)}
+
+
+def timestamp_to_human(ts: int) -> str:
+ return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
+
+
+def human_to_timestamp(date_str: str) -> int:
+ dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
+ return int(dt.timestamp())
+
+
+def ip_lookup(ip: str) -> Dict[str, Any]:
+ """
+ Local lookup only.
+ No external API unless you approve.
+ Returns internal info only.
+ """
+ return {
+ "ip": ip,
+ "info": "Local lookup only. Enable external API if needed.",
+ }
+
+
+# ----------------------------
+# SECURITY TOOLS
+# ----------------------------
+
+def generate_uuid() -> str:
+ return str(uuid.uuid4())
+
+
+def generate_password(length: int = 12, upper: bool = True, digits: bool = True, symbols: bool = True) -> str:
+ base = string.ascii_lowercase
+ if upper:
+ base += string.ascii_uppercase
+ if digits:
+ base += string.digits
+ if symbols:
+ base += "!@#$%^&*()_+-=[]{}|;:,.<>?"
+ return "".join(random.choice(base) for _ in range(length))
+
diff --git a/services/video_service.py b/services/video_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f3dbb8548acfd02f1ac8f4d2a4c4dcfc5eef0ee
--- /dev/null
+++ b/services/video_service.py
@@ -0,0 +1,507 @@
+# backend/services/video_service.py
+import os
+import uuid
+import subprocess
+import shutil
+from typing import List, Optional, Tuple, Dict, Any
+from core.config import settings
+from pathlib import Path
+
+import ffmpeg # ffmpeg-python wrapper
+from moviepy.editor import VideoFileClip, concatenate_videoclips
+import numpy as np
+import cv2
+
+# Ensure dirs exist
+os.makedirs(settings.OUTPUT_DIR, exist_ok=True)
+os.makedirs(settings.TEMP_DIR, exist_ok=True)
+
+def _out_name(ext="mp4") -> str:
+ return os.path.join(settings.OUTPUT_DIR, f"{uuid.uuid4()}.{ext.lstrip('.')}")
+
+def _temp_name(ext="mp4") -> str:
+ return os.path.join(settings.TEMP_DIR, f"{uuid.uuid4()}.{ext.lstrip('.')}")
+
+# ---------- Core utilities ----------
+def _run_cmd(cmd: List[str]):
+ """Run subprocess and swallow output (used for ffmpeg commands)."""
+ proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ return proc.returncode, proc.stdout, proc.stderr
+
+# ---------- Basic conversions ----------
+def convert_video(input_path: str, output_path: str, target_format: str):
+ try:
+ if target_format.lower() == "gif":
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", input_path,
+ "-vf",
+ "fps=10,scale=1280:-1:flags=lanczos,split[s0][s1];"
+ "[s0]palettegen[p];"
+ "[s1][p]paletteuse",
+ output_path
+ ]
+
+ else:
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", input_path,
+ output_path
+ ]
+
+ subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+
+ except subprocess.CalledProcessError as e:
+ print("FFmpeg Error:\n", e.stderr.decode())
+ raise RuntimeError("Video conversion failed")
+
+
+def cut_video(input_path: str, start: float = 0.0, duration: Optional[float] = None, reencode: bool = False) -> str:
+ out = _out_name("mp4")
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-ss", str(start)]
+ if duration:
+ cmd += ["-t", str(duration)]
+ if not reencode:
+ # try stream copy
+ cmd += ["-c", "copy", out]
+ else:
+ cmd += [out]
+ _run_cmd(cmd)
+ return out
+
+def merge_videos(input_paths: List[str], target_ext: str = "mp4") -> str:
+ """
+ Merge by re-encoding or by concat demuxer when inputs are identical. We'll use moviepy fallback for robustness.
+ """
+ clips = []
+ for p in input_paths:
+ clips.append(VideoFileClip(p))
+ final = concatenate_videoclips(clips)
+ out = _out_name(target_ext)
+ final.write_videofile(out, codec="libx264", audio_codec="aac", verbose=False, logger=None)
+ for c in clips:
+ try: c.close()
+ except: pass
+ return out
+
+# ---------- Compression ----------
+def compress_video(input_path: str, crf: int = 28, preset: str = "medium", target_ext: str = "mp4") -> str:
+ """
+ Use libx264 CRF-based compression. crf: lower => higher quality. preset: ultrafast..veryslow
+ """
+ out = _out_name(target_ext)
+ cmd = [
+ "ffmpeg", "-y", "-i", input_path,
+ "-c:v", "libx264", "-preset", preset, "-crf", str(crf),
+ "-c:a", "aac", "-b:a", "128k",
+ out
+ ]
+ _run_cmd(cmd)
+ return out
+
+# ---------- Extract / Replace audio ----------
+def extract_audio(input_path: str, target_ext: str = "mp3") -> str:
+ out = _out_name(target_ext)
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-vn", "-acodec", "libmp3lame", "-q:a", "2", out]
+ _run_cmd(cmd)
+ return out
+
+def replace_audio(video_path: str, audio_path: str, target_ext: str = "mp4") -> str:
+ out = _out_name(target_ext)
+ cmd = ["ffmpeg", "-y", "-i", video_path, "-i", audio_path, "-c:v", "copy", "-map", "0:v:0", "-map", "1:a:0", out]
+ _run_cmd(cmd)
+ return out
+
+# ---------- Resolution & speed ----------
+def change_resolution(input_path: str, width: Optional[int] = None, height: Optional[int] = None, target_ext: str = "mp4") -> str:
+ out = _out_name(target_ext)
+ if not width and not height:
+ raise ValueError("width or height required")
+ scale = f"scale={width if width else -2}:{height if height else -2}"
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-vf", scale, "-c:v", "libx264", "-crf", "23", out]
+ _run_cmd(cmd)
+ return out
+
+def change_speed(input_path: str, speed: float = 1.0, target_ext: str = "mp4") -> str:
+ out = _out_name(target_ext)
+ # setpts for video, atempo for audio (chain if out of range)
+ # audio atempo supports 0.5-2. For other ratios chain a tempo filter.
+ # Build complex filter
+ video_filter = f"setpts={1/speed}*PTS"
+ if 0.5 <= speed <= 2.0:
+ audio_filter = f"atempo={speed}"
+ else:
+ # chain
+ parts = []
+ s = speed
+ while s < 0.5 or s > 2.0:
+ if s < 0.5:
+ parts.append("atempo=0.5"); s /= 0.5
+ else:
+ parts.append("atempo=2.0"); s /= 2.0
+ parts.append(f"atempo={s}")
+ audio_filter = ",".join(parts)
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-vf", video_filter, "-af", audio_filter, out]
+ _run_cmd(cmd)
+ return out
+
+# ---------- Stabilization (vidstab) ----------
+def stabilize_video(input_path: str, target_ext: str = "mp4") -> str:
+ """
+ Requires ffmpeg compiled with libvidstab. Two-pass:
+ 1) generate transforms
+ 2) apply transforms
+ """
+ out = _out_name(target_ext)
+ trans_file = os.path.join(settings.TEMP_DIR, f"trans_{uuid.uuid4()}.trf")
+ step1 = ["ffmpeg", "-y", "-i", input_path, "-vf", f"vidstabdetect=shakiness=10:accuracy=15:result={trans_file}", "-f", "null", "-"]
+ _run_cmd(step1)
+ step2 = ["ffmpeg", "-y", "-i", input_path, "-vf", f"vidstabtransform=input={trans_file}", "-c:v", "libx264", "-crf", "23", out]
+ _run_cmd(step2)
+ try:
+ os.remove(trans_file)
+ except:
+ pass
+ return out
+
+# ---------- Thumbnails, GIF, frames ----------
+def generate_thumbnail(input_path: str, time: float = 1.0, width: int = 320, target_ext: str = "jpg") -> str:
+ out = _out_name(target_ext)
+ cmd = ["ffmpeg", "-y", "-ss", str(time), "-i", input_path, "-vframes", "1", "-vf", f"scale={width}:-2", out]
+ _run_cmd(cmd)
+ return out
+
+def video_to_gif(input_path: str, start: float = 0.0, duration: float = 3.0, width: int = 320, target_ext: str = "gif") -> str:
+ out = _out_name(target_ext)
+ cmd = [
+ "ffmpeg", "-y", "-ss", str(start), "-t", str(duration), "-i", input_path,
+ "-vf", f"fps=15,scale={width}:-1:flags=lanczos", "-gifflags", "-transdiff", "-y", out
+ ]
+ _run_cmd(cmd)
+ return out
+
+def extract_frames(input_path: str, every_n: int = 1) -> List[str]:
+ """
+ Extract every Nth frame and return list of file paths (jpg).
+ """
+ base = os.path.join(settings.TEMP_DIR, f"frames_{uuid.uuid4()}")
+ os.makedirs(base, exist_ok=True)
+ pattern = os.path.join(base, "frame_%05d.jpg")
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-vf", f"select=not(mod(n\\,{every_n}))", "-vsync", "vfr", pattern]
+ _run_cmd(cmd)
+ # collect files
+ files = sorted([os.path.join(base, f) for f in os.listdir(base)])
+ return files
+
+# ---------- Crop, rotate, watermark ----------
+def crop_video(input_path: str, x: int, y: int, w: int, h: int, target_ext: str = "mp4") -> str:
+ out = _out_name(target_ext)
+
+ # ✅ HARD SAFETY: Prevent FFmpeg crashes
+ x = max(0, int(x))
+ y = max(0, int(y))
+ w = max(2, int(w))
+ h = max(2, int(h))
+
+ cmd = [
+ "ffmpeg",
+ "-y",
+ "-i", input_path,
+ "-vf", f"crop={w}:{h}:{x}:{y}",
+ "-c:v", "libx264", # ✅ re-encode video safely
+ "-c:a", "aac", # ✅ avoids broken audio streams
+ out
+ ]
+
+ code, stdout, stderr = _run_cmd(cmd)
+
+ # ✅ CRITICAL: If FFmpeg failed, raise error instead of ghost return
+ if code != 0:
+ raise RuntimeError(
+ f"FFmpeg crop failed\n"
+ f"CMD: {' '.join(cmd)}\n"
+ f"STDERR: {stderr.decode(errors='ignore')}"
+ )
+
+ return out
+
+
+def rotate_video(input_path: str, degrees: int = 90, target_ext: str = "mp4") -> str:
+ out = _out_name(target_ext)
+ # ffmpeg transpose values: 1=90cw,2=180cw,3=270cw
+ transpose_map = {90: "transpose=1", 180: "transpose=1,transpose=1", 270: "transpose=2"}
+ vf = transpose_map.get(degrees, "")
+ if vf:
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-vf", vf, out]
+ else:
+ # fallback: rotate filter with degrees
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-vf", f"rotate={np.deg2rad(degrees)}", out]
+ _run_cmd(cmd)
+ return out
+
+def add_watermark_video(input_path: str, watermark_path: str, x: int = 10, y: int = 10, opacity: float = 0.7, target_ext: str = "mp4") -> str:
+ out = _out_name(target_ext)
+ # prepare overlay with alpha (assuming watermark PNG has alpha)
+ # set opacity by using colorchannelmixer or overlay with format
+ cmd = [
+ "ffmpeg", "-y", "-i", input_path, "-i", watermark_path,
+ "-filter_complex", f"[1]format=rgba,colorchannelmixer=aa={opacity}[wm];[0][wm]overlay={x}:{y}",
+ "-c:a", "copy", out
+ ]
+ _run_cmd(cmd)
+ return out
+
+# ---------- Bitrate control / keyframe ----------
+def reencode_with_bitrate(input_path: str, v_bitrate: str = "2000k", a_bitrate: str = "128k", target_ext: str = "mp4") -> str:
+ out = _out_name(target_ext)
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-b:v", v_bitrate, "-b:a", a_bitrate, out]
+ _run_cmd(cmd)
+ return out
+
+def extract_keyframes(input_path: str) -> List[str]:
+ dest = os.path.join(settings.TEMP_DIR, f"keyframes_{uuid.uuid4()}")
+ os.makedirs(dest, exist_ok=True)
+ pattern = os.path.join(dest, "kf_%05d.jpg")
+ # -skip_frame nokey selects keyframes, or use select=eq(pict_type\,I)
+ cmd = ["ffmpeg", "-y", "-i", input_path, "-vf", "select='eq(pict_type,PICT_TYPE_I)'", "-vsync", "vfr", pattern]
+ _run_cmd(cmd)
+ files = sorted([os.path.join(dest, f) for f in os.listdir(dest)])
+ return files
+
+# ---------- Placeholder: AI Super-Resolution (local heavy) ----------
+def ai_superres_realesrgan_ncnn_vulkan(input_path: str, scale: int = 2, model_name: str = "realesrgan-x4plus", model_dir: str = "/opt/realesrgan-models", keep_audio: bool = True) -> str:
+ import subprocess, os, uuid, shutil
+ from core.config import settings
+
+ def _out_name(ext="mp4"):
+ return os.path.join(settings.OUTPUT_DIR, f"{uuid.uuid4()}.{ext.lstrip('.')}")
+
+ def _temp_dir(prefix="rsr"):
+ d = os.path.join(settings.TEMP_DIR, f"{prefix}_{uuid.uuid4()}")
+ os.makedirs(d, exist_ok=True)
+ return d
+
+ def _ffprobe_fps(path):
+ try:
+ cmd = [
+ "ffprobe", "-v", "error",
+ "-select_streams", "v:0",
+ "-show_entries", "stream=r_frame_rate",
+ "-of", "default=noprint_wrappers=1:nokey=1",
+ path
+ ]
+ out = subprocess.check_output(cmd, stderr=subprocess.DEVNULL).decode().strip()
+ if "/" in out:
+ a, b = out.split("/")
+ return float(a) / float(b)
+ return float(out)
+ except:
+ return 25.0
+
+ binary = shutil.which("realesrgan-ncnn-vulkan")
+ if not binary:
+ raise RuntimeError("realesrgan-ncnn-vulkan not installed or not in PATH")
+
+ param = os.path.join(model_dir, f"{model_name}.param")
+ binf = os.path.join(model_dir, f"{model_name}.bin")
+ if not (os.path.exists(param) and os.path.exists(binf)):
+ raise RuntimeError("Model files not found in model_dir")
+
+ temp_frames = _temp_dir("frames")
+ up_frames = _temp_dir("up")
+
+ try:
+ # 1. Extract frames
+ frame_pattern = os.path.join(temp_frames, "frame_%06d.png")
+ subprocess.run(["ffmpeg", "-y", "-i", input_path, "-vsync", "0", frame_pattern], check=True)
+
+ fps = _ffprobe_fps(input_path)
+
+ # detect audio
+ has_audio = True
+ try:
+ cmd = [
+ "ffprobe", "-v", "error", "-select_streams", "a",
+ "-show_entries", "stream=index",
+ "-of", "default=noprint_wrappers=1:nokey=1",
+ input_path
+ ]
+ audio_exists = subprocess.check_output(cmd, stderr=subprocess.DEVNULL).decode().strip()
+ has_audio = audio_exists != ""
+ except:
+ has_audio = False
+
+ # 2. Upscale frames using Real-ESRGAN
+ frames = sorted([f for f in os.listdir(temp_frames) if f.endswith(".png")])
+ if not frames:
+ raise RuntimeError("No frames extracted")
+
+ for fname in frames:
+ inp = os.path.join(temp_frames, fname)
+ out = os.path.join(up_frames, fname)
+ subprocess.run([
+ binary,
+ "-i", inp,
+ "-o", out,
+ "-s", str(scale),
+ "-m", param
+ ], check=True)
+
+ # 3. Rebuild video
+ up_pattern = os.path.join(up_frames, "frame_%06d.png")
+ out_video = _out_name("mp4")
+
+ if has_audio and keep_audio:
+ # extract audio
+ audio_tmp = os.path.join(settings.TEMP_DIR, f"aud_{uuid.uuid4()}.aac")
+ subprocess.run(["ffmpeg", "-y", "-i", input_path, "-vn", "-acodec", "copy", audio_tmp], check=False)
+
+ # build raw video
+ raw_video = os.path.join(settings.TEMP_DIR, f"tmp_{uuid.uuid4()}.mp4")
+ subprocess.run([
+ "ffmpeg", "-y",
+ "-framerate", str(fps),
+ "-i", up_pattern,
+ "-c:v", "libx264",
+ "-pix_fmt", "yuv420p",
+ raw_video
+ ], check=True)
+
+ # merge audio
+ subprocess.run([
+ "ffmpeg", "-y",
+ "-i", raw_video,
+ "-i", audio_tmp,
+ "-c:v", "copy",
+ "-c:a", "aac",
+ "-b:a", "192k",
+ out_video
+ ], check=True)
+
+ try:
+ os.remove(raw_video)
+ os.remove(audio_tmp)
+ except:
+ pass
+
+ else:
+ subprocess.run([
+ "ffmpeg", "-y",
+ "-framerate", str(fps),
+ "-i", up_pattern,
+ "-c:v", "libx264",
+ "-pix_fmt", "yuv420p",
+ out_video
+ ], check=True)
+
+ return out_video
+
+ finally:
+ try: shutil.rmtree(temp_frames)
+ except: pass
+ try: shutil.rmtree(up_frames)
+ except: pass
+def ai_superres_placeholder(input_path: str):
+ """
+ Temporary placeholder for AI Super Resolution.
+ Just returns the same file path until AI model is added.
+ """
+ return input_path
+
+# --- (Previous imports and functions are unchanged) ---
+
+import subprocess
+import os
+import uuid
+
+# ... (all previous functions like ai_superres_placeholder, etc.) ...
+
+# ---------- Chroma Key (FFmpeg chromakey filter) ----------
+def chroma_key_video(
+ video_path: str, # Renamed for clarity: fg_path passed from save_upload_file
+ bg_path: Optional[str] = None, # Optional background file path
+ key_color_hex: str = "#00ff00", # Renamed to match FastAPI argument
+ tolerance: int = 100,
+ smoothing: int = 20,
+ target_ext: str = "mp4"
+) -> str:
+ """
+ Applies the FFmpeg chromakey filter to replace a specified color
+ in the foreground video with an optional background image or video.
+ """
+ out = _out_name(target_ext)
+
+ # Convert settings to FFmpeg filter values (0.0 to 1.0)
+ ff_color = "0x" + key_color_hex.replace("#", "")
+ similarity = tolerance / 200 # Normalized from 1-200 to 0.005-1.0
+ blend = smoothing / 200 # Normalized from 1-100 to 0.01-0.5
+
+ if bg_path:
+ # Complex filter graph for foreground + background overlay
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", video_path, # [0] Foreground
+ "-i", bg_path, # [1] Background
+ "-filter_complex",
+ # [0:v] Apply chromakey, output is stream [ck]
+ f"[0:v]chromakey={ff_color}:{similarity}:{blend}[ck];"
+ # [1:v] Take background, overlay [ck] on top of it at (0,0)
+ f"[1:v][ck]overlay=0:0[out]",
+ "-map", "[out]", # Map the final filtered video stream
+ "-map", "0:a:?", # Copy audio stream from foreground if exists
+ "-c:v", "libx264",
+ "-crf", "23",
+ "-pix_fmt", "yuv420p",
+ out
+ ]
+ else:
+ # Simple filter for foreground only (result will have alpha channel or transparency)
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", video_path,
+ "-vf", f"chromakey={ff_color}:{similarity}:{blend}",
+ # Use 'yuva420p' or 'rgba' for alpha channel, but MP4 often struggles with it.
+ # Sticking to libx264 which often forces black background if alpha isn't supported.
+ "-c:v", "libx264",
+ "-crf", "23",
+ "-pix_fmt", "yuv420p",
+ out
+ ]
+
+ # Use _run_cmd instead of raw subprocess.run for consistent logging/error handling
+ _run_cmd(cmd)
+ return out
+import os
+import uuid
+import subprocess
+
+def apply_video_filter(input_path: str, filter_name: str) -> str:
+ output_path = input_path.replace(".mp4", f"_filtered_{uuid.uuid4().hex}.mp4")
+
+ FILTER_MAP = {
+ "grayscale": "format=gray",
+ "sepia": "colorchannelmixer=.393:.769:.189:0:.349:.686:.168:0:.272:.534:.131",
+ "invert": "negate",
+ "warm": "eq=contrast=1.05:saturation=1.3",
+ "cool": "eq=contrast=1.05:saturation=1.3,hue=h=180",
+ "vintage": "curves=vintage",
+ "dramatic": "eq=contrast=1.4:saturation=1.1",
+ "cyber": "eq=saturation=2,hue=180",
+ "none": "null"
+ }
+
+ ff_filter = FILTER_MAP.get(filter_name, "null")
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-i", input_path,
+ "-vf", ff_filter,
+ "-movflags", "+faststart",
+ "-preset", "ultrafast",
+ output_path
+ ]
+
+ subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+
+ return output_path
diff --git a/start.txt b/start.txt
new file mode 100755
index 0000000000000000000000000000000000000000..3b18e512dba79e4c8300dd08aeb37f8e728b8dad
--- /dev/null
+++ b/start.txt
@@ -0,0 +1 @@
+hello world
diff --git a/start2engine.sh b/start2engine.sh
new file mode 100755
index 0000000000000000000000000000000000000000..17a8a1418755fc0330d99517eaf9bd94e30c134a
--- /dev/null
+++ b/start2engine.sh
@@ -0,0 +1,6 @@
+sudo systemctl enable backend
+sudo systemctl start backend
+
+sudo systemctl enable celery
+sudo systemctl start celery
+
diff --git a/static/pdf/text_736d3dd0b4424a6395f153a7a00af9c7.txt b/static/pdf/text_736d3dd0b4424a6395f153a7a00af9c7.txt
new file mode 100644
index 0000000000000000000000000000000000000000..6931a66e1cd4588c2d4402419607670f12c19868
--- /dev/null
+++ b/static/pdf/text_736d3dd0b4424a6395f153a7a00af9c7.txt
@@ -0,0 +1,173 @@
+INTERNSHIP REPORT
+
+A report submitted in partial fulfillment of the requirements for the Award of
+Degree of
+
+BACHELOR OF ARTS
+in
+COMPUTER ANIMATION
+by
+SANTYA SADIK
+RegNo: 2214303
+
+Under Supervision of
+Mr. Abdulla Kunhi
+CEO
+IOD Kasaragod
+(Duration: 1% June to 30™ June, 2024)
+
+ESTD : 1880
+
+DEPARTMENT OF COMPUTER ANIMATION,
+ST ALOYSIUS COLLEGE, (AUTONOMOUS)
+MANGALURU 575 003
+
+
+DEPARTMENT OF COMPUTER ANIMATION, ST ALOYSIUS COLLEGE,
+(AUTONOMOUS) MANGALURU 575 003
+
+WU
+
+WY
+
+TTT
+
+1}
+
+ESTD : 1880
+
+CERTIFICATE
+
+This is to certify that the “Internship report” submitted by Saniya Sadik (RegNo:
+2214303)is work done by her and submitted during 2023-2024 academic year, in
+partial fulfillment of the requirements for the award of the degree of BACHELOR
+
+OF ARTS in COMPUTERANIMATION, at Institute of Digital Skills(IOD),
+
+Kasaragod.
+
+College Internship Coordinator
+
+Dr. Rejig John
+Assistant Professor
+Department of Economics
+
+Department Internship Coordinator
+Mr. Santhosh Notagar
+
+Assistant Professor
+Dept of Computer Animation
+
+Mr. Santhosh Notagar
+Assistant Professor & Head of the
+
+Department
+Computer Animation
+
+
+CONTENT
+
+1. Internship Certificate
+
+2. Acknowledgement
+
+3. Weekly Report
+
+4. Observation and experience
+
+
+institute Of Digital Skills
+
+Institute Of Digital Skills 15-07-2024
+Square Nine Mall, New Bus Stand Monday
+Kasaragod, Kerala - 671121
+
+8606 411 729
+
+This is to certify that Ms. Saniya Sadik (2214303), student of St Aloysius Collage,
+Manglore has undergone Training in our Organization from 01-6-2024 to 30-06-2024.
+
+She has acquinted herself with all the departments and succesfully completed her training.
+During the period of her internship program, she was regular in attendance and has taken
+
+keen interest in the work assigned to her from time to time.
+
+We also found that her conduct and behavior are fine.
+We wish her all the success and a better future.
+
+ABDULLA KUNHI
+CEO
+INSTITUTE OF DIGITAL SKILLS
+
+F DIG LS
+‘NSTITUTE OF DIGITAL SKIL
+Regd: UDYAM-KL-05-0016667
+
+
+
+ACKNOWLEDGEMENT
+
+First I would like to thank Mr. Abdulla kunhi, CEO of IOD for giving me the opportunity to do
+an internship within the organization.
+
+I also would like to thank all the people that worked along with, including Mr. Shakir, my
+internship mentor, Ms. Faiza, Ms. Farzana, Mr. Thufail, Ms. Hajira, Ms. Muna, Ms.
+Ramseena, Ms. Muhsina and others, whose patience and openness created an enjoyable
+working environment.
+
+| would lastly like to thank my fellow-intern Mr. Abdulla kunhi kottakunnnil, for their camaraderie and
+support during our month-long stint at the organization.
+
+
+WEEKLY OVERVIEW OF INTERNSHIP ACTIVITIES
+
+4 | Date Day Name of the work
+
+a 03-06-2024 | Monday Introduction with the team.
+
+= | 04-06-2024 | Tuesday Created my CV using photoshop.
+
+%, | 05-06-2024 | Wednesday | Did basics training in Adobe premiere pro.
+06-06-2024 | Thursday _| Edited a video for the organization.
+07-06-2024 | Friday Continued with the editing work.
+Date Day Name of the work
+10-06-2024 | Monday Brainstorming new ideas for videos.
+
+- 11-06-2024 | Tuesda Assisted with shooting videos.
+
+& A 12-06-2024 | Wednesday | Editing videos in premiere pro.
+13-06-2024 | Thursday | Editing videos in premiere pro
+14-06-2024 | Friday Assisted with shooting videos.
+
+
+
+Date Day Name of the work
+17-06-2024 Monday Basics training in Adobe Illustrator.
+~ 18-06-2024 Tuesday Created a poster using photoshop.
+& = 19-06-2024 | Wednesday | Green screen video editing.
+20-06-2024 Thursday __| Green screen video editing.
+21-06-2024 Friday Green screen video editing.
+y Date Day Name of the work
+fq | 24-06-2024 | Monday Poster designing in photoshop.
+> 25-06-2024 | Tuesday Assisted with video shooting.
+= 26-06-2024 | Wednesday | Convocation ceremony at the organization.
++ [27-06-2024 Thursday __| Video editing with premiere pro.
+28-06-2024 | Friday Video editing with premiere pro.
+
+
+
+Observation and Experience
+
+During my internship, I gained a wealth of knowledge and experience that
+significantly shaped my professional outlook. I worked with Photoshop, Premiere
+Pro, and Illustrator, which honed my skills in graphic design and video editing.
+
+Observing the organization’s operations allowed me to understand the dynamics of
+a real-world work environment, including the importance of teamwork and effective
+communication. I learned about professional ethics and how they guide decision-
+making and behavior in the workplace.
+
+Additionally, the opportunity to interact with colleagues and fellow interns helped
+me forge new friendships and build a network of contacts. Overall, the experience
+was enriching, providing me with practical skills and insights that I will carry
+forward in my career.
diff --git a/static/pdf/text_a7c4f3fc68c64da4be4dfaa6b895702f.txt b/static/pdf/text_a7c4f3fc68c64da4be4dfaa6b895702f.txt
new file mode 100644
index 0000000000000000000000000000000000000000..85bcd8ee37d2c423f12fccde546804fd1883007f
--- /dev/null
+++ b/static/pdf/text_a7c4f3fc68c64da4be4dfaa6b895702f.txt
@@ -0,0 +1,261 @@
+~~
+
+Sonustes ol
+
+: ha att pst ey a rate inehrdt tal
+
+Fottio
+
+
+
+
+
+Viminate : EO a
+
+:
+
+le , lmuenhnt na (}) A3* 51 * SER eee
+(eye =o x =\@ \ Bo a3 Vath
+
+p= a SpOSOe Ri, sb pe
+
+
+
+Dons
+
+4
+2 [potentiating He : ye
+(
+8 \
+Paice aie tbae u |
+iat, LSE yes,
+
+hasta) D-E Uey Aiminat; q the axbituasiy Constants
+
+PT) ZL= Ax +5 an 2
+
+( r
+Zt =70 4+ a+ be —(D
+reemttatma (4) UG: X
+00 j=
+OZ — a =p = fi L
+) Ox ae
+aif even tating ff) weds q a
+00 a ;
+72) —— ee)
+
+2. é 2 @ =
+ST) es (A | Y
+P. bs . aly: ma 3 4 tua CONnsStan a and b
+- elim 6 oy i AGL UN) 6. ELAG Oh at AO Ss A re 4 A
+
+
+
+DOM
+
+- Oz =(a+a)\C1+0) > | xta=4
+
+
+
+DOHT | page No.
+
+ff) * (a4
+iL enentra and I) W'S
+
+J ae WH der sls
+
+On z : é : iret : i!
+
+
+
+SONS
+
+‘floHentiatin g (4) A? S1* A
+UD x = { U eS 2 2 : 3 >
+4 x
+OY @
+Vaoar lett bfo/52 24 72 : q
+
+y, — AA LZ Q
+
+
+Eliminat: the axbityaun Junction ds1om Dx + my + nz
+
+2
+
+-
+>
+
+bY
+
+Qj
+aE)
+
+(D
+
+6
+
+b 22 entrat'n O
+
+pot
+
+2
+
+"Guanwon kA + Mey Nx = ©
+
++ ing
+
+A) Fs a hl H
+
+1 Sars
+g + ne OF -=- fh (x + U2
+
+OX
+24 y2%+x*) 2
+
+Saya = canis y
+
+OX
+
+20H
+
+a 24 4? =)
+
+
+
+~~
+
+Minar a Ne Nn Hoo () Horn nn D LOG
+Cj x ¢
+Q
+% = ox 2 We =(D
+XL
+; t { 4
+‘el nye nnanthg (DD wet. 9: Of 2D fer i ilog - cepa /—!
+
+Gg :
+
+UJ
+gn (Q) Uy exome “on _(%) cy) ae
+
+n= _ Ae =) - a ae
+nH 2
+% a 3
+SSP ee
+
+
+
+B (Rgx4+Aax
+
+di! pH einita tin 4 Wsstyss ( ee “A
+
+V0 ti. 9g oN a Gn QOL
+
+
+
+
+
+Dons
+
+a Ca YP me oes 27 yea —
+
+fRedeniiatyng wv -ot-4 - H
+ye + Ge a 49:0 ite 42)
+
+(eae ae ap Cua, +2) = Ela) 4 —
+
+Qe
+
+
+
+? =
+\
+
+{t 2+ (rt4) bo & oGuty) per 3
+aiaes yy xy rac UZ bgxq
+FS oo wa yee Pea bls base bagel or
+
+past +@ +Q eee oy ean
+
+_—
+
+r qu av pu
+(
+
+ma.
+{
+
+21 ~ YZa- FUG
+
+
+
+DOHs
+
+i )
+
+(
+"
+
+=
+D>
+>
+
+be Emotion : -D- cbhy elimination of anbifasu xunction 7)
+(
+
+a aie, fi UWI winelocoel 4 ge daakee b
+
+( . .
+
+ang : Ay Ko i deb end t 64) 0 oY C 4°
+
+a ind MN, end DNNOLHLS . 43 : .
+
+6aGeake (D
+
+(0 _ aan : |
+__Bd- Qu 4 96 - du DK + Od - Ov -Ov. Dz =
+aD QW .of O*%. > Oy O% , OBVLOLD Ox
+
+d Ou a . . 4 O° ; U ’ 4, = 0
+u Ox Ox @VvV \ OL OL
+
+C1
+
+Od NT u. = -*?D9 b: ON
+ul Oa Or Ov \ OX Oz
+
+S
+.
+
+
+
+I —
+CaaRE pv OU = bdy. Ou + o ON OU =.a Ott. Dy = -Ov.Qu —py. au
+
+
+
+Dons
+
+fg
+
+Ox
+Jhen
+
+p= QU -Dv -—Dv . Dy = 1: Ma -
+OF OX Oz Ox
+
+(x24 : 74 Q4Hx)=0
+
+U2 L' + Quz Vru‘¢ Qz
+
+4 = ow k= rn c Ov = az Ov = ay ov =
+
+Dx dy ax ¢ Ox ay Ox
+P= Bu oy — Ow. Dy = a%- Ao —laqp ay) = az - URYT
+
+Sie lo Pi _ Qu = (Qyu-Q7%)~C AA's = UY A — UX
+
diff --git a/status.sh b/status.sh
new file mode 100755
index 0000000000000000000000000000000000000000..a384d076063cb1dfe3e6af61821f756f907fffa2
--- /dev/null
+++ b/status.sh
@@ -0,0 +1,2 @@
+sudo systemctl status backend
+sudo systemctl status celery
diff --git a/table.txt b/table.txt
new file mode 100755
index 0000000000000000000000000000000000000000..b5713927e33d63774e23f1d08dd4174ee8184856
--- /dev/null
+++ b/table.txt
@@ -0,0 +1,100 @@
+from core.database import Base, engine
+import models # this imports all model classes
+
+Base.metadata.create_all(bind=engine)
+from core.database import Base, engine
+import models
+Base.metadata.create_all(bind=engine)
+print("Tables created!")
+sudo -u postgres psql
+CREATE USER gpr3 WITH PASSWORD 'yourpassword';
+CREATE DATABASE gpr3db OWNER gpr3;
+GRANT ALL PRIVILEGES ON DATABASE gpr3db TO gpr3;
+from core.database import Base, engine
+import models
+
+Base.metadata.create_all(bind=engine)
+from core.database import Base, engine
+from models.tool_stat import ToolStat
+from models.tool_event import ToolEvent
+
+Base.metadata.create_all(bind=engine)
+from models.tool_stat import ToolStat
+from models.tool_event import ToolEvent
+
+Base.metadata.create_all(bind=engine)
+from core.database import Base, engine
+from core.database import Base, engine
+import models.tool_event
+import models.tool_stat
+
+Base.metadata.create_all(bind=engine)
+-- Add columns to ad_units
+ALTER TABLE ad_units
+ ADD COLUMN IF NOT EXISTS ad_type VARCHAR,
+ ADD COLUMN IF NOT EXISTS preset_size VARCHAR,
+ ADD COLUMN IF NOT EXISTS custom_width INTEGER,
+ ADD COLUMN IF NOT EXISTS custom_height INTEGER,
+ ADD COLUMN IF NOT EXISTS file_path TEXT,
+ ADD COLUMN IF NOT EXISTS vast_url TEXT,
+ ADD COLUMN IF NOT EXISTS html_code TEXT,
+ ADD COLUMN IF NOT EXISTS click_url TEXT,
+ ADD COLUMN IF NOT EXISTS duration_seconds INTEGER,
+ ADD COLUMN IF NOT EXISTS skippable_after INTEGER,
+ ADD COLUMN IF NOT EXISTS target_devices TEXT,
+ ADD COLUMN IF NOT EXISTS target_categories TEXT,
+ ADD COLUMN IF NOT EXISTS target_countries TEXT,
+ ADD COLUMN IF NOT EXISTS frequency_cap_count INTEGER DEFAULT 0,
+ ADD COLUMN IF NOT EXISTS frequency_cap_window_hours INTEGER,
+ ADD COLUMN IF NOT EXISTS frequency_cap_type VARCHAR DEFAULT 'none',
+ ADD COLUMN IF NOT EXISTS priority INTEGER DEFAULT 5,
+ ADD COLUMN IF NOT EXISTS enabled BOOLEAN DEFAULT true;
+
+-- Add ad_impressions table
+CREATE TABLE IF NOT EXISTS ad_impressions (
+ id SERIAL PRIMARY KEY,
+ ad_unit_id INTEGER NOT NULL REFERENCES ad_units(id),
+ client_id TEXT,
+ placement TEXT,
+ timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);
+
+-- Add fields to ad_placements if missing
+ALTER TABLE ad_placements
+ ADD COLUMN IF NOT EXISTS ad_unit_id INTEGER,
+ ADD COLUMN IF NOT EXISTS placement VARCHAR,
+ ADD COLUMN IF NOT EXISTS priority INTEGER DEFAULT 0,
+ ADD COLUMN IF NOT EXISTS enabled BOOLEAN DEFAULT true,
+ ADD COLUMN IF NOT EXISTS custom_width INTEGER,
+ ADD COLUMN IF NOT EXISTS custom_height INTEGER;
+ALTER TABLE ad_units
+ ADD COLUMN IF NOT EXISTS ad_type VARCHAR,
+ ADD COLUMN IF NOT EXISTS preset_size VARCHAR,
+ ADD COLUMN IF NOT EXISTS custom_width INTEGER,
+ ADD COLUMN IF NOT EXISTS custom_height INTEGER,
+ ADD COLUMN IF NOT EXISTS file_path TEXT,
+ ADD COLUMN IF NOT EXISTS vast_url TEXT,
+ ADD COLUMN IF NOT EXISTS html_code TEXT,
+ ADD COLUMN IF NOT EXISTS click_url TEXT,
+ ADD COLUMN IF NOT EXISTS duration_seconds INTEGER,
+ ADD COLUMN IF NOT EXISTS skippable_after INTEGER,
+ ADD COLUMN IF NOT EXISTS target_devices TEXT,
+ ADD COLUMN IF NOT EXISTS target_categories TEXT,
+ ADD COLUMN IF NOT EXISTS target_countries TEXT,
+ ADD COLUMN IF NOT EXISTS frequency_cap_count INTEGER DEFAULT 0,
+ ADD COLUMN IF NOT EXISTS frequency_cap_window_hours INTEGER,
+ ADD COLUMN IF NOT EXISTS frequency_cap_type VARCHAR DEFAULT 'none',
+ ADD COLUMN IF NOT EXISTS priority INTEGER DEFAULT 5,
+ ADD COLUMN IF NOT EXISTS enabled BOOLEAN DEFAULT true;
+ALTER TABLE ad_placements
+ ADD COLUMN IF NOT EXISTS ad_unit_id INTEGER,
+ ADD COLUMN IF NOT EXISTS placement VARCHAR,
+ ADD COLUMN IF NOT EXISTS priority INTEGER DEFAULT 0,
+ ADD COLUMN IF NOT EXISTS enabled BOOLEAN DEFAULT true,
+ ADD COLUMN IF NOT EXISTS custom_width INTEGER,
+ ADD COLUMN IF NOT EXISTS custom_height INTEGER;
+ALTER TABLE usage_stats ADD COLUMN open_count INT DEFAULT 0;
+ALTER TABLE usage_stats ADD COLUMN process_count INT DEFAULT 0;
+ALTER TABLE usage_stats ADD COLUMN download_count INT DEFAULT 0;
+ALTER TABLE ad_units ADD COLUMN file_type VARCHAR;
+
diff --git a/tests/test_stats.py b/tests/test_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..d51592abf397cec629cf884a719c8bb2ad6f0b8e
--- /dev/null
+++ b/tests/test_stats.py
@@ -0,0 +1,73 @@
+import pytest
+from core.models import ToolUsage
+from sqlalchemy.orm import Session
+# You will need to import the admin token generator or manually get an admin token
+# from your admin_auth.py router for the authenticated request.
+
+def test_tool_usage_logging_and_retrieval(client, db: Session):
+ # 1. SETUP: Find initial usage count for a specific tool
+ TEST_TOOL = "pdf_merge"
+
+ # Check current count in the database
+ initial_count = db.query(ToolUsage).filter(
+ ToolUsage.tool_name == TEST_TOOL
+ ).count()
+
+ # 2. ACTION: Simulate a successful request to the tool endpoint
+ # NOTE: The client needs to send form-data or files as required by the endpoint.
+ # We use a POST request that triggers the LogToolUsage dependency.
+
+ # Since /pdf/merge takes files, we simulate the file upload:
+ # (This is a simplified example, actual FastAPI testing requires a BytesIO object)
+
+ # --- Actual Code Execution (Simulated Tool Call) ---
+ response = client.post(
+ "/pdf/merge",
+ files=[
+ ("files", ("file1.pdf", b"pdf_content_1", "application/pdf")),
+ ("files", ("file2.pdf", b"pdf_content_2", "application/pdf")),
+ ],
+ # Add necessary headers, like the admin token, if the endpoint was protected
+ # but here we test the logging on the public endpoint first.
+ )
+
+ # Check that the tool execution was successful (e.g., returns a file)
+ assert response.status_code == 200
+
+ # 3. VERIFY LOGGING: Check the database directly
+
+ # Check the count again after the request
+ new_count = db.query(ToolUsage).filter(
+ ToolUsage.tool_name == TEST_TOOL
+ ).count()
+
+ # The count should have increased by exactly 1
+ assert new_count == initial_count + 1
+
+ # 4. VERIFY RETRIEVAL (The new stats router)
+ # ⚠️ For this step, you must get an admin token first
+
+ # Simulate admin login to get a token
+ auth_response = client.post("/admin/login", data={"password": "YOUR_ADMIN_SECRET"})
+ admin_token = auth_response.json().get("token")
+
+ # Request the statistics endpoint (which requires the admin token)
+ stats_response = client.get(
+ "/admin/stats/tool_usage",
+ headers={"Authorization": f"Bearer {admin_token}"}
+ )
+
+ # Check that the stats endpoint is accessible and returns data
+ assert stats_response.status_code == 200
+ stats_data = stats_response.json().get("data", [])
+
+ # 5. FINAL VERIFICATION: Check the stats data for the updated count
+
+ # Find the statistics for our test tool
+ tool_stat = next((item for item in stats_data if item["tool_name"] == TEST_TOOL), None)
+
+ # Check that the tool exists in the returned stats and the count matches the database
+ assert tool_stat is not None
+ assert tool_stat["count"] == new_count
+
+ print(f"Test Passed: {TEST_TOOL} count increased from {initial_count} to {new_count}")
diff --git a/tostart.sh b/tostart.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3f8323a1e4b9194a702ccfb83e5eb0cfcf3af442
--- /dev/null
+++ b/tostart.sh
@@ -0,0 +1,2 @@
+./venv/bin/python -m uvicorn main:app --reload
+
diff --git a/udo apt install -y ffmpeg b/udo apt install -y ffmpeg
new file mode 100644
index 0000000000000000000000000000000000000000..d6d3a3209ce6da1effab04e403e13068f48c3ecc
--- /dev/null
+++ b/udo apt install -y ffmpeg
@@ -0,0 +1,22 @@
+[0;1;32m●[0m backend.service - Backend API
+ Loaded: loaded (]8;;file://CloudAiRambo/etc/systemd/system/backend.service/etc/systemd/system/backend.service]8;;; [0;1;32menabled[0m; preset: [0;1;32menabled[0m)
+ Active: [0;1;32mactive (running)[0m since Fri 2025-12-26 11:31:29 UTC; 1h 39min ago
+TriggeredBy: [0;1;32m●[0m backend.socket
+ Main PID: 65355 (gunicorn)
+ Tasks: 12 (limit: 4537)
+ Memory: 2.4G (peak: 2.9G)
+ CPU: 21.184s
+ CGroup: /system.slice/backend.service
+ ├─[0;38;5;245m65355 /root/backend_copy/venv/bin/python3.10 /root/backend_copy/venv/bin/gunicorn main:app --worker-class uvicorn.workers.UvicornWorker -w 1 -b 0.0.0.0:8000[0m
+ └─[0;38;5;245m65358 /root/backend_copy/venv/bin/python3.10 /root/backend_copy/venv/bin/gunicorn main:app --worker-class uvicorn.workers.UvicornWorker -w 1 -b 0.0.0.0:8000[0m
+
+Dec 26 11:31:29 CloudAiRambo systemd[1]: Started backend.service - Backend API.
+Dec 26 11:31:30 CloudAiRambo gunicorn[65355]: [2025-12-26 11:31:30 +0000] [65355] [INFO] Starting gunicorn 23.0.0
+Dec 26 11:31:30 CloudAiRambo gunicorn[65355]: [2025-12-26 11:31:30 +0000] [65355] [INFO] Listening at: http://0.0.0.0:8000 (65355)
+Dec 26 11:31:30 CloudAiRambo gunicorn[65355]: [2025-12-26 11:31:30 +0000] [65355] [INFO] Using worker: uvicorn.workers.UvicornWorker
+Dec 26 11:31:30 CloudAiRambo gunicorn[65358]: [2025-12-26 11:31:30 +0000] [65358] [INFO] Booting worker with pid: 65358
+Dec 26 11:31:36 CloudAiRambo gunicorn[65358]: /root/backend_copy/venv/lib/python3.10/site-packages/pydub/utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
+Dec 26 11:31:36 CloudAiRambo gunicorn[65358]: warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
+Dec 26 11:31:38 CloudAiRambo gunicorn[65358]: [2025-12-26 11:31:38 +0000] [65358] [INFO] Started server process [65358]
+Dec 26 11:31:38 CloudAiRambo gunicorn[65358]: [2025-12-26 11:31:38 +0000] [65358] [INFO] Waiting for application startup.
+Dec 26 11:31:38 CloudAiRambo gunicorn[65358]: [2025-12-26 11:31:38 +0000] [65358] [INFO] Application startup complete.
diff --git a/utils/! b/utils/!
new file mode 100644
index 0000000000000000000000000000000000000000..4b2abecfce5ffe3f76811f4b637c3a97e5c2a7fd
--- /dev/null
+++ b/utils/!
@@ -0,0 +1,9 @@
+from fastapi.responses import FileResponse
+
+def send_file(path: str):
+ return FileResponse(
+ path,
+ filename=path.split("/")[-1],
+ media_type="application/octet-stream"
+ )
+
diff --git a/utils/__pycache__/archive_utils.cpython-312.pyc b/utils/__pycache__/archive_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ea2cd7ed0bf2bc35c1e24639699d5e14aadcbe8
Binary files /dev/null and b/utils/__pycache__/archive_utils.cpython-312.pyc differ
diff --git a/utils/__pycache__/archive_utils.cpython-39.pyc b/utils/__pycache__/archive_utils.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..62ac5494c2207d43ee23ed64949bca545e406bdf
Binary files /dev/null and b/utils/__pycache__/archive_utils.cpython-39.pyc differ
diff --git a/utils/__pycache__/ffmpeg_utils.cpython-312.pyc b/utils/__pycache__/ffmpeg_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..90f02c6569352bfad014da490a39b7af7ed2153c
Binary files /dev/null and b/utils/__pycache__/ffmpeg_utils.cpython-312.pyc differ
diff --git a/utils/__pycache__/ffmpeg_utils.cpython-39.pyc b/utils/__pycache__/ffmpeg_utils.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f32fcc94e2b500da7ef6b73bdcc95dd819a77d3
Binary files /dev/null and b/utils/__pycache__/ffmpeg_utils.cpython-39.pyc differ
diff --git a/utils/__pycache__/file_utils.cpython-312.pyc b/utils/__pycache__/file_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..31f1df5515e8b696156b36a8ca0a535bf407b35c
Binary files /dev/null and b/utils/__pycache__/file_utils.cpython-312.pyc differ
diff --git a/utils/__pycache__/file_utils.cpython-39.pyc b/utils/__pycache__/file_utils.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..097756f70ad58ef9f818074d66b4975efe5f90b3
Binary files /dev/null and b/utils/__pycache__/file_utils.cpython-39.pyc differ
diff --git a/utils/__pycache__/format_registry.cpython-312.pyc b/utils/__pycache__/format_registry.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..75d94cf2ca075b8101d61ede053cff0c07a0f8a9
Binary files /dev/null and b/utils/__pycache__/format_registry.cpython-312.pyc differ
diff --git a/utils/__pycache__/ghostscript_utils.cpython-312.pyc b/utils/__pycache__/ghostscript_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1c5baac28046252c96775b1d23ba9626e958f604
Binary files /dev/null and b/utils/__pycache__/ghostscript_utils.cpython-312.pyc differ
diff --git a/utils/__pycache__/ghostscript_utils.cpython-39.pyc b/utils/__pycache__/ghostscript_utils.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c588b302a9658cb5526c9da05f5184536a4576ce
Binary files /dev/null and b/utils/__pycache__/ghostscript_utils.cpython-39.pyc differ
diff --git a/utils/__pycache__/imagemagic_utils.cpython-312.pyc b/utils/__pycache__/imagemagic_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fef09c088d33d45c3ef8eb280c2db5bbecf9f327
Binary files /dev/null and b/utils/__pycache__/imagemagic_utils.cpython-312.pyc differ
diff --git a/utils/__pycache__/imagemagic_utils.cpython-39.pyc b/utils/__pycache__/imagemagic_utils.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0988fed6fd22e6a09b2bb2dd16512150a5012837
Binary files /dev/null and b/utils/__pycache__/imagemagic_utils.cpython-39.pyc differ
diff --git a/utils/__pycache__/pandoc_utils.cpython-312.pyc b/utils/__pycache__/pandoc_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a7d1dd31327ae09dab0a3775e5246bda1d2f658
Binary files /dev/null and b/utils/__pycache__/pandoc_utils.cpython-312.pyc differ
diff --git a/utils/__pycache__/pandoc_utils.cpython-39.pyc b/utils/__pycache__/pandoc_utils.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4e60ceb126f5ead36d4032702355f3e3d11ed1c2
Binary files /dev/null and b/utils/__pycache__/pandoc_utils.cpython-39.pyc differ
diff --git a/utils/__pycache__/response_utils.cpython-312.pyc b/utils/__pycache__/response_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..17bda31abfa8624d1b31f6ec9fd4f1ff7d011dad
Binary files /dev/null and b/utils/__pycache__/response_utils.cpython-312.pyc differ
diff --git a/utils/__pycache__/response_utils.cpython-39.pyc b/utils/__pycache__/response_utils.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6b43afbaf865de88ec93e6c3461bf83155a93d93
Binary files /dev/null and b/utils/__pycache__/response_utils.cpython-39.pyc differ
diff --git a/utils/__pycache__/validate_utils.cpython-312.pyc b/utils/__pycache__/validate_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e6c97b613732056a7e3822be7d831dd0c433bc07
Binary files /dev/null and b/utils/__pycache__/validate_utils.cpython-312.pyc differ
diff --git a/utils/__pycache__/validate_utils.cpython-39.pyc b/utils/__pycache__/validate_utils.cpython-39.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f889cfc4b05e7fff4900fd08ba3c74f0bfd99f5
Binary files /dev/null and b/utils/__pycache__/validate_utils.cpython-39.pyc differ
diff --git a/utils/archive_utils.py b/utils/archive_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a72f0e73175c9bdde170d463f663310e0f5ed8c6
--- /dev/null
+++ b/utils/archive_utils.py
@@ -0,0 +1,23 @@
+import subprocess
+import os
+import uuid
+import shutil
+from core.config import settings
+
+def extract_archive(input_path: str):
+ extract_dir = os.path.join(settings.TEMP_DIR, f"extract_{uuid.uuid4()}")
+ os.makedirs(extract_dir, exist_ok=True)
+
+ cmd = ["7z", "x", input_path, f"-o{extract_dir}", "-y"]
+ subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+
+ return extract_dir
+
+def rezip_folder(folder_path: str, target_ext: str):
+ output_name = f"{uuid.uuid4()}.{target_ext}"
+ output_path = os.path.join(settings.OUTPUT_DIR, output_name)
+
+ cmd = ["7z", "a", output_path, folder_path]
+ subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ return output_path
+
diff --git a/utils/auth_utils.py b/utils/auth_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec6dc61ee278dae236784c000f51fe4e6b520afa
--- /dev/null
+++ b/utils/auth_utils.py
@@ -0,0 +1,9 @@
+# utils/auth_utils.py
+from passlib.hash import bcrypt
+
+def hash_password(password: str) -> str:
+ return bcrypt.hash(password)
+
+def verify_password(password: str, password_hash: str) -> bool:
+ return bcrypt.verify(password, password_hash)
+
diff --git a/utils/ffmpeg_utils.py b/utils/ffmpeg_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a752789fdec2edbe91ac385d84f763bfcd6d346
--- /dev/null
+++ b/utils/ffmpeg_utils.py
@@ -0,0 +1,19 @@
+import subprocess
+import uuid
+import os
+from core.config import settings
+
+def run_ffmpeg(input_path: str, output_ext: str):
+ output_filename = f"{uuid.uuid4()}.{output_ext}"
+ output_path = os.path.join(settings.OUTPUT_DIR, output_filename)
+
+ cmd = [
+ "ffmpeg",
+ "-y",
+ "-i", input_path,
+ output_path
+ ]
+
+ subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ return output_path
+
diff --git a/utils/file_utils.py b/utils/file_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..56cdaacb9bdfdd3fffa267daa50f4611201e4065
--- /dev/null
+++ b/utils/file_utils.py
@@ -0,0 +1,37 @@
+import os
+import uuid
+from core.config import settings
+
+# -------------------------------------------------
+# LOW-LEVEL BYTE SAVER (NEW, CORRECT)
+# -------------------------------------------------
+def save_bytes_to_file(data: bytes, original_name: str):
+ os.makedirs(settings.TEMP_DIR, exist_ok=True)
+
+ filename = f"{uuid.uuid4().hex}_{original_name}"
+ path = os.path.join(settings.TEMP_DIR, filename)
+
+ with open(path, "wb") as f:
+ f.write(data)
+
+ if os.path.getsize(path) == 0:
+ raise RuntimeError("Saved file is empty")
+
+ return path
+
+
+# -------------------------------------------------
+# BACKWARD-COMPAT WRAPPER (IMPORTANT)
+# -------------------------------------------------
+def save_upload_file(file):
+ """
+ Compatibility wrapper for existing routers.
+ DO NOT remove — many routers depend on this.
+ """
+ data = file.file.read()
+
+ if not data:
+ raise RuntimeError("Uploaded file stream is empty")
+
+ return save_bytes_to_file(data, file.filename)
+
diff --git a/utils/format_registry.py b/utils/format_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..48dd2bd6cd149dfaf68f3b1752d5af05dd11dac8
--- /dev/null
+++ b/utils/format_registry.py
@@ -0,0 +1,208 @@
+import subprocess
+import shutil
+from functools import lru_cache
+
+
+# -------------------------------------------------
+# ImageMagick
+# -------------------------------------------------
+@lru_cache()
+def imagemagick_formats():
+ magick = shutil.which("magick") or shutil.which("convert")
+ if not magick:
+ return set()
+
+ out = subprocess.check_output(
+ [magick, "-list", "format"],
+ stderr=subprocess.DEVNULL
+ ).decode(errors="ignore")
+
+ fmts = set()
+ for line in out.splitlines():
+ parts = line.split()
+ if parts and parts[0].isalpha():
+ fmts.add(parts[0].lower())
+ return fmts
+
+
+# -------------------------------------------------
+# FFmpeg
+# -------------------------------------------------
+@lru_cache()
+def ffmpeg_formats():
+ if not shutil.which("ffmpeg"):
+ return set()
+
+ out = subprocess.check_output(
+ ["ffmpeg", "-formats"],
+ stderr=subprocess.STDOUT
+ ).decode(errors="ignore")
+
+ fmts = set()
+ for line in out.splitlines():
+ if line.startswith(" D") or line.startswith(" E"):
+ fmts.update(line.split()[1].split(","))
+ return fmts
+
+
+# -------------------------------------------------
+# Pandoc
+# -------------------------------------------------
+@lru_cache()
+def pandoc_formats():
+ if not shutil.which("pandoc"):
+ return set()
+
+ out = subprocess.check_output(
+ ["pandoc", "--list-output-formats"]
+ ).decode(errors="ignore")
+
+ return set(out.split())
+
+
+# -------------------------------------------------
+# LibreOffice
+# -------------------------------------------------
+@lru_cache()
+def libreoffice_formats():
+ if not (shutil.which("soffice") or shutil.which("libreoffice")):
+ return set()
+
+ return {
+ "doc", "docx", "ppt", "pptx",
+ "xls", "xlsx", "odt", "ods", "odp",
+ "rtf", "pdf", "txt"
+ }
+
+
+# -------------------------------------------------
+# Calibre (Ebooks)
+# -------------------------------------------------
+@lru_cache()
+def ebook_formats():
+ if not shutil.which("ebook-convert"):
+ return set()
+
+ return {"epub", "mobi", "azw3", "fb2", "lit", "pdf"}
+
+
+# -------------------------------------------------
+# Archives
+# -------------------------------------------------
+@lru_cache()
+def archive_formats():
+ return {"zip", "7z", "rar", "tar", "gz", "bz2", "xz"}
+
+
+# -------------------------------------------------
+# GDAL / OGR (GIS)
+# -------------------------------------------------
+@lru_cache()
+def gdal_formats():
+ if not shutil.which("ogr2ogr"):
+ return set()
+
+ out = subprocess.check_output(
+ ["ogrinfo", "--formats"],
+ stderr=subprocess.DEVNULL
+ ).decode(errors="ignore")
+
+ fmts = set()
+ for line in out.splitlines():
+ if "-" in line:
+ name = line.split("-")[0].strip().lower()
+ fmts.add(name)
+ return fmts
+
+
+# -------------------------------------------------
+# OpenBabel (Scientific / Chemistry)
+# -------------------------------------------------
+@lru_cache()
+def openbabel_formats():
+ if not shutil.which("obabel"):
+ return set()
+
+ out = subprocess.check_output(
+ ["obabel", "-L", "formats"],
+ stderr=subprocess.DEVNULL
+ ).decode(errors="ignore")
+
+ fmts = set()
+ for line in out.splitlines():
+ if "." in line:
+ ext = line.split(".")[1].split()[0].lower()
+ fmts.add(ext)
+ return fmts
+
+
+# -------------------------------------------------
+# Poppler (Advanced PDF targets)
+# -------------------------------------------------
+@lru_cache()
+def poppler_formats():
+ if not shutil.which("pdftocairo"):
+ return set()
+
+ return {"svg", "html", "ps", "ppm"}
+
+
+# -------------------------------------------------
+# Whisper (AI transcription targets)
+# -------------------------------------------------
+@lru_cache()
+def whisper_formats():
+ if not shutil.which("whisper"):
+ return set()
+
+ return {"txt", "srt", "vtt"}
+
+
+# -------------------------------------------------
+# MASTER REGISTRY
+# -------------------------------------------------
+def all_formats():
+ return {
+ "images": imagemagick_formats(),
+ "audio_video": ffmpeg_formats(),
+ "documents": pandoc_formats(),
+ "office": libreoffice_formats(),
+ "ebooks": ebook_formats(),
+ "archives": archive_formats(),
+ "gis": gdal_formats(),
+ "scientific": openbabel_formats(),
+ "advanced_pdf": poppler_formats(),
+ "speech_to_text": whisper_formats(),
+ }
+
+@lru_cache()
+def djvu_formats():
+ if not shutil.which("ddjvu"):
+ return set()
+ return {"djvu"}
+@lru_cache()
+def graphicsmagick_formats():
+ if not shutil.which("gm"):
+ return set()
+ return {
+ "bmp", "gif", "jpg", "jpeg", "png", "tiff",
+ "webp", "pnm", "ppm", "ico", "psd"
+ }
+@lru_cache()
+def mupdf_formats():
+ if not shutil.which("mutool"):
+ return set()
+ return {"xps", "cbz", "svg"}
+
+# -------------------------------------------------
+# CLI TEST
+# -------------------------------------------------
+if __name__ == "__main__":
+ f = all_formats()
+
+ for k, v in f.items():
+ print(f"{k}: {len(v)}")
+
+ total = set.union(*[set(v) for v in f.values() if v])
+ print("TOTAL DISTINCT FORMATS:", len(total))
+
diff --git a/utils/ghostscript_utils.py b/utils/ghostscript_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..879dd92e4512fb793d1e204eb0999a4bb593e44d
--- /dev/null
+++ b/utils/ghostscript_utils.py
@@ -0,0 +1,24 @@
+import subprocess
+import os
+import uuid
+from core.config import settings
+
+def compress_pdf(input_path: str):
+ output_filename = f"{uuid.uuid4()}.pdf"
+ output_path = os.path.join(settings.OUTPUT_DIR, output_filename)
+
+ cmd = [
+ "gs",
+ "-sDEVICE=pdfwrite",
+ "-dCompatibilityLevel=1.5",
+ "-dPDFSETTINGS=/ebook",
+ "-dNOPAUSE",
+ "-dQUIET",
+ "-dBATCH",
+ f"-sOutputFile={output_path}",
+ input_path,
+ ]
+
+ subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ return output_path
+
diff --git a/utils/imagemagic_utils.py b/utils/imagemagic_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e75afb61dd35d58437c2b762ef1e2a03adccd78
--- /dev/null
+++ b/utils/imagemagic_utils.py
@@ -0,0 +1,95 @@
+import os
+import subprocess
+import uuid
+from shutil import which
+from PIL import Image
+
+from core.config import settings
+
+
+# -------------------------------------------------
+# Helper: check command availability
+# -------------------------------------------------
+def _has_cmd(cmd: str) -> bool:
+ return which(cmd) is not None
+
+
+# -------------------------------------------------
+# MAIN IMAGE CONVERTER
+# -------------------------------------------------
+def convert_image(input_path: str, output_ext: str):
+ output_ext = output_ext.lower().lstrip(".")
+ output_path = os.path.join(
+ settings.OUTPUT_DIR,
+ f"{uuid.uuid4().hex}.{output_ext}"
+ )
+
+ # -------------------------------------------------
+ # SPECIAL CASE: ICO (USE PILLOW — VERY RELIABLE)
+ # -------------------------------------------------
+ if output_ext == "ico":
+ return _convert_to_ico_pillow(input_path, output_path)
+
+ # -------------------------------------------------
+ # Prefer ImageMagick v7
+ # -------------------------------------------------
+ if _has_cmd("magick"):
+ cmd = [
+ "magick",
+ input_path,
+ "-background", "white",
+ "-flatten",
+ output_path
+ ]
+ subprocess.run(cmd, check=True)
+ return output_path
+
+ # -------------------------------------------------
+ # Fallback to ImageMagick v6
+ # -------------------------------------------------
+ if _has_cmd("convert"):
+ cmd = [
+ "convert",
+ input_path,
+ "-background", "white",
+ "-flatten",
+ output_path
+ ]
+ subprocess.run(cmd, check=True)
+ return output_path
+
+ # -------------------------------------------------
+ # No converter available
+ # -------------------------------------------------
+ raise RuntimeError(
+ "Image conversion failed: ImageMagick not installed"
+ )
+
+
+# -------------------------------------------------
+# PILLOW ICO CONVERTER (MULTI-SIZE ICON)
+# -------------------------------------------------
+def _convert_to_ico_pillow(input_path: str, output_path: str):
+ with Image.open(input_path) as img:
+ img = img.convert("RGBA")
+
+ sizes = [
+ (16, 16),
+ (32, 32),
+ (48, 48),
+ (64, 64),
+ (128, 128),
+ (256, 256),
+ ]
+
+ img.save(
+ output_path,
+ format="ICO",
+ sizes=sizes
+ )
+
+ if not os.path.exists(output_path):
+ raise RuntimeError("ICO conversion failed")
+
+ return output_path
+
diff --git a/utils/pandoc_utils.py b/utils/pandoc_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d28a4c0fa013d2dc88c6115200daf8b79c74880
--- /dev/null
+++ b/utils/pandoc_utils.py
@@ -0,0 +1,29 @@
+import subprocess
+import os
+import uuid
+from core.config import settings
+
+def convert_pandoc(input_path: str, target_ext: str):
+ target_ext = target_ext.lower().lstrip(".")
+
+ output_name = f"{uuid.uuid4()}.{target_ext}"
+ output_path = os.path.join(settings.OUTPUT_DIR, output_name)
+
+ cmd = ["pandoc", input_path, "-o", output_path]
+
+ # ✅ CRITICAL LINE (UNICODE SAFE)
+ if target_ext == "pdf":
+ cmd.extend(["--pdf-engine=xelatex"])
+
+ proc = subprocess.run(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE
+ )
+
+ if proc.returncode != 0:
+ stderr = proc.stderr.decode(errors="ignore")
+ raise RuntimeError("Pandoc failed: " + stderr)
+
+ return output_path
+
diff --git a/utils/response_utils.py b/utils/response_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..31d9da23b877e98a9d8a0e6dce5feb5353cfd129
--- /dev/null
+++ b/utils/response_utils.py
@@ -0,0 +1,55 @@
+import os
+from fastapi.responses import FileResponse
+
+def send_file(path: str):
+ if not os.path.exists(path):
+ return {"error": "File not found"}
+
+ return FileResponse(
+ path,
+ filename=os.path.basename(path),
+ media_type="video/mp4", # ✅ REQUIRED FOR PLAYBACK
+ headers={
+ "Accept-Ranges": "bytes"
+ }
+ )
+# utils/response_utils.py (or wherever send_file is defined)
+
+from fastapi.responses import FileResponse, JSONResponse
+import os
+import shutil
+import uuid
+# ... (other imports)
+
+def send_file(file_path: str, file_size: int = None): # ✅ ADD file_size PARAMETER
+ """
+ Sends the processed file back, and cleans up the file after transmission.
+ Returns a JSON response with URL and size for the frontend.
+ """
+ if not os.path.exists(file_path):
+ raise HTTPException(status_code=500, detail="Output file not found after processing.")
+
+ # 1. Determine the output URL path (e.g., /output/filename.mp4)
+ # This logic depends on how your FastAPI serves static files.
+ # We use a simple path relative to the UPLOAD_DIR
+ filename = os.path.basename(file_path)
+ output_url = f"/uploads/{filename}" # Adjust this to your static file serving path
+
+ # 2. Get size if not provided
+ if file_size is None:
+ file_size = os.path.getsize(file_path)
+
+ # 3. Use FileResponse to send the file and clean it up (using background tasks)
+ # The actual implementation of cleaning up after FileResponse needs a BackgroundTask
+
+ # 4. Return the required JSON structure to the frontend
+ # Note: The frontend uses the URL and size from this JSON response.
+ return JSONResponse(content={
+ "url": output_url,
+ "size": file_size,
+ "message": "File processed successfully"
+ })
+
+ # Note: If your send_file is designed to return the FileResponse directly,
+ # you would need to adjust the frontend or use FastAPI's BackgroundTasks
+ # to clean up the file after it is served.
diff --git a/utils/validate_utils.py b/utils/validate_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b783dc379ee2a209f4732048dac425c6faa3f80a
--- /dev/null
+++ b/utils/validate_utils.py
@@ -0,0 +1,6 @@
+import magic
+
+def get_mime_type(filepath: str):
+ mime = magic.Magic(mime=True)
+ return mime.from_file(filepath)
+
diff --git a/workerchange.sh b/workerchange.sh
new file mode 100644
index 0000000000000000000000000000000000000000..28f0503f4a96683fed79d44f58210e50d7fc1bb3
--- /dev/null
+++ b/workerchange.sh
@@ -0,0 +1,3 @@
+sudo systemctl daemon-reload
+sudo systemctl restart backend
+
diff --git a/workers/__init__.py b/workers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/workers/__pycache__/__init__.cpython-312.pyc b/workers/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3d22a1656d452fbb8dcc0f2167d499c3824a9970
Binary files /dev/null and b/workers/__pycache__/__init__.cpython-312.pyc differ
diff --git a/workers/__pycache__/converter_worker.cpython-312.pyc b/workers/__pycache__/converter_worker.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ffe206ef15583784797c692081dc473fc4b97d73
Binary files /dev/null and b/workers/__pycache__/converter_worker.cpython-312.pyc differ
diff --git a/workers/__pycache__/pdf_worker.cpython-312.pyc b/workers/__pycache__/pdf_worker.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85af0cc82c38b4292420a1e28348aa72fb53b3fa
Binary files /dev/null and b/workers/__pycache__/pdf_worker.cpython-312.pyc differ
diff --git a/workers/converter_worker.py b/workers/converter_worker.py
new file mode 100644
index 0000000000000000000000000000000000000000..4eebca24edfa0012f943795b426f8772f1c0b0b8
--- /dev/null
+++ b/workers/converter_worker.py
@@ -0,0 +1,23 @@
+from celery_app import celery_app
+from services.universal_converter_service import convert_file
+
+@celery_app.task(bind=True, name="workers.converter_worker.convert_task")
+def convert_task(self, input_path: str, target_ext: str):
+ try:
+ # 🔴 IMPORTANT: tell Celery we started
+ self.update_state(state="PROCESSING")
+
+ output_path = convert_file(input_path, target_ext)
+
+ # ✅ FINAL RESULT (this is what AsyncResult.result returns)
+ return {
+ "status": "done",
+ "output_path": output_path
+ }
+
+ except Exception as e:
+ return {
+ "status": "failed",
+ "error": str(e)
+ }
+
diff --git a/workers/pdf_worker.py b/workers/pdf_worker.py
new file mode 100644
index 0000000000000000000000000000000000000000..68f956c1a41c23d0b34bc0921988b83e4433701a
--- /dev/null
+++ b/workers/pdf_worker.py
@@ -0,0 +1,54 @@
+# backend/workers/pdf_worker.py
+import os
+import uuid
+import shutil
+
+from celery_app import celery_app
+from routers.pdf import (
+ ghostscript_compress,
+ PRESET_MAP,
+ TEMP_DIR,
+ safe_remove,
+)
+
+@celery_app.task(bind=True)
+def pdf_compress_task(self, input_path: str, preset: str):
+ output_path = None
+
+ try:
+ preset_value = PRESET_MAP.get(preset, "/screen")
+
+ output_path = os.path.join(
+ TEMP_DIR,
+ f"compressed_{uuid.uuid4().hex}.pdf"
+ )
+
+ # 🔥 HEAVY WORK (Ghostscript)
+ ghostscript_compress(
+ input_path=input_path,
+ output_path=output_path,
+ preset=preset_value
+ )
+
+ if not os.path.exists(output_path):
+ raise Exception("Compression failed: output file missing")
+
+ return {
+ "status": "done",
+ "output_path": output_path,
+ "size": os.path.getsize(output_path),
+ }
+
+ except Exception as e:
+ return {
+ "status": "failed",
+ "error": str(e),
+ }
+
+ finally:
+ # Cleanup input
+ try:
+ safe_remove(input_path)
+ except:
+ pass
+