# PYTHON script

**URL:** https://forum.kirupa.com/t/python-script/659770
**Category:** programming
**Created:** [July 1, 2023, 3:37pm UTC](https://forum.kirupa.com/t/python-script/659770 "2023-07-01T15:37:47Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![payback](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/payback/32/20328_2.png) [@payback](https://forum.kirupa.com/u/payback)
#### Post date: [July 1, 2023, 3:37pm UTC](https://forum.kirupa.com/t/python-script/659770/1 "2023-07-01T15:37:47Z")

</div>

## Hello Gentlemen, I am testing the GTTS function IN PYTHON , CGI ENVIRONMENT , with the aim of implementing it in browsers that do not support text-to-speech. I can turn text to speech in MICROSOFT EDGE AND GOOGLE CHROME browsers with the speechSynthesis function. This function acts on error messages ( for example ) , system caption ( onmouseover ) , etc. In OPERA , VIVALD , FIREFOX browsers, the speechSynthesis function is not working. The PYTHON script to convert text to speech is very simple:

#!c:\python\python.exe  
from gtts import gTTS  
from gtts.tokenizer.pre\_processors import abbreviations, end\_of\_line  
from time import sleep  
from datetime import datetime  
import os  
import pyglet  
import cgi

# Create the text

form = cgi.FieldStorage()  
idioma = form.getvalue(‘idioma’)  
texto = form.getvalue(‘texto’)  
date\_s = (datetime.now().strftime(‘%Y%m%d%H%M%S%f’))

tts = gTTS(text=texto, lang=idioma , slow=False, pre\_processor\_funcs = [abbreviations, end\_of\_line])  
filename = ‘c:/payback/temp/’ + date\_s + ‘.mp3’  
if os.path.exists(filename): os.remove(filename) #remove temperory file  
tts.save(filename)

music = pyglet.media.load(filename, streaming=False)  
music.play()

## sleep(music.duration) #prevent from killing os.remove(filename) #remove temperory file #print (“Content-Type: text/html\n\n”)

## This script is run from the URL: https://server\_domain/tts.py?idioma=en&texto=Hello gentlemen, let’s discuss our strategic planning for the year 2024

My problem is in the last line of the script ( print (“Content-Type: text/html\n\n”) that is, if you don’t include it, the script plays the created mp3 file (so it converted text into voice) however it sends an error message: Internal Server Error ( Premature end of script headers: tts.py )  
If you include it, the script plays the mp3 file (no error) however it sends a new empty page harming the systematics of my need ( speak an error message , speak a caption with the onmouseover event , etc )  
no pagination.

I’m researching the CALLBACK function in javascript to try to work around this problem.This function would call the URL and when returning it would execute a BACK(-1) function.  
Note - Doesn’t seem like a good solution.  
Does anyone know how to solve this problem more properly?  
Thank you for your attention,  
Kleber  
Note - This text was translated by google.

---

<div class="post-metadata">

### Author: ![rohitsihag](https://avatars.discourse-cdn.com/v4/letter/r/71e660/32.png) [@rohitsihag](https://forum.kirupa.com/u/rohitsihag)
#### Post date: [July 4, 2023, 5:49am UTC](https://forum.kirupa.com/t/python-script/659770/2 "2023-07-04T05:49:22Z")

</div>

To create the specified text in JavaScript, you can use the `XMLHttpRequest` or the newer `fetch` API to send a request to the server-side script that handles the form submission. Here’s an example of how you can achieve this:

htmlCopy code

```auto
<!DOCTYPE html>
<html>
<head>
  <title>Form Submission Example</title>
</head>
<body>

  <h1>Form Submission Example</h1>

  <form id="myForm">
    <label for="idioma">Idioma:</label>
    <input type="text" name="idioma" id="idioma"><br>

    <label for="texto">Texto:</label>
    <input type="text" name="texto" id="texto"><br>

    <button type="submit">Submit</button>
  </form>

  <script>
    document.getElementById('myForm').addEventListener('submit', function(event) {
      event.preventDefault(); // Prevent form submission

      var form = new FormData(event.target); // Get form data
      var xhr = new XMLHttpRequest(); // Create XMLHttpRequest object

      // Set up the request
      xhr.open('POST', '/path/to/your/server-side/script', true);
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

      // Handle the response
      xhr.onload = function() {
        if (xhr.status === 200) {
          console.log(xhr.responseText); // Do something with the response
        } else {
          console.error('Request failed. Status: ' + xhr.status);
        }
      };

      // Send the request
      xhr.send(form);
    });
  </script>

</body>
</html>

```

In this example, the JavaScript code sets up an event listener on the form submission. When the form is submitted, it prevents the default form submission behavior, creates an XMLHttpRequest object, and sends the form data to the server-side script specified by the `open` method. Make sure to replace `/path/to/your/server-side/script` with the actual path to your server-side script that handles the form submission.

On the server-side, you would need to use a server-side language like Python to handle the form data and perform the necessary operations. Here’s a Python example using the CGI module:

pythonCopy code

```auto
import cgi
import os
from datetime import datetime
from gtts import gTTS
import pyglet

form = cgi.FieldStorage()
idioma = form.getvalue('idioma')
texto = form.getvalue('texto')
date_s = datetime.now().strftime('%Y%m%d%H%M%S%f')

tts = gTTS(text=texto, lang=idioma, slow=False)
filename = 'c:/payback/temp/' + date_s + '.mp3'
if os.path.exists(filename):
    os.remove(filename) # remove temporary file
tts.save(filename)

music = pyglet.media.load(filename, streaming=False)
music.play()

```

Please note that this is a simplified example, and you may need to modify the server-side code based on your specific requirements and server setup. Additionally, make sure you have the necessary dependencies (`gtts` and `pyglet`) installed for the server-side code to work properly.

---

<div class="post-metadata">

### Author: ![payback](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/payback/32/20328_2.png) [@payback](https://forum.kirupa.com/u/payback)
#### Post date: [July 4, 2023, 3:45pm UTC](https://forum.kirupa.com/t/python-script/659770/3 "2023-07-04T15:45:01Z")

</div>

Thank you for your kindness in replying.  
I tested with the suggested HTML and got the following message (in apache)  
Premature end of script headers: tts.py, referer: [https://server/development/test/tts.html](https://server/development/test/tts.html)  
There was no sound reproduction.  
Kleber  
Note - This text was translated by google.
