SGDL / app.py
NeoPy's picture
Create app.py
72116c0 verified
raw
history blame
2.76 kB
import gradio as gr
import requests
import re
from urllib.parse import urlparse
import os
def validate_url(url):
"""Validate if the URL is a valid soundgasm.net link."""
pattern = r'^https?://soundgasm\.net/u/[\w-]+/[\w-]+'
return bool(re.match(pattern, url.strip()))
def extract_audio_url(page_content):
"""Extract the direct audio URL from the Soundgasm page content."""
audio_pattern = r'(https?://media\.soundgasm\.net/sounds/[\w-]+\.(?:mp3|m4a))'
match = re.search(audio_pattern, page_content)
return match.group(1) if match else None
def download_audio(url):
"""Download audio from a soundgasm.net link."""
try:
# Validate URL
if not validate_url(url):
return "Invalid Soundgasm.net URL. Please provide a valid link."
# Get the page content
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url.strip(), headers=headers, timeout=10)
response.raise_for_status()
# Extract audio URL
audio_url = extract_audio_url(response.text)
if not audio_url:
return "Could not find audio file in the provided link."
# Download the audio
audio_response = requests.get(audio_url, headers=headers, stream=True, timeout=10)
audio_response.raise_for_status()
# Extract filename from URL
parsed_url = urlparse(audio_url)
filename = os.path.basename(parsed_url.path)
# Save the audio file temporarily
temp_dir = "downloads"
os.makedirs(temp_dir, exist_ok=True)
file_path = os.path.join(temp_dir, filename)
with open(file_path, 'wb') as f:
for chunk in audio_response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
return file_path
except requests.exceptions.RequestException as e:
return f"Error downloading audio: {str(e)}"
except Exception as e:
return f"An unexpected error occurred: {str(e)}"
# Gradio Blocks UI
with gr.Blocks(title="Soundgasm Audio Downloader") as demo:
gr.Markdown("# Soundgasm Audio Downloader")
gr.Markdown("Enter a Soundgasm.net link to download the audio file.")
with gr.Row():
url_input = gr.Textbox(label="Soundgasm URL", placeholder="https://soundgasm.net/u/username/audio-title")
download_button = gr.Button("Download Audio")
output = gr.File(label="Downloaded Audio")
error_message = gr.Textbox(label="Status", interactive=False)
download_button.click(
fn=download_audio,
inputs=url_input,
outputs=[output, error_message]
)
if __name__ == "__main__":
demo.launch()