scripts/elhuyar_ahotsa.py
(Deskargatu)
import urllib.request
import re
import ssl
import json
import sys
import subprocess
def get_csrf_token(url):
"""
Fetches the given URL and extracts the CSRF middleware token.
"""
try:
# Create a default SSL context that does not verify certificates
context = ssl._create_unverified_context()
with urllib.request.urlopen(url, context=context) as response:
html = response.read().decode('utf-8')
# Use regex to find the csrfmiddlewaretoken
match = re.search(r'<input[^>]*name="csrfmiddlewaretoken"[^>]*value="([^"]+)"', html)
if match:
return match.group(1)
else:
return "CSRF token not found."
except Exception as e:
return f"An error occurred: {e}"
def get_audio_path(post_url, text, token, target_url):
"""
Makes a POST request to get an audio path.
"""
try:
# Prepare the data for the POST request
post_data = {
'csrfmiddlewaretoken': token,
'language': 'eu',
'voice': '29',
'text': text
}
# Encode the data as X-WWW-Form-Urlencoded
data = urllib.parse.urlencode(post_data).encode('utf-8')
# create cookie header
cookie = f"csrftoken={token}"
# Create a request object
req = urllib.request.Request(
post_url,
data=data,
headers={
'Cookie': cookie,
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
'Referer': target_url,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
)
# Create a default SSL context that does not verify certificates
context = ssl._create_unverified_context()
with urllib.request.urlopen(req, context=context) as response:
# Read and print the response
response_data = response.read().decode('utf-8')
# Parse json result
json_result = json.loads(response_data)
# get the result audio_path
return json_result.get('audio_path')
except Exception as e:
print(f"An error occurred during the POST request: {e}")
return None
def play_audio(audio_url):
"""
Plays the audio from the given URL using ffplay.
"""
if not audio_url:
print("No audio URL provided.")
return
try:
# Construct the full URL if it's a relative path
if not audio_url.startswith('http'):
audio_url = f"https://ttsneuronala.elhuyar.eus{audio_url}"
print(f"Playing audio from: {audio_url}")
subprocess.run(['ffplay', '-nodisp', '-autoexit', audio_url], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except FileNotFoundError:
print("ffplay not found. Please install ffmpeg.")
except subprocess.CalledProcessError as e:
print(f"An error occurred while trying to play the audio: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
text = " ".join(sys.argv[1:])
if not text:
print("No text provided")
sys.exit(1)
target_url = "https://ttsneuronala.elhuyar.eus/es"
token = get_csrf_token(target_url)
if "CSRF token not found" in token or "An error occurred" in token:
print(token)
else:
post_url = "https://ttsneuronala.elhuyar.eus/ajax/get_audio_from_box"
audio_path = get_audio_path(post_url, text, token, target_url)
if audio_path:
play_audio(audio_path)