import gradio as gr from PIL import Image import os import ffmpeg import tempfile import threading import shutil # Atur tema Gradio gr.themes.Soft() def delete_temp_dir(directory, delay=900): # 15 minutes = 900 seconds timer = threading.Timer(delay, shutil.rmtree, [directory]) timer.start() # Format gambar yang didukung supported_formats = sorted(Image.SAVE.keys()) or ['BLP', 'BMP', 'BUFR', 'DDS', 'DIB', 'EPS', 'GIF', 'GRIB', 'HDF5', 'ICNS', 'ICO', 'IM', 'JPEG', 'JPEG2000', 'MPO', 'MSP', 'PALM', 'PCX', 'PDF', 'PNG', 'PPM', 'SGI', 'SPIDER', 'TGA', 'TIFF'] CACHE_DIR = tempfile.mkdtemp() delete_temp_dir(CACHE_DIR, delay=900) # Clean up cache after 15 minutes def sanitize_filename(filename): """Sanitize filename by removing special characters and spaces.""" return re.sub(r'[^a-zA-Z0-9_.-]', '_', filename) def clean_cache(): """Remove files in the cache directory older than 15 minutes.""" now = time.time() for file in os.listdir(CACHE_DIR): file_path = os.path.join(CACHE_DIR, file) if os.path.isfile(file_path) and now - os.path.getmtime(file_path) > 900: # 15 minutes os.remove(file_path) def convert_image(image_path, target_format): try: # Pastikan target format valid if target_format.lower() not in supported_formats: return "Error: Unsupported target format." # Sanitize file path sanitized_base_name = sanitize_filename(os.path.splitext(os.path.basename(image_path))[0]) # Nama file keluaran output_file = os.path.join(CACHE_DIR, f"flowly_ai_image_converter_{sanitized_base_name}.{target_format.lower()}") # Gunakan ffmpeg untuk konversi ffmpeg.input(image_path).output(output_file, format=target_format).overwrite_output().run( capture_stdout=True, capture_stderr=True ) return output_file # Return path ke file hasil except Exception as e: return f"Error: {e}" # Antarmuka Gradio interface = gr.Interface( fn=convert_image, inputs=[ gr.Image(label="Upload Image", type="filepath", height=512), # Input gambar gr.Dropdown(label="Select Target Format", choices=supported_formats) # Pilih format ], outputs=gr.File(label="Converted Image"), # Output file hasil title="Image Format Converter", description="Upload an image and select any target format for conversion using FFmpeg.", css="footer {visibility: hidden}" # Sembunyikan footer ) # Jalankan aplikasi if __name__ == "__main__": interface.launch()