import requests import gradio as gr import tempfile import os import pandas as pd API_URL = "https://de1.api.radio-browser.info/json/stations" # Fetch full list of stations from the API def fetch_stations(): try: response = requests.get(API_URL) response.raise_for_status() stations = response.json() count = len(stations) print(f"Starting fetch of {count} stations...") return stations, None except Exception as e: print(f"Error fetching stations: {e}") return None, str(e) # Write stations to M3U file def save_as_m3u(stations): tmp_dir = tempfile.mkdtemp() file_path = os.path.join(tmp_dir, "radio_stations.m3u") with open(file_path, "w", encoding="utf-8") as f: f.write("#EXTM3U\n") for station in stations: name = station.get("name", "Unknown") url = station.get("url_resolved", station.get("url", "")) f.write(f"#EXTINF:-1,{name}\n") f.write(f"{url}\n") print(f"M3U file created at {file_path} with {len(stations)} entries.") return file_path # Write stations to Excel file def save_as_excel(stations): tmp_dir = tempfile.mkdtemp() file_path = os.path.join(tmp_dir, "radio_stations.xlsx") data = [{"Station Name": s.get("name", ""), "Stream URL": s.get("url_resolved", s.get("url", ""))} for s in stations] df = pd.DataFrame(data) df.to_excel(file_path, index=False) print(f"Excel file created at {file_path} with {len(stations)} entries.") return file_path # Gradio interface def create_app(): with gr.Blocks() as demo: gr.Markdown( "## Radio Station Database Export\n" "Fetch the full list of radio stations from radio-browser.info and export in your chosen format." ) format_selector = gr.Radio( choices=["M3U", "Excel"], value="M3U", label="Select output format" ) export_button = gr.Button("Export") download_file = gr.File(label="Download File") status = gr.Textbox(label="Status") count_box = gr.Textbox(label="Stations Exported") def on_export(selected_format): stations, error = fetch_stations() if error: return None, f"❌ Error: {error}", "0" count = len(stations) if selected_format == "M3U": file_path = save_as_m3u(stations) else: file_path = save_as_excel(stations) return file_path, "✔️ Export completed.", str(count) export_button.click( fn=on_export, inputs=format_selector, outputs=[download_file, status, count_box] ) return demo if __name__ == "__main__": app = create_app() app.launch(share=False)