from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import Response, HTMLResponse
import yt_dlp
import whisper
import tempfile
import os
import io
import urllib.request
import urllib.parse
import json
from diffusers import StableDiffusionPipeline
# --- 1. METADATA & NEON UI ---
api_description = """
SILENT TECH UTILITY ENGINE
This is the Private Backend API for the Silent Bot network.
Completely independent, uncensored, and running on a dedicated 16GB RAM Linux container.
"""
tags_metadata = [
{"name": "System", "description": "Server health status."},
{"name": "Media Downloader", "description": "Extract raw media URLs from social platforms."},
{"name": "Voice AI", "description": "Transcribe audio files perfectly."},
{"name": "Image AI", "description": "Generate uncensored images."}
]
app = FastAPI(
title="SILENT TECH API",
description=api_description,
version="2.0.0",
openapi_tags=tags_metadata,
docs_url=None,
redoc_url=None
)
@app.get("/docs", include_in_schema=False)
async def neon_swagger_ui():
html = """
Silent Tech API - NEON UI
"""
return HTMLResponse(html)
# --- 2. LOAD AI MODELS ---
print("Loading Whisper Voice AI...")
voice_model = whisper.load_model("base")
print("Loading Uncensored Image AI...")
image_model = StableDiffusionPipeline.from_pretrained("prompthero/openjourney", safety_checker=None)
image_model.to("cpu")
# --- 3. API ENDPOINTS ---
@app.get("/", tags=["System"])
def read_root():
return {"status": "Silent Utils API is ONLINE", "version": "2.0.0"}
@app.get("/api/download", tags=["Media Downloader"])
def download_media(url: str):
"""Bypasses protections and gets the direct raw MP4/MP3 link."""
clean_url = url.strip()
# 💥 FIREWALL BYPASS: If it's YouTube, route it through an external proxy API!
if "youtube.com" in clean_url or "youtu.be" in clean_url:
try:
bypass_url = f"https://api.bk9.site/yt/mp4?url={urllib.parse.quote(clean_url)}"
req = urllib.request.Request(bypass_url, headers={'User-Agent': 'Mozilla/5.0'})
with urllib.request.urlopen(req) as response:
data = json.loads(response.read().decode())
if data.get("status") and "BK9" in data:
return {
"success": True,
"title": data["BK9"].get("title", "YouTube Video"),
"download_url": data["BK9"].get("url")
}
except Exception as bypass_e:
print("Bypass failed:", str(bypass_e))
# If bypass fails, fall back to yt-dlp just in case
# Standard yt-dlp for TikTok, Instagram, Twitter, etc.
ydl_opts = {
'format': 'best',
'quiet': True,
'no_warnings': True,
'skip_download': True,
'nocheckcertificate': True
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(clean_url, download=False)
if 'entries' in info:
info = info['entries'][0]
final_url = info.get('url')
if not final_url and 'requested_downloads' in info:
final_url = info['requested_downloads'][0].get('url')
if not final_url:
raise Exception("Could not extract the raw video URL.")
return {
"success": True,
"title": info.get('title', 'Silent Media'),
"download_url": final_url
}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.post("/api/transcribe", tags=["Voice AI"])
async def transcribe_audio(file: UploadFile = File(...)):
"""Converts WhatsApp voice notes (or any audio) to text."""
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".ogg") as temp_audio:
temp_audio.write(await file.read())
temp_audio_path = temp_audio.name
result = voice_model.transcribe(temp_audio_path)
os.remove(temp_audio_path)
return {"success": True, "text": result["text"].strip()}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/image", tags=["Image AI"])
def generate_image(prompt: str):
"""Generates an uncensored image and returns it directly as a PNG."""
try:
image = image_model(prompt, num_inference_steps=8, height=384, width=384).images[0]
img_bytes = io.BytesIO()
image.save(img_bytes, format="PNG")
return Response(content=img_bytes.getvalue(), media_type="image/png")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))