CoolFace
Apppublic

srrexus/backendapi

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
main.py111 linesDownload Raw Back to root
1import os2import json3import shutil4import tempfile5from typing import Optional6from fastapi import FastAPI, File, UploadFile, Form7from fastapi.responses import JSONResponse8from fastapi.middleware.cors import CORSMiddleware9from tinytag import TinyTag10from mutagen.id3 import ID3, TIT2, TPE1, TALB, TYER, TCON, COMM, ID3NoHeaderError11 12app = FastAPI()13 14app.add_middleware(15    CORSMiddleware,16    allow_origins=["*"],17    allow_methods=["*"],18    allow_headers=["*"],19)20 21def get_metadata(file_path: str) -> dict:22    try:23        tag = TinyTag.get(file_path)24        return {25            "title": tag.title,26            "artist": tag.artist,27            "album": tag.album,28            "genre": tag.genre,29            "year": tag.year,30            "duration": round(tag.duration, 2) if tag.duration else None,31            "bitrate": tag.bitrate,32            "samplerate": tag.samplerate33        }34    except Exception as e:35        return {"error": str(e)}36 37def process_mp3_metadata_mutagen(file_path: str, custom_tags: dict):38    """Manipulasi metadata MP3 murni menggunakan Python Mutagen."""39    try:40        # 1. Strip/Hapus ID3 Tag lama41        try:42            audio = ID3(file_path)43            audio.delete()44            audio.save()45        except ID3NoHeaderError:46            pass # File mungkin tidak punya tag, lanjut saja47 48        # 2. Tulis Metadata Kustom49        # Map key manual_metadata ke ID3 Frame50        audio = ID3()51        if "Title" in custom_tags: audio.add(TIT2(encoding=3, text=custom_tags["Title"]))52        if "Artist" in custom_tags: audio.add(TPE1(encoding=3, text=custom_tags["Artist"]))53        if "Album" in custom_tags: audio.add(TALB(encoding=3, text=custom_tags["Album"]))54        if "Year" in custom_tags: audio.add(TYER(encoding=3, text=custom_tags["Year"]))55        if "Genre" in custom_tags: audio.add(TCON(encoding=3, text=custom_tags["Genre"]))56        if "Comment" in custom_tags: audio.add(COMM(encoding=3, lang='eng', text=custom_tags["Comment"]))57        58        audio.save(file_path, v2_version=3)59        60    except Exception as e:61        print(f"Log: Mutagen Error: {e}")62        raise e63 64@app.post("/engine/sanitize")65async def sanitize_endpoint(66    file: UploadFile = File(...),67    manual_metadata: Optional[str] = Form(None)68):69    with tempfile.TemporaryDirectory() as temp_dir:70        safe_filename = file.filename.replace(" ", "_")71        input_path = os.path.join(temp_dir, f"in_{safe_filename}")72        output_path = os.path.join(temp_dir, f"out_{safe_filename}")73        74        try:75            with open(input_path, "wb") as f:76                f.write(await file.read())77            78            metadata_before = get_metadata(input_path)79            is_mp3 = file.filename.lower().endswith('.mp3')80            81            custom_tags = {}82            if manual_metadata:83                try:84                    custom_tags = json.loads(manual_metadata)85                except:86                    pass87            88            # Alur Pemrosesan89            if is_mp3:90                shutil.copy2(input_path, output_path)91                # Gunakan mutagen untuk edit92                process_mp3_metadata_mutagen(output_path, custom_tags)93                mode = "Advanced Secure MP3 Edit (Mutagen)"94            else:95                # Untuk non-MP3, tetap copy (bisa tambahkan library lain jika mau)96                shutil.copy2(input_path, output_path)97                mode = "Default Clean"98            99            metadata_after = get_metadata(output_path)100            101            return JSONResponse({102                "message": f"Success. Mode: {mode}",103                "metadata": {"before": metadata_before, "after": metadata_after}104            })105            106        except Exception as e:107            return JSONResponse(status_code=500, content={"error": str(e)})108 109if __name__ == "__main__":110    import uvicorn111    uvicorn.run(app, host="0.0.0.0", port=7860)