Top

libtlp module

The transLectures-UPV Platform (TLP) 2.0 Python Library

Software Requirements:

This module mainly implements the TLPClient class that provides several methods to interact with the transLectures-UPV Platform.

Import libtlp and create a TLPClient class instance:

>>> import tlplib
>>> tlp = TLPClient("http://ttp.mllp.upv.es/api", "http://ttp.mllp.upv.es/player", "tluser", "akjsfd982323098qwjs209823id09321io3290d")

To get the list of subtitle languages available for a particular Media ID:

>>> tlp.api_langs("media-id-1")
>>> print tlp.get_printable_response_data()

To download a subtitles file, for instance, English subtitles in SRT format:

>>> tlp.api_subs("media-id-1", "en", form="srt")
>>> tlp.save_response_data("/path/to/my/media_subs.en.srt")

To Generate and upload a Media Package File to the TLP Server is also quite straightforward:

>>> # Initialise Manifest, define "New Media" Operation and Media ID:
>>> tlp.manifest_init(libtlp.TLPClient.INGEST_OPCODE_NEW, "media-id-2")
>>> # Add media language and title:
>>> tlp.manifest_set_metadata(language="en", title="Testing libtlp")
>>> # Add main media file:
>>> tlp.manifest_set_main_media_file("/path/to/my/media_file.mp4")
>>> # Enable Ingest Service's Test Mode, since we are doing a test:
>>> tlp.manifest_set_options(test_mode=True)
>>> # Generate Media Package File and upload it via the /ingest interface:
>>> tlp.api_ingest()
>>> # Why to print the response? I just want the upload ID!
>>> upload_id = tlp.ret_data['id']

To track the progress of our first upload:

>>> tlp.api_status(upload_id)
>>> print tlp.get_printable_response_data()

Anyway, you can build the most complex Media Package in the world, but only if you want!

>>> tlp.manifest_init(libtlp.TLPClient.INGEST_OPCODE_NEW, "media-id-3")
>>> tlp.manifest_set_metadata(language="en", title="Really testing libtlp")
>>> tlp.manifest_set_main_media_file("/path/to/my/media_file.mp4")
>>> # Add info about media speaker:
>>> tlp.manifest_add_speaker("speaker-id_1", "John Snow", email="jsnow21@got.com")
>>> # Add a related text file to improve the media transcription
>>> tlp.manifest_add_attachment("/path/to/my/doc_file.pdf", libtlp.TLPClient.FTYPE_CODE_DOCUMENT)
>>> # Request Spanish subtitles (English are generated by default):
>>> tlp.manifest_add_subtitles_request("es")
>>> # Request also a text-to-speech synthesized Spanish audiotrack:
>>> tlp.manifest_add_audiotrack_request("es")
>>> # etc, etc, etc.
>>> # BUT FINALLY...
>>> tlp.api_ingest()
>>> # Mere curiosity... print me the generated Manifest JSON object!
>>> print tlp.get_printable_manifest()

For further information you might check the full documentation of the transLectures-UPV Platform.

# -*- coding: utf-8 -*-
#  Copyright 2015 transLectures-UPV Team
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#

"""

## The *transLectures-UPV Platform* (TLP) 2.0 Python Library

Software Requirements:

* [python-requests](http://docs.python-requests.org)

This module mainly implements the `TLPClient` class that provides several
methods to interact with the *transLectures-UPV Platform*.

Import **libtlp** and create a TLPClient class instance:

    #!python
    >>> import tlplib
    >>> tlp = TLPClient("http://ttp.mllp.upv.es/api", "http://ttp.mllp.upv.es/player", "tluser", "akjsfd982323098qwjs209823id09321io3290d")

To **get the list of subtitle languages available** for a particular Media ID:

    #!python
    >>> tlp.api_langs("media-id-1")
    >>> print tlp.get_printable_response_data()

To **download a subtitles file**, for instance, English subtitles in SRT format:

    #!python
    >>> tlp.api_subs("media-id-1", "en", form="srt")
    >>> tlp.save_response_data("/path/to/my/media_subs.en.srt")


To **Generate and upload a Media Package File** to the TLP Server is also quite straightforward:
    
    #!python
    >>> # Initialise Manifest, define "New Media" Operation and Media ID:
    >>> tlp.manifest_init(libtlp.TLPClient.INGEST_OPCODE_NEW, "media-id-2")
    >>> # Add media language and title:
    >>> tlp.manifest_set_metadata(language="en", title="Testing libtlp")
    >>> # Add main media file:
    >>> tlp.manifest_set_main_media_file("/path/to/my/media_file.mp4")
    >>> # Enable Ingest Service's Test Mode, since we are doing a test:
    >>> tlp.manifest_set_options(test_mode=True)
    >>> # Generate Media Package File and upload it via the /ingest interface:
    >>> tlp.api_ingest()
    >>> # Why to print the response? I just want the upload ID!
    >>> upload_id = tlp.ret_data['id']

To **track the progress** of our first upload: 

    #!python
    >>> tlp.api_status(upload_id)
    >>> print tlp.get_printable_response_data()
    
Anyway, you can build the most **complex Media Package** in the world, but only if you want!
    
    #!python
    >>> tlp.manifest_init(libtlp.TLPClient.INGEST_OPCODE_NEW, "media-id-3")
    >>> tlp.manifest_set_metadata(language="en", title="Really testing libtlp")
    >>> tlp.manifest_set_main_media_file("/path/to/my/media_file.mp4")
    >>> # Add info about media speaker:
    >>> tlp.manifest_add_speaker("speaker-id_1", "John Snow", email="jsnow21@got.com")
    >>> # Add a related text file to improve the media transcription
    >>> tlp.manifest_add_attachment("/path/to/my/doc_file.pdf", libtlp.TLPClient.FTYPE_CODE_DOCUMENT)
    >>> # Request Spanish subtitles (English are generated by default):
    >>> tlp.manifest_add_subtitles_request("es")
    >>> # Request also a text-to-speech synthesized Spanish audiotrack:
    >>> tlp.manifest_add_audiotrack_request("es")
    >>> # etc, etc, etc.
    >>> # BUT FINALLY...
    >>> tlp.api_ingest()
    >>> # Mere curiosity... print me the generated Manifest JSON object!
    >>> print tlp.get_printable_manifest()
 
For **further information** you might check the [full documentation of the transLectures-UPV Platform](http://ttp.mllp.upv.es/doc).

"""
 
import cStringIO
from datetime import datetime, timedelta
import hashlib
import json
import base64
import os.path
import tempfile
import zipfile
import shutil
import urllib2
import requests


class TLPClient():

    """
    TLPClient class.
    """

    FTYPE_CODE_MEDIA = 0
    """Main Media file type code"""
    FTYPE_CODE_SLIDES = 1
    """Slides file type code code"""
    FTYPE_CODE_DOCUMENT = 2
    """Related Text Document file type code"""
    FTYPE_CODE_THUMBNAIL = 3
    """Media thumbnail file type code"""
    FTYPE_CODE_SUBS = 4
    """Subtitles file type code"""
    FTYPE_CODE_AUDIOTRACK = 5
    """Audiotrack file type code"""
    FTYPE_CODE_WAVEFORM = 6
    """Waveform file type code"""

    SUBS_SELDATA_ALL = 0
    """Subtitle contents to be returned: Return both former and current contents (only for DFXP format). """
    SUBS_SELDATA_FORMER = 1
    """Subtitle contents to be returned: Return former contents (automatic transcription or translation). """
    SUBS_SELDATA_CURRENT = 2
    """Subtitle contents to be returned: Return current contents (current status of supervision of the subtitles). """
    
    SUBS_SEGFILT_EMTPY = -1
    """Segment text filtering policy: Empty all segments (removes text from all segments). """
    SUBS_SEGFILT_DISABLE = 0
    """Segment text filtering policy: Filtering disabled. """
    SUBS_SEGFILT_ENABLE = 1
    """Segment text filtering policy: Filters out special annotations. """

    INGEST_OPCODE_NEW = 0
    """Ingest Service New Media Operation Code: A new media will be processed by the Ingest Service and inserted into database. """
    INGEST_OPCODE_UPDATE = 1
    """Ingest Service Update Media Operation Code: An existing media will be updated after processing the input data by the Ingest Service. """
    INGEST_OPCODE_DELETE = 2
    """Ingest Service Delete Media Operation Code: An existing media will be deleted from the database. """
    INGEST_OPCODE_CANCEL = 3
    """Ingest Service Cancel Upload Operation Code: An ongoing upload will be cancelled. """

    def __init__(self, api_base_url, player_base_url, api_user, api_secret_key):
        """
        Creates a TLPClient class instance. Parameters:

        - **_api_base_url_**: Base URL to the transLectures-UPV Platform's Web Service.
        - **_player_base_url_**: Base URL to the transLectures-UPV Platform's Player.
        - **_api_user_**: API username / TLP username.
        - **_api_secret_key_**: API Secret Key.
        """
        self.__manifest_files = None
        self.__last_api_call = None
        self.__tmp_dir = None
        self.__session = None
        self.__response = None
        self.__http_auth_enabled = False
        self.__http_user = None
        self.__http_pass = None
        self.__api_mod_session_id = None
        self.__api_base_url = api_base_url
        self.__player_base_url = player_base_url
        self.__api_user = api_user
        self.__api_secret_key = api_secret_key
        self.use_get_method = False
        """Use HTTP GET Method instead of POST."""
        self.use_data_parameter = True
        """Use a single "data" parameter on HTTP GET calls instead multiple GET parameters."""
        self.parameters = None
        """Dictionary with API query parameters."""
        self.ret_data = None
        """Data returned by the last performed API call. If the response was a JSON object, *ret_data* becomes a a parsed JSON object (dictionary or list, depending on the JSON)."""
        self.ret_content_type = None
        """Mime-type of the data returned by the last performed API call."""
        self.debug = False
        """Enable/Disable generation of debug information."""
        self.debug_info = None
        """Debug information of the last performed API call / Generation of Player URL."""
        self.manifest = None
        """Manifest JSON object."""

    def __reset_http_session(self):
        """Resets requests.Session class instance."""
        self.__session = requests.Session()
        if self.__http_auth_enabled:
            self.__session.auth = (self.__http_user, self.__http_pass)

    def __reset(self):
        """Reset all class methods to perform a new API call."""
        self.__reset_http_session()
        self.__response = None
        self.parameters = {}
        self.ret_data = None
        self.ret_content_type = None
        self.debug_info = None

    def __set_auth_parameters_secret_key(self):
        """Set API authentication parameters using the secret key."""
        self.parameters['user'] = self.__api_user
        self.parameters['auth_token'] = self.__api_secret_key

    def __set_auth_parameters_request_key_api(self, req_key_lifetime, oid, author=None, author_conf=None):
        """Set API authentication parameters using a request key for an API call."""
        self.parameters['user'] = self.__api_user
        expire = self.__gen_expire_parameter(req_key_lifetime)
        self.parameters['auth_token'] = self.gen_request_key(oid, expire, author, author_conf)
        self.parameters['expire'] = expire

    def __set_auth_parameters_request_key_player(self, req_key_lifetime, oid, author=None, author_conf=None):
        """Set API authentication parameters using a request key for generating a Player URL."""
        self.parameters['api_user'] = self.__api_user
        expire = self.__gen_expire_parameter(req_key_lifetime)
        self.parameters['request_key'] = self.gen_request_key(oid, expire, author, author_conf)
        self.parameters['expire'] = expire

    def __gen_expire_parameter(self, lifetime):
        """Returns a valid value of the "expire" API authentication parameter."""
        return int((datetime.utcnow() + timedelta(minutes=lifetime) - datetime(1970,01,01)).total_seconds())

    def __generate_debug_info_api(self, url):
        """ Generates debug information about the last API call."""
        o = cStringIO.StringIO()
        o.write("\n")
        o.write("- Input data (JSON-formatted):\n")
        o.write("%s\n" % json.dumps(self.parameters, encoding="UTF-8", indent=4))
        o.write("\n")
        if self.use_get_method:
          if self.use_data_parameter:
            o.write("- URL (using GET request with a single 'data' base64-encoded JSON parameter):\n")
            o.write("%s?data=%s\n" % (url, base64.b64encode(json.dumps(self.parameters, encoding="UTF-8"))))
            o.write("\n")
          else:
            o.write("- URL (using GET request with multiple parameters):\n")
            params = "&".join([ "%s=%s"%(k, str(self.parameters[k])) for k in self.parameters ])
            o.write("%s?%s\n" % (url, params))
            o.write("\n")
        else:
          o.write("- URL + POST data parameter:\n")
          o.write("%s\n" % url)
          o.write("%s\n" % base64.b64encode(json.dumps(self.parameters, encoding="UTF-8")))
        if self.__last_api_call == "ingest":
          if self.manifest != None:
            o.write("\n- Manifest.JSON file:\n")
            o.write("%s\n" % self.get_printable_manifest())
            o.write("\n")
          if self.__tmp_dir != None:
            o.write("- Temp dir: %s\n" % self.__tmp_dir)
        self.debug_info = o.getvalue()
 
    def __generate_debug_info_player(self):
        """ Generates debug information about the last generated Player URL."""
        o = cStringIO.StringIO()
        o.write("\n")
        o.write("- Input data (JSON-formatted):\n")
        o.write("%s\n" % json.dumps(self.parameters, encoding="UTF-8", indent=4))
        o.write("\n")
        o.write("- Input data (Base 64):\n")
        o.write("%s\n" % base64.b64encode(json.dumps(self.parameters, encoding="UTF-8")))
        o.write("\n")
        self.debug_info = o.getvalue()

    
    def __parse_response(self):
        if self.__response.status_code == 200:
            self.ret_content_type = self.__response.headers['content-type']
            if self.ret_content_type.find("application/json") >= 0:
                self.ret_data = json.loads(self.__response.content)
            else:
                self.ret_data = self.__response.content
        elif self.__response.status_code == 400:
            raise APIBadRequest(self.__response.content)
        elif self.__response.status_code == 401:
            raise APIUnauthorized(self.__response.content)
        elif self.__response.status_code == 419:
            raise APIAuthenticationTimeout(self.__response.content)
        elif self.__response.status_code == 500:
            raise APIInternalServerError(self.__response.content)
        
   
    def __call(self, url):
        """ Call the specified url using with the parameters determined by the "parameters" class attribute."""
        if self.use_get_method:
            if self.use_data_parameter:
                data = base64.b64encode(json.dumps(self.parameters, encoding="UTF-8"))
                par = {'data':data}
            else:
                par = self.parameters
            self.__response = self.__session.get(url=url,params=par)
        else:
            data = base64.b64encode(json.dumps(self.parameters, encoding="UTF-8"))
            self.__response = self.__session.post(url=url,data=data)
        self.__parse_response()

     
    def __call_ingest(self, url, data):
        """ Call the specified url (ingest interface) using with the parameters determined by the "parameters" class attribute."""
        if self.use_data_parameter:
            json_data = base64.b64encode(json.dumps(self.parameters, encoding="UTF-8"))
            par = {'data':json_data}
        else:
            par = self.parameters
        self.__response = self.__session.post(url=url,data=data,headers={'Content-Type': 'application/zip'},params=par)
        self.__parse_response()


    def __is_url(self, url):
        try:
            myurl = urllib2.urlopen(url).geturl()
        except: 
            return False
        return True

 
    def __get_file_format(self, fp):
        return os.path.splitext(fp)[1][1:]


    def __get_file_name(self, fp):
        return os.path.basename(fp)


    def __md5sum(self, fp):
        md5 = hashlib.md5()
        with open(fp, 'rb') as f:
            for chunk in iter(lambda: f.read(128 * md5.block_size), b''):
                md5.update(chunk)
        return md5.hexdigest()

    def enable_http_auth(self, http_user, http_pass):
        """Use HTTP Authentication for all API calls.
           
           **_http_user_** is the HTTP Authentication username, while **_http_pass_** is the corresponding user password.
        """
        self.__http_user = http_user
        self.__http_pass = http_pass
        self.__http_auth_enabled = True


    def disable_http_auth(self):
        """Disable HTTP Authentication for all API calls"""
        self.__http_user = None
        self.__http_pass = None
        self.__http_auth_enabled = False


    def gen_request_key(self, oid, expire, author=None, author_conf=None):
        """Returns a valid request key to be used as an API authentication token.

	   **_oid_** is the object ID that will be queried (*id* API call
           parameter), and **_expire_** is the UNIX timestamp of the expiration time of
           the key. With these two parameters is generated the *basic request key*.
   
           If **_author_** (*author_id* API parameter) is supplied, then the *full request key* is generated 
           using this parameter plus **_author_conf_** (*author_conf* API parameter).

        """
        s1 = hashlib.sha1()
        s1.update(oid + str(expire) + self.__api_user + self.__api_secret_key)
        rk = s1.hexdigest()
        if author != None:
          s2 = hashlib.sha1()
          s2.update(author + str(author_conf) + str(expire) + self.__api_user + self.__api_secret_key)
          rk += s2.hexdigest()
        return rk


    def get_printable_response_data(self):
         """Returns a printable, user friendly version of the response data from the 
            last API call (stored in the `libtlp.TLPClient.ret_data` class member).
         """
         if self.ret_data == None:
            raise TLPException("No response data available (have you called any API interface before?).")
         if self.ret_content_type.find("application/json") >= 0:
             return json.dumps(self.ret_data, indent=4)
         else:
             return self.ret_data


    def get_printable_manifest(self):
         """Returns a printable, user friendly version of the manifest JSON object (stored in the `libtlp.TLPClient.manifest` class member).
         """
         if self.manifest != None:
             return json.dumps(self.manifest, indent=4)
         else:
             raise TLPException("Manifest file was not initialized.")


    def save_response_data(self, dest):
         """Saves the response data from the last API call (stored in the `libtlp.TLPClient.ret_data` 
            class member) into the destination **_dest_** file.
         """
         with open(dest,'wb') as fd:
             fd.write(self.get_printable_response_data())


    def manifest_init(self, operation_code, external_id):
        """Initalize the `libtlp.TLPClient.manifest` JSON object.

	   Allowed **_operation_code_** values are: `libtlp.TLPClient.INGEST_OPCODE_NEW`,
           `libtlp.TLPClient.INGEST_OPCODE_UPDATE`,
           `libtlp.TLPClient.INGEST_OPCODE_DELETE`,
           `libtlp.TLPClient.INGEST_OPCODE_CANCEL`.

           **_external_id_** must be a Media ID or an existing upload ID if **_operation_code_** is `libtlp.TLPClient.INGEST_OPCODE_CANCEL`.

           **Note:** This method should be executed before calling the `libtlp.TLPClient.api_ingest` method and any *manifest_\** class methods.
        """
        self.__tmp_dir = None
        self.__manifest_files = []
        self.manifest = {}
        self.manifest['operation_code'] = operation_code
        self.manifest['metadata'] = {}
        self.manifest['metadata']['external_id'] = external_id


    def manifest_set_metadata(self, language=None, title=None, topic=None, keywords=None, date=None):
        """Set metadata in the `libtlp.TLPClient.manifest` JSON object.

	   **_language_** is the Media language code in ISO 639-1 format (e.g.
           "en", "es"), **_title_** is the title of the media, **_topic_** is the topic of
           the media, **_keywords_** are the media keywords, and **_date_** is the
           publication date of the media. 

	   All arguments are optional, but **_language_** and **_title_**
           arguments are mandatory for `libtlp.TLPClient.INGEST_OPCODE_NEW` operations.

	   **Note:** The `libtlp.TLPClient.manifest` object should have been
           initialised before with a `libtlp.TLPClient.manifest_init` call. This method
           should be executed before calling the `libtlp.TLPClient.api_ingest` method.

        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        if language != None:
            self.manifest['metadata']['language'] = language
        if title != None:
            self.manifest['metadata']['title'] = title
        if topic != None:
            self.manifest['metadata']['topic'] = topic
        if keywords != None:
            self.manifest['metadata']['keywords'] = keywords
        if date != None:
            self.manifest['metadata']['date'] = date
        
   
    def manifest_add_speaker(self, speaker_id, speaker_name, email=None, gender=None):
        """Add a speaker in the metadata section of the `libtlp.TLPClient.manifest` JSON object.

	   **_speaker_id_** is the speaker ID of the media file, **_speaker_name_** is
           the full name of the speaker, **_email_** is the e-mail of the speaker, and
           **_gender_** is the gender of the speaker (*M* for Male or *F* for Female).
           **_email_** and **_gender_** are optional.

	   **Note:** The `libtlp.TLPClient.manifest` object should have been
           initialised before with a `libtlp.TLPClient.manifest_init` call. This method
           should be executed before calling the `libtlp.TLPClient.api_ingest` method.
        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        spk = {}
        spk['speaker_id'] = speaker_id
        spk['speaker_name'] = speaker_name
        if gender != None: spk['speaker_gender'] = gender
        if email != None: spk['speaker_email'] = email
        try:
            self.manifest['metadata']['speakers'].append(spk)
        except:
            self.manifest['metadata']['speakers'] = [spk]


    def manifest_set_main_media_file(self, uri):
        """Set main media file in the `libtlp.TLPClient.manifest` JSON object.

           **_uri_** can be a media file path o a media URL.

	   **Note:** The `libtlp.TLPClient.manifest` object should have been
           initialised before with a `libtlp.TLPClient.manifest_init` call. This method
           should be executed before calling the `libtlp.TLPClient.api_ingest` method.
        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        self.manifest['media'] = {}
        if self.__is_url(uri):
            self.manifest['media']['url'] = uri
        else:
            self.manifest['media']['filename'] = self.__get_file_name(uri)
            self.manifest['media']['fileformat'] = self.__get_file_format(uri)
            self.manifest['media']['md5'] = self.__md5sum(uri)
            self.__manifest_files.append(uri)

            
    def manifest_add_attachment(self, uri, file_type_code, language=None, human=None):
        """Add attachment file to the `libtlp.TLPClient.manifest` JSON object.

	   **_uri_** is the attachment file path, and **_file_type_code_** must be one of
           the following values: `libtlp.TLPClient.FTYPE_CODE_MEDIA`,
           `libtlp.TLPClient.FTYPE_CODE_SLIDES`, `libtlp.TLPClient.FTYPE_CODE_DOCUMENT`,
           `libtlp.TLPClient.FTYPE_CODE_THUMBNAIL`, `libtlp.TLPClient.FTYPE_CODE_SUBS`,
           `libtlp.TLPClient.FTYPE_CODE_AUDIOTRACK`,
           `libtlp.TLPClient.FTYPE_CODE_WAVEFORM`.

	   In case **_file_type_code_** = `libtlp.TLPClient.FTYPE_CODE_SUBS`
           or **_file_type_code_** = `libtlp.TLPClient.FTYPE_CODE_AUDIOTRACK`, **_language_** and **_human_**
           arguments are mandatory. The first one is the  requested subtitles language
           code in ISO 639-1 format (e.g.  "en", "es"), while **_human_** is a boolean
           variable indicationg whether the provided subtitles or audiotrack have been
           produced by a human, or have been generated automatically by a computer.

	   **Note:** The `libtlp.TLPClient.manifest` object should have been
           initialised before with a `libtlp.TLPClient.manifest_init` call. This method
           should be executed before calling the `libtlp.TLPClient.api_ingest` method.
        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        at = {}
        at['filename'] = self.__get_file_name(uri)
        at['fileformat'] = self.__get_file_format(uri)
        at['md5'] = self.__md5sum(uri)
        at['type_code'] = file_type_code
        if language != None: at['language'] = language
        if human != None: at['human'] = human
        try:
            self.manifest['attachments'].append(at)
        except:
            self.manifest['attachments'] = [at]
        self.__manifest_files.append(uri)

   
    def manifest_add_subtitles_request(self, language, system_id=None, lm_adapt=None, tl_path=None):
        """Request subtitles language in the "requested_langs" option of the `libtlp.TLPClient.manifest` JSON object.

           **_language_** is the requested subtitles language code in ISO 639-1 format (e.g.
           "en", "es").

	   Some advanced options can be provided to the Ingest Service for
           subtitles generation. **_system_id_** must be an integer value indicating the
           System ID to use, **_lm_adapt_** is a boolean variable to enable or disable the
           Language Model Adaptation technique, and **_tl_path_** must be a list of tuples
           (language, system_id) describing an alternative translation path. In this
           latter case, system_id is optional and must be set to None if is not provided. 

	   **Note:** The `libtlp.TLPClient.manifest` object should have been
           initialised before with a `libtlp.TLPClient.manifest_init` call. This method
           should be executed before calling the `libtlp.TLPClient.api_ingest` method.
        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        if 'requested_langs' not in self.manifest:
            self.manifest['requested_langs'] = {}
        if language not in self.manifest['requested_langs']:
            self.manifest['requested_langs'][language] = {}
        d = {}
        if tl_path != None:
            p = []
            for s in tl_path: # is a tuple (langcode, systemId=None)
                ds = {}
                ds['l'] = s[0]
                if s[1] != None: ds['sid'] = s[1]
                p.append(ds)
            d['tlpath'] = p
        else:
            if system_id != None: d['sid'] = system_id
            if lm_adapt != None: d['lma'] = lm_adapt
        self.manifest['requested_langs'][language]['sub'] = d 


    def manifest_add_audiotrack_request(self, language, system_id=None):
        """Request audiotrack language in the "requested_langs" option of the `libtlp.TLPClient.manifest` JSON object.

           **_language_** is the requested audiotrack language code in ISO 639-1 format (e.g.
           "en", "es").

	   Some advanced options can be provided to the Ingest Service for
           subtitles generation. **_system_id_** must be an integer value indicating the
           System ID to use.

	   **Note:** The `libtlp.TLPClient.manifest` object should have been
           initialised before with a `libtlp.TLPClient.manifest_init` call. This method
           should be executed before calling the `libtlp.TLPClient.api_ingest` method.
        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        if 'requested_langs' not in self.manifest:
            self.manifest['requested_langs'] = {}
        if language not in self.manifest['requested_langs']:
            self.manifest['requested_langs'][language] = {}
        d = {}
        if system_id != None: d['sid'] = system_id
        self.manifest['requested_langs'][language]['tts'] = d
        

    def manifest_set_options(self, transLecture=None, tL_regenerate=None, tL_force=None, delete_mode=None, test_mode=None):
        """Set Ingest Service options to the `libtlp.TLPClient.manifest` JSON object.

           **_transLecture_** is a boolean variable to enable/disable transcription and translation technologies.

	   On `libtlp.TLPClient.INGEST_OPCODE_UPDATE` operations,
           **_tL_regenerate_** option can be used to request a regeneration of
           transcriptions, translations and/or synthesized audiotracks.  Must be a list of
           keywords. Allowed Keywords are: *tx* (request regeneration of the media
           transcription), *tl* (request regeneration of media translations), *tts*
           (request regeneration of synthesized audiotracks). Also, if **_tL_force_** = *True*, 
           regeneration of automatic subtitles is forced even if there exist human-supervised subtitles.

           For the `libtlp.TLPClient.INGEST_OPCODE_DELETE` operation, the
           **_delete_mode_** argument defines the delete mode. Delete modes can be: *hard*
           (default) and *soft*.

           Finally, the **_test_mode_** argument is a boolean variable to enable/disable the Test Mode of the Ingest Service. 
           When enabled, the uploaded media will be available inmediately with an empty subtitles file. 
           This feature is very useful when executing integration tests with the /ingest interface. By default it is disabled.

	   **Note:** The `libtlp.TLPClient.manifest` object should have been
           initialised before with a `libtlp.TLPClient.manifest_init` call. This method
           should be executed before calling the `libtlp.TLPClient.api_ingest` method.
        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        if transLecture != None: self.manifest['transLecture'] = int(transLecture)
        if tL_regenerate!= None: self.manifest['tL-regenerate'] = tL_regenerate
        if tL_force != None: self.manifest['tL-force'] = int(tL_force)
        if delete_mode != None: self.manifest['delete_mode'] = delete_mode
        if test_mode != None: self.manifest['test_mode'] = test_mode


    def create_media_package(self, dest=None):
        """Creates a Media Package File from the `libtlp.TLPClient.manifest` JSON object information, returning the location of the zip package.

	   By default the media package file is created and stored in a
           temporal directory, unless you specify the destination file path with the
           optional parameter **_dest_**.
        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        self.__tmp_dir = tempfile.mkdtemp()
        manif_fp = "%s/manifest.json" % self.__tmp_dir
        with open(manif_fp,'w') as fd:
            fd.write(json.dumps(self.manifest, indent=4, separators=(',', ': '), encoding="UTF-8", ensure_ascii=False).encode('utf-8'))
        self.__manifest_files.append(manif_fp)
        if dest == None:
            dest = "%s/mpf.zip" % self.__tmp_dir
        zf = zipfile.ZipFile(dest, mode='w')
        for f in self.__manifest_files: 
            zf.write(f, arcname=self.__get_file_name(f))
        zf.close()
        return dest


    def api_ingest(self, media_package_file=None, external_id=None, operation_code=None, email=None, su=None):
      """ Performs an API call to the /ingest interface: 

	  > *Upload media (audio/video) files and many other attachments and
	  > metadata to the TLP Server for automatic multilingual subtitling
	  > and speech synthesization.*

	  If **_media_package_file_** is not provided, then it is generated
          automatically by calling the `libtlp.TLPClient.create_media_package` method. In
          this latter case, it is assumed that at least a manifest file has been
          initialised before with the `libtlp.TLPClient.manifest_init` method.

	  By default, /ingest API call parameters *id* and *opc* are retrieved
          from the `libtlp.TLPClient.manifest` JSON object, but they can be overrided with
          the optional arguments **_external_id_** and **_operation_code_**,
          respectively. However, both arguments become mandatory in case a
          **_media_package_file_** is provided.

	  Optionally, you can provide an **_email_** addressto send
          notifications about status updates of the Ingest Service.
  
	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/ingest'
      if media_package_file != None:
          mp_fp = media_package_file
      else:
          mp_fp = self.create_media_package()
      data = open(mp_fp, 'rb').read()
      self.parameters['id'] = external_id if external_id != None else self.manifest['metadata']['external_id']
      self.parameters['opc'] = operation_code if operation_code != None else self.manifest['operation_code']
      if email != None: self.parameters['email'] = email
      if su != None: self.parameters['su'] = su
      self.__set_auth_parameters_secret_key()
      self.__call_ingest(url, data)
      self.__last_api_call = "ingest"
      if self.debug: 
          self.__generate_debug_info_api(url)
      else:
          if self.__tmp_dir != None:
              shutil.rmtree(self.__tmp_dir)
    

    def api_systems(self, su=None):
      """ Performs an API call to the /systems interface:

	  > *Get a list of all available Speech Recognition, Machine
	  > Translation, and Text-To-Speech Systems that can be applied to
	  > transcribe, translate, and synthesize a media file.*

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/systems'
      if su != None: self.parameters['su'] = su
      self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "systems"
      if self.debug: self.__generate_debug_info_api(url)
  
    def api_uploadslist(self, object_id=None, su=None):
      """ Performs an API call to the /uploadslist interface:

          > *Get a list of all user's uploads.*

	  If the optional **_object_id_** argument is given, then the Web
          Service will return a list of uploads involving the provided object ID (could
          be an Upload ID or a Media ID).

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/uploadslist'
      if object_id != None: self.parameters['object_id'] = object_id
      if su != None: self.parameters['su'] = su
      self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "uploadslist"
      if self.debug: self.__generate_debug_info_api(url)
      
 
    def api_status(self, oid, su=None):
      """ Performs an API call to the /status interface:

          > *Check the current status of a specific upload ID.*

          **_oid_** is an upload ID, returned by the /ingest interface.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/status'
      self.parameters['id'] = oid
      if su != None: self.parameters['su'] = su
      self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "status"
      if self.debug: self.__generate_debug_info_api(url)
    

    def api_langs(self, oid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /langs interface:

          > *Get a list of all subtitle and audiotrack languages available for a given media ID.*
      
          The **_oid_** parameter is the Media ID. 

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/langs'
      self.parameters['id'] = oid
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "langs"
      if self.debug: self.__generate_debug_info_api(url)
     
    def api_metadata(self, oid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /metadata interface:

          > *Get metadata and media file locations for a given media ID.*

          The **_oid_** parameter is the Media ID. 

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/metadata'
      self.parameters['id'] = oid
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "metadata"
      if self.debug: self.__generate_debug_info_api(url)
      

    def api_subs(self, oid, lang, form=None, seldata=None, segfilt=None, session_id=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /subs interface:

          > *Download current subtitles file for a given media ID and language.*

	  The **_oid_** parameter is the Media ID, and **_lang_** is the
          language code (ISO 639-1) of the requested subtitles language.

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

          The **_format_** optional parameter sets the downloaded subtitles format.
          Possbile formats are: *dfxp* (default), *srt*, *ttml*, *vtt*, *text*.

	  **_seldata_** and **_segfilt_** are also optional parameters
          corresponding to the *sel_data_policy* and *seg_filt_policy* API call
          parameters.  

	  On the one hand, **_seldata_** defines which subtitle contents are returned. Possible
          values are: *`libtlp.TLPClient.SUBS_SELDATA_ALL`*,
          *`libtlp.TLPClient.SUBS_SELDATA_FORMER`*,
          *`libtlp.TLPClient.SUBS_SELDATA_CURRENT`*.

	  On the other hand, **_segfilt_** specifies the segment text filtering
          policy. Possible values are: *`libtlp.TLPClient.SUBS_SEGFILT_EMTPY`*,
          *`libtlp.TLPClient.SUBS_SEGFILT_DISABLE`*,
          *`libtlp.TLPClient.SUBS_SEGFILT_ENABLE`*.

          A **_session_id_** argument can be provided in order to apply subtitle modifications made under the given edit session ID to the subtitles file.
 
          For further details of both API call parameters please check the full TLP API documentation.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/subs'
      Dformats = { 'dfxp':0, 'ttml':1, 'srt':2, 'vtt':3, 'text':4 }
      self.parameters['id'] = oid
      self.parameters['lang'] = lang
      if form != None: self.parameters['format'] = Dformats[form]
      if seldata != None: self.parameters['sel_data_policy'] = seldata
      if segfilt != None: self.parameters['seg_filt_policy'] = segfilt
      if session_id != None: self.parameters['session_id'] = session_id
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "subs"
      if self.debug: self.__generate_debug_info_api(url)

      
    def api_audiotrack(self, oid, lang, aid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /audiotrack interface:

          > *Download an audiotrack file for a given media ID and language.*

          The **_oid_** parameter is the Media ID, **_lang_** is the
          language code (ISO 639-1) of the requested audiotrack language, and
          **_aid_** is the audiotrack ID (retrieved from the /metadata interface).

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/audiotrack'
      self.parameters['id'] = oid
      self.parameters['lang'] = lang
      self.parameters['aid'] = aid
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "audiotrack"
      if self.debug: self.__generate_debug_info_api(url)

 
    def api_start_session(self, oid, author_id, author_conf, author_name=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /start_session interface:

          > *Starts an edition session to send and commit modifications of a subtitles file.*

          The **_oid_** parameter is the Media ID, **_author_id_** is the ID of
          the user that will edit the subtitles (typically the internal user ID that the
          API client's organisation assigns to the user), and **_author_conf_** is an
          integer value (range 0-100) that indicates the confidence level that the API
          client's organisation provide to the user.

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/start_session'
      self.parameters['id'] = oid
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      if author_name != None:  self.parameters['author_name'] = author_name
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "start_session"
      if self.debug: self.__generate_debug_info_api(url)
      if self.ret_data['rcode'] == 0:
          self.__api_mod_session_id = self.ret_data['session_id']
 
      
    def api_session_status(self, oid, author_id, author_conf, session_id=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /session_status interface:

          > *Returns the current status of the given session ID. If it is alive, it updates the last alive timestamp. This interface is commonly used to avoid the automatic end of session due to user inactivity.*

	  By default, the session ID will be the one returned after calling the
          */start_session* (`libtlp.TLPClient.start_session`) interface. However, an alternative session ID can be
	  provided via the optional **_session_id_** argument.

          The **_oid_** parameter is the Media ID, **_author_id_** is the ID of
          the user that will edit the subtitles (typically the internal user ID that the
          API client's organisation assigns to the user), and **_author_conf_** is an
          integer value (range 0-100) that indicates the confidence level that the API
          client's organisation provide to the user.

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/session_status'
      self.parameters['id'] = oid
      if session_id != None:
          self.parameters['session_id'] = session_id
      elif self.__api_mod_session_id != None:
          self.parameters['session_id'] = self.__api_mod_session_id
      else:
          raise TLPException("You must start an edit session to check session status (see api_start_session()), or to manually provide a session ID (session_id optional argument).")
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "session_status"
      if self.debug: self.__generate_debug_info_api(url)
 

    def api_mod(self, oid, lang, author_id, author_conf, txt_array, del_array, author_name=None, session_id=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1, data=None):
      """ Performs an API call to the /mod interface:

          > *Send and commit subtitle corrections made by a user under an edit session ID.*

	  By default, the session ID will be the one returned after calling the
          */start_session* (`libtlp.TLPClient.start_session`) interface. However, an alternative session ID can be
	  provided via the optional **_session_id_** argument.

	  The **_oid_** parameter is the Media ID, **_lang_** is the language
          code (ISO 639-1) of the edited subtitles language, **_author_id_** is the ID of
          the user that will edit the subtitles (typically the internal user ID that the
          API client's organisation assigns to the user), and **_author_conf_** is an
          integer value (range 0-100) that indicates the confidence level that the API
          client's organisation provide to the user.

          **_txt_array_** is a list of JSON dictionaries, where each dictionary contains the following segment edition information:

 
                         {"sI":<int>, "b":<float>, "e":<float>, "t":<str>}


          **sI** is the segment ID, **b** is the segment start time, **e** is the segment end time, and **t** is the updated segment text.
          **_txt_array_** must be an empty list if no segments where modified.

          **_del_array_** is a list containing the segment IDs (int values) to delete. It must be an empty list if no segments are being deleted.

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.

	  Alternatively, you can provide a base64-encoded JSON data parameter
          value with all required /mod parameters. In this case, all mandatory arguments can be
          set to *None*, because they are ignored.
      """
      self.__reset()
      url = self.__api_base_url+'/mod'
      if data != None:
          self.parameters = json.loads(base64.b64decode(data), encoding='utf-8')
      else:
          self.parameters['id'] = oid
          if session_id != None:
              self.parameters['session_id'] = session_id
          elif self.__api_mod_session_id != None:
              self.parameters['session_id'] = self.__api_mod_session_id
          else:
              raise TLPException("You must start an edit session to send subtitle modifications (see api_start_session()), or to manually provide a session ID (session_id optional argument).")
          self.parameters['author_id'] = author_id
          self.parameters['author_conf'] = author_conf
          self.parameters['mods'] = { lang: { 'txt':[], 'del':[] } }
          if author_name != None:  self.parameters['author_name'] = author_name
          if txt_array != None: self.parameters['mods'][lang]['txt'] = txt_array
          if del_array != None: self.parameters['mods'][lang]['del'] = del_array
          if vhash != None: self.parameters['hash'] = vhash
          if su != None: self.parameters['su'] = su
          if self.use_get_method and not(self.use_data_parameter): self.parameters['mods'] = base64.b64encode(json.dumps(self.parameters['mods'], encoding='utf-8'))
          if use_req_key:
              self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
          else:
              self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "mod"
      if self.debug: self.__generate_debug_info_api(url)
  
    def api_end_session(self, oid, author_id, author_conf, author_name=None, session_id=None, force=False, regenerate=True, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /end_session interface:

          > *Ends an existing edition session.*

	  By default, the session ID will be the one returned after calling the
          */start_session* (`libtlp.TLPClient.start_session`) interface. However, an alternative session ID can be
	  provided via the optional **_session_id_** argument.

          The **_oid_** parameter is the Media ID, **_author_id_** is the ID of
          the user that will edit the subtitles (typically the internal user ID that the
          API client's organisation assigns to the user), and **_author_conf_** is an
          integer value (range 0-100) that indicates the confidence level that the API
          client's organisation provide to the user.

	  **_force_** option should set to *True* to force the end of a session when
          the given **_author_id_** or API user are not the same that started the given
          **_session_id**.

          The **_regenerate_** option tells to the TLP Server if subtitles and/or synthesized audiotracks will be
          regenerated after ending the session. By default it is set to *True*.

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/end_session'
      self.parameters['id'] = oid
      if session_id != None:
          self.parameters['session_id'] = session_id
      elif self.__api_mod_session_id != None:
          self.parameters['session_id'] = self.__api_mod_session_id
      else:
          raise TLPException("You must start an edit session to send subtitle modifications (see api_start_session()), or to manually provide a session ID (session_id optional argument).")
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      self.parameters['force'] = int(force)
      self.parameters['regenerate'] = int(regenerate)
      if author_name != None:  self.parameters['author_name'] = author_name
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "end_session"
      if self.debug: self.__generate_debug_info_api(url)
      if self.ret_data['rcode'] == 0:
          self.__api_mod_session_id = None
       
    def api_lock_subs(self, oid, lock, author_id, author_conf, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /lock_subs interface:

          > *Allow/disallow regular users to send subtitles modifications for an specific Media ID.*

          The **_oid_** parameter is the Media ID, **_author_id_** is the ID of
          the user that will edit the subtitles (typically the internal user ID that the
          API client's organisation assigns to the user), and **_author_conf_** is an
          integer value (range 0-100) that indicates the confidence level that the API
          client's organisation provide to the user.

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      if not(isinstance(lock, bool)):
          raise TLPException("lock must be a boolean.")
      self.__reset()
      url = self.__api_base_url+'/lock_subs'
      self.parameters['id'] = oid
      self.parameters['lock'] = int(lock)
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "lock_subs"
      if self.debug: self.__generate_debug_info_api(url)

       
    def api_edit_history(self, oid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /edit_history interface:

          > *Returns a list of all edit sessions carried out over an specific Media ID.*

	  The **_oid_** parameter is the Media ID. Optionally, a media hash
          value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/edit_history'
      self.parameters['id'] = oid
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "edit_history"
      if self.debug: self.__generate_debug_info_api(url)
  
    def api_mark_revised(self, oid, session_id, author_id, author_conf, author_name=None, revision_session_id=None, unmark=False, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /mark_revised interface:

          > *Mark/unmark an edition session as revised.*

	  **_session_id_** is the Session ID to mark/unmark as revised,
          the **_oid_** parameter is the Media ID, **_author_id_** is the ID of
          the user that will edit the subtitles (typically the internal user ID that the
          API client's organisation assigns to the user), and **_author_conf_** is an
          integer value (range 0-100) that indicates the confidence level that the API
          client's organisation provide to the user.
 
          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      if not(isinstance(unmark, bool)):
          raise TLPException("unmark must be a boolean.")
      self.__reset()
      url = self.__api_base_url+'/mark_revised'
      self.parameters['id'] = oid
      self.parameters['session_id'] = session_id
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      self.parameters['unmark'] = int(unmark)
      if author_name != None:  self.parameters['author_name'] = author_name
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "mark_revised"
      if self.debug: self.__generate_debug_info_api(url)
 
    def api_accept(self, ids, author_id, author_conf, author_name=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /accept interface:

          > *Accept modifications of one or more pending edit sessions without having to revise them.*

	  
	  The **_ids_** parameter must be a list Session IDs whose edits are
          meant to be accepted by the given Author ID.  **_author_id_** is the ID of the
          user that will edit the subtitles (typically the internal user ID that the API
          client's organisation assigns to the user), and **_author_conf_** is an integer
          value (range 0-100) that indicates the confidence level that the API client's
          organisation provide to the user.
 
          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      if not(isinstance(ids, list)):
          raise TLPException("ids must be a list.")
      self.__reset()
      url = self.__api_base_url+'/accept'
      self.parameters['id'] = ",".join([ str(x) for x in ids ])
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      if author_name != None:  self.parameters['author_name'] = author_name
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "accept"
      if self.debug: self.__generate_debug_info_api(url)
 
    def api_reject(self, ids, author_id, author_conf, author_name=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /reject interface:

          > *Reject modifications of one or more pending edit sessions without having to revise them.*

	  
	  The **_ids_** parameter must be a list Session IDs whose edits are
          meant to be rejected by the given Author ID.  **_author_id_** is the ID of the
          user that will edit the subtitles (typically the internal user ID that the API
          client's organisation assigns to the user), and **_author_conf_** is an integer
          value (range 0-100) that indicates the confidence level that the API client's
          organisation provide to the user.
 
          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      if not(isinstance(ids, list)):
          raise TLPException("ids must be a list.")
      self.__reset()
      url = self.__api_base_url+'/reject'
      self.parameters['id'] = ",".join([ str(x) for x in ids ])
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      if author_name != None:  self.parameters['author_name'] = author_name
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "reject"
      if self.debug: self.__generate_debug_info_api(url)

    def api_revisions(self, su=None):
      """ Performs an API call to the /revisions interface:

          > *Returns a list of all edit sessions for all API user's media files that are pending to be revised.*

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/revisions'
      if su != None: self.parameters['su'] = su
      self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "revisions"
      if self.debug: self.__generate_debug_info_api(url)
 
    def generate_player_url(self, oid, author_id, author_conf, session_id=None, req_key_lifetime=1440, language=None, author_name=None, start=None):
      """ Returns a valid TLP Player URL.

	  **_oid_** is the Media ID, **_author_id_** is the ID of the user that
          will edit the subtitles (typically the internal user ID that the API client's
          organisation assigns to the user), and **_author_conf_** is an integer value
          (range 0-100) that indicates the confidence level that the API client's
          organisation provide to the user. 

	  Optionally, a **_language_** ISO-639-1 code can be provided to make
          the Player load directly the specified subtitles language (if not provided, the
          Player will load the source language transcriptions). Also, you can set the
          media start time in seconds with the **_start_** parameter.

          The full name of the user that will edit the subtitles can be provided with the parameter **_author_name**.

          A **_session_id_** argument can be provided in order review subtitle modifications made under the provided edit session ID.

	  Finally, you can adjust de lifetime duration in minutes of the
          generated URL using the option **_req_key_lifetime_**. By default is set to 24
          hours (1440 minutes).
      """
      self.__reset()
      self.parameters['id'] = oid
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      if language != None: self.parameters['language'] = language
      if author_name != None: self.parameters['author_name'] = author_name
      if session_id != None: self.parameters['session_id'] = session_id
      self.__set_auth_parameters_request_key_player(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      if self.debug: self.__generate_debug_info_player()
      request_parameter = base64.b64encode(json.dumps(self.parameters, encoding='UTF-8'))
      url = "%s?request=%s" % (self.__player_base_url, request_parameter)
      if start != None:
        url += "&t=%d" % int(start)
      return url

class TLPException(Exception):
    """Generic TLP Exception"""
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return self.msg
 
class APIBadRequest(TLPException):
    """Exception that is raised when the TLP Web Service returns a "400 Bad Request" HTTP error code."""

    def __str__(self):
        string = 'TLP Web Service retuned a "400 Bad Request" HTTP error code'
        if self.msg.strip() != "":
            string = '%s: \n\n%s\n' % (string, self.msg)
        else:
            string = '%s.' % string
        return string
 
class APIUnauthorized(TLPException):
    """Exception that is raised when the TLP Web Service returns a "401 Unauthorized" HTTP error code."""

    def __str__(self):
        string = 'TLP Web Service retuned a "401 Unautorized" HTTP error code (please check your API credentials)'
        if self.msg.strip() != "":
            string = '%s: \n\n%s\n' % (string, self.msg)
        else:
            string = '%s.' % string
        return string
  
class APIAuthenticationTimeout(TLPException):
    """Exception that is raised when the TLP Web Service returns a "419 Authentication Timeout" HTTP error code."""

    def __str__(self):
        string = 'TLP Web Service retuned a "419 Authentication Timeout" HTTP error code'
        if self.msg.strip() != "":
            string = '%s: \n\n%s\n' % (string, self.msg)
        else:
            string = '%s.' % string
        return string
   
class APIInternalServerError(TLPException):
    """Exception that is raised when the TLP Web Service returns a "500 Internal Server Error" HTTP error code."""

    def __str__(self):
        string = 'TLP Web Service retuned a "500 Internal Server Error" HTTP error code'
        if self.msg.strip() != "":
            string = '%s: \n\n%s\n' % (string, self.msg)
        else:
            string = '%s.' % string
        return string
 

Classes

class APIAuthenticationTimeout

Exception that is raised when the TLP Web Service returns a "419 Authentication Timeout" HTTP error code.

class APIAuthenticationTimeout(TLPException):
    """Exception that is raised when the TLP Web Service returns a "419 Authentication Timeout" HTTP error code."""

    def __str__(self):
        string = 'TLP Web Service retuned a "419 Authentication Timeout" HTTP error code'
        if self.msg.strip() != "":
            string = '%s: \n\n%s\n' % (string, self.msg)
        else:
            string = '%s.' % string
        return string

Ancestors (in MRO)

Class variables

var args

Inheritance: TLPException.args

var message

Inheritance: TLPException.message

Instance variables

var msg

Inheritance: TLPException.msg

Methods

def __init__(

self, msg)

Inheritance: TLPException.__init__

def __init__(self, msg):
    self.msg = msg

class APIBadRequest

Exception that is raised when the TLP Web Service returns a "400 Bad Request" HTTP error code.

class APIBadRequest(TLPException):
    """Exception that is raised when the TLP Web Service returns a "400 Bad Request" HTTP error code."""

    def __str__(self):
        string = 'TLP Web Service retuned a "400 Bad Request" HTTP error code'
        if self.msg.strip() != "":
            string = '%s: \n\n%s\n' % (string, self.msg)
        else:
            string = '%s.' % string
        return string

Ancestors (in MRO)

Class variables

var args

Inheritance: TLPException.args

var message

Inheritance: TLPException.message

Instance variables

var msg

Inheritance: TLPException.msg

Methods

def __init__(

self, msg)

Inheritance: TLPException.__init__

def __init__(self, msg):
    self.msg = msg

class APIInternalServerError

Exception that is raised when the TLP Web Service returns a "500 Internal Server Error" HTTP error code.

class APIInternalServerError(TLPException):
    """Exception that is raised when the TLP Web Service returns a "500 Internal Server Error" HTTP error code."""

    def __str__(self):
        string = 'TLP Web Service retuned a "500 Internal Server Error" HTTP error code'
        if self.msg.strip() != "":
            string = '%s: \n\n%s\n' % (string, self.msg)
        else:
            string = '%s.' % string
        return string

Ancestors (in MRO)

Class variables

var args

Inheritance: TLPException.args

var message

Inheritance: TLPException.message

Instance variables

var msg

Inheritance: TLPException.msg

Methods

def __init__(

self, msg)

Inheritance: TLPException.__init__

def __init__(self, msg):
    self.msg = msg

class APIUnauthorized

Exception that is raised when the TLP Web Service returns a "401 Unauthorized" HTTP error code.

class APIUnauthorized(TLPException):
    """Exception that is raised when the TLP Web Service returns a "401 Unauthorized" HTTP error code."""

    def __str__(self):
        string = 'TLP Web Service retuned a "401 Unautorized" HTTP error code (please check your API credentials)'
        if self.msg.strip() != "":
            string = '%s: \n\n%s\n' % (string, self.msg)
        else:
            string = '%s.' % string
        return string

Ancestors (in MRO)

Class variables

var args

Inheritance: TLPException.args

var message

Inheritance: TLPException.message

Instance variables

var msg

Inheritance: TLPException.msg

Methods

def __init__(

self, msg)

Inheritance: TLPException.__init__

def __init__(self, msg):
    self.msg = msg

class TLPClient

TLPClient class.

class TLPClient():

    """
    TLPClient class.
    """

    FTYPE_CODE_MEDIA = 0
    """Main Media file type code"""
    FTYPE_CODE_SLIDES = 1
    """Slides file type code code"""
    FTYPE_CODE_DOCUMENT = 2
    """Related Text Document file type code"""
    FTYPE_CODE_THUMBNAIL = 3
    """Media thumbnail file type code"""
    FTYPE_CODE_SUBS = 4
    """Subtitles file type code"""
    FTYPE_CODE_AUDIOTRACK = 5
    """Audiotrack file type code"""
    FTYPE_CODE_WAVEFORM = 6
    """Waveform file type code"""

    SUBS_SELDATA_ALL = 0
    """Subtitle contents to be returned: Return both former and current contents (only for DFXP format). """
    SUBS_SELDATA_FORMER = 1
    """Subtitle contents to be returned: Return former contents (automatic transcription or translation). """
    SUBS_SELDATA_CURRENT = 2
    """Subtitle contents to be returned: Return current contents (current status of supervision of the subtitles). """
    
    SUBS_SEGFILT_EMTPY = -1
    """Segment text filtering policy: Empty all segments (removes text from all segments). """
    SUBS_SEGFILT_DISABLE = 0
    """Segment text filtering policy: Filtering disabled. """
    SUBS_SEGFILT_ENABLE = 1
    """Segment text filtering policy: Filters out special annotations. """

    INGEST_OPCODE_NEW = 0
    """Ingest Service New Media Operation Code: A new media will be processed by the Ingest Service and inserted into database. """
    INGEST_OPCODE_UPDATE = 1
    """Ingest Service Update Media Operation Code: An existing media will be updated after processing the input data by the Ingest Service. """
    INGEST_OPCODE_DELETE = 2
    """Ingest Service Delete Media Operation Code: An existing media will be deleted from the database. """
    INGEST_OPCODE_CANCEL = 3
    """Ingest Service Cancel Upload Operation Code: An ongoing upload will be cancelled. """

    def __init__(self, api_base_url, player_base_url, api_user, api_secret_key):
        """
        Creates a TLPClient class instance. Parameters:

        - **_api_base_url_**: Base URL to the transLectures-UPV Platform's Web Service.
        - **_player_base_url_**: Base URL to the transLectures-UPV Platform's Player.
        - **_api_user_**: API username / TLP username.
        - **_api_secret_key_**: API Secret Key.
        """
        self.__manifest_files = None
        self.__last_api_call = None
        self.__tmp_dir = None
        self.__session = None
        self.__response = None
        self.__http_auth_enabled = False
        self.__http_user = None
        self.__http_pass = None
        self.__api_mod_session_id = None
        self.__api_base_url = api_base_url
        self.__player_base_url = player_base_url
        self.__api_user = api_user
        self.__api_secret_key = api_secret_key
        self.use_get_method = False
        """Use HTTP GET Method instead of POST."""
        self.use_data_parameter = True
        """Use a single "data" parameter on HTTP GET calls instead multiple GET parameters."""
        self.parameters = None
        """Dictionary with API query parameters."""
        self.ret_data = None
        """Data returned by the last performed API call. If the response was a JSON object, *ret_data* becomes a a parsed JSON object (dictionary or list, depending on the JSON)."""
        self.ret_content_type = None
        """Mime-type of the data returned by the last performed API call."""
        self.debug = False
        """Enable/Disable generation of debug information."""
        self.debug_info = None
        """Debug information of the last performed API call / Generation of Player URL."""
        self.manifest = None
        """Manifest JSON object."""

    def __reset_http_session(self):
        """Resets requests.Session class instance."""
        self.__session = requests.Session()
        if self.__http_auth_enabled:
            self.__session.auth = (self.__http_user, self.__http_pass)

    def __reset(self):
        """Reset all class methods to perform a new API call."""
        self.__reset_http_session()
        self.__response = None
        self.parameters = {}
        self.ret_data = None
        self.ret_content_type = None
        self.debug_info = None

    def __set_auth_parameters_secret_key(self):
        """Set API authentication parameters using the secret key."""
        self.parameters['user'] = self.__api_user
        self.parameters['auth_token'] = self.__api_secret_key

    def __set_auth_parameters_request_key_api(self, req_key_lifetime, oid, author=None, author_conf=None):
        """Set API authentication parameters using a request key for an API call."""
        self.parameters['user'] = self.__api_user
        expire = self.__gen_expire_parameter(req_key_lifetime)
        self.parameters['auth_token'] = self.gen_request_key(oid, expire, author, author_conf)
        self.parameters['expire'] = expire

    def __set_auth_parameters_request_key_player(self, req_key_lifetime, oid, author=None, author_conf=None):
        """Set API authentication parameters using a request key for generating a Player URL."""
        self.parameters['api_user'] = self.__api_user
        expire = self.__gen_expire_parameter(req_key_lifetime)
        self.parameters['request_key'] = self.gen_request_key(oid, expire, author, author_conf)
        self.parameters['expire'] = expire

    def __gen_expire_parameter(self, lifetime):
        """Returns a valid value of the "expire" API authentication parameter."""
        return int((datetime.utcnow() + timedelta(minutes=lifetime) - datetime(1970,01,01)).total_seconds())

    def __generate_debug_info_api(self, url):
        """ Generates debug information about the last API call."""
        o = cStringIO.StringIO()
        o.write("\n")
        o.write("- Input data (JSON-formatted):\n")
        o.write("%s\n" % json.dumps(self.parameters, encoding="UTF-8", indent=4))
        o.write("\n")
        if self.use_get_method:
          if self.use_data_parameter:
            o.write("- URL (using GET request with a single 'data' base64-encoded JSON parameter):\n")
            o.write("%s?data=%s\n" % (url, base64.b64encode(json.dumps(self.parameters, encoding="UTF-8"))))
            o.write("\n")
          else:
            o.write("- URL (using GET request with multiple parameters):\n")
            params = "&".join([ "%s=%s"%(k, str(self.parameters[k])) for k in self.parameters ])
            o.write("%s?%s\n" % (url, params))
            o.write("\n")
        else:
          o.write("- URL + POST data parameter:\n")
          o.write("%s\n" % url)
          o.write("%s\n" % base64.b64encode(json.dumps(self.parameters, encoding="UTF-8")))
        if self.__last_api_call == "ingest":
          if self.manifest != None:
            o.write("\n- Manifest.JSON file:\n")
            o.write("%s\n" % self.get_printable_manifest())
            o.write("\n")
          if self.__tmp_dir != None:
            o.write("- Temp dir: %s\n" % self.__tmp_dir)
        self.debug_info = o.getvalue()
 
    def __generate_debug_info_player(self):
        """ Generates debug information about the last generated Player URL."""
        o = cStringIO.StringIO()
        o.write("\n")
        o.write("- Input data (JSON-formatted):\n")
        o.write("%s\n" % json.dumps(self.parameters, encoding="UTF-8", indent=4))
        o.write("\n")
        o.write("- Input data (Base 64):\n")
        o.write("%s\n" % base64.b64encode(json.dumps(self.parameters, encoding="UTF-8")))
        o.write("\n")
        self.debug_info = o.getvalue()

    
    def __parse_response(self):
        if self.__response.status_code == 200:
            self.ret_content_type = self.__response.headers['content-type']
            if self.ret_content_type.find("application/json") >= 0:
                self.ret_data = json.loads(self.__response.content)
            else:
                self.ret_data = self.__response.content
        elif self.__response.status_code == 400:
            raise APIBadRequest(self.__response.content)
        elif self.__response.status_code == 401:
            raise APIUnauthorized(self.__response.content)
        elif self.__response.status_code == 419:
            raise APIAuthenticationTimeout(self.__response.content)
        elif self.__response.status_code == 500:
            raise APIInternalServerError(self.__response.content)
        
   
    def __call(self, url):
        """ Call the specified url using with the parameters determined by the "parameters" class attribute."""
        if self.use_get_method:
            if self.use_data_parameter:
                data = base64.b64encode(json.dumps(self.parameters, encoding="UTF-8"))
                par = {'data':data}
            else:
                par = self.parameters
            self.__response = self.__session.get(url=url,params=par)
        else:
            data = base64.b64encode(json.dumps(self.parameters, encoding="UTF-8"))
            self.__response = self.__session.post(url=url,data=data)
        self.__parse_response()

     
    def __call_ingest(self, url, data):
        """ Call the specified url (ingest interface) using with the parameters determined by the "parameters" class attribute."""
        if self.use_data_parameter:
            json_data = base64.b64encode(json.dumps(self.parameters, encoding="UTF-8"))
            par = {'data':json_data}
        else:
            par = self.parameters
        self.__response = self.__session.post(url=url,data=data,headers={'Content-Type': 'application/zip'},params=par)
        self.__parse_response()


    def __is_url(self, url):
        try:
            myurl = urllib2.urlopen(url).geturl()
        except: 
            return False
        return True

 
    def __get_file_format(self, fp):
        return os.path.splitext(fp)[1][1:]


    def __get_file_name(self, fp):
        return os.path.basename(fp)


    def __md5sum(self, fp):
        md5 = hashlib.md5()
        with open(fp, 'rb') as f:
            for chunk in iter(lambda: f.read(128 * md5.block_size), b''):
                md5.update(chunk)
        return md5.hexdigest()

    def enable_http_auth(self, http_user, http_pass):
        """Use HTTP Authentication for all API calls.
           
           **_http_user_** is the HTTP Authentication username, while **_http_pass_** is the corresponding user password.
        """
        self.__http_user = http_user
        self.__http_pass = http_pass
        self.__http_auth_enabled = True


    def disable_http_auth(self):
        """Disable HTTP Authentication for all API calls"""
        self.__http_user = None
        self.__http_pass = None
        self.__http_auth_enabled = False


    def gen_request_key(self, oid, expire, author=None, author_conf=None):
        """Returns a valid request key to be used as an API authentication token.

	   **_oid_** is the object ID that will be queried (*id* API call
           parameter), and **_expire_** is the UNIX timestamp of the expiration time of
           the key. With these two parameters is generated the *basic request key*.
   
           If **_author_** (*author_id* API parameter) is supplied, then the *full request key* is generated 
           using this parameter plus **_author_conf_** (*author_conf* API parameter).

        """
        s1 = hashlib.sha1()
        s1.update(oid + str(expire) + self.__api_user + self.__api_secret_key)
        rk = s1.hexdigest()
        if author != None:
          s2 = hashlib.sha1()
          s2.update(author + str(author_conf) + str(expire) + self.__api_user + self.__api_secret_key)
          rk += s2.hexdigest()
        return rk


    def get_printable_response_data(self):
         """Returns a printable, user friendly version of the response data from the 
            last API call (stored in the `libtlp.TLPClient.ret_data` class member).
         """
         if self.ret_data == None:
            raise TLPException("No response data available (have you called any API interface before?).")
         if self.ret_content_type.find("application/json") >= 0:
             return json.dumps(self.ret_data, indent=4)
         else:
             return self.ret_data


    def get_printable_manifest(self):
         """Returns a printable, user friendly version of the manifest JSON object (stored in the `libtlp.TLPClient.manifest` class member).
         """
         if self.manifest != None:
             return json.dumps(self.manifest, indent=4)
         else:
             raise TLPException("Manifest file was not initialized.")


    def save_response_data(self, dest):
         """Saves the response data from the last API call (stored in the `libtlp.TLPClient.ret_data` 
            class member) into the destination **_dest_** file.
         """
         with open(dest,'wb') as fd:
             fd.write(self.get_printable_response_data())


    def manifest_init(self, operation_code, external_id):
        """Initalize the `libtlp.TLPClient.manifest` JSON object.

	   Allowed **_operation_code_** values are: `libtlp.TLPClient.INGEST_OPCODE_NEW`,
           `libtlp.TLPClient.INGEST_OPCODE_UPDATE`,
           `libtlp.TLPClient.INGEST_OPCODE_DELETE`,
           `libtlp.TLPClient.INGEST_OPCODE_CANCEL`.

           **_external_id_** must be a Media ID or an existing upload ID if **_operation_code_** is `libtlp.TLPClient.INGEST_OPCODE_CANCEL`.

           **Note:** This method should be executed before calling the `libtlp.TLPClient.api_ingest` method and any *manifest_\** class methods.
        """
        self.__tmp_dir = None
        self.__manifest_files = []
        self.manifest = {}
        self.manifest['operation_code'] = operation_code
        self.manifest['metadata'] = {}
        self.manifest['metadata']['external_id'] = external_id


    def manifest_set_metadata(self, language=None, title=None, topic=None, keywords=None, date=None):
        """Set metadata in the `libtlp.TLPClient.manifest` JSON object.

	   **_language_** is the Media language code in ISO 639-1 format (e.g.
           "en", "es"), **_title_** is the title of the media, **_topic_** is the topic of
           the media, **_keywords_** are the media keywords, and **_date_** is the
           publication date of the media. 

	   All arguments are optional, but **_language_** and **_title_**
           arguments are mandatory for `libtlp.TLPClient.INGEST_OPCODE_NEW` operations.

	   **Note:** The `libtlp.TLPClient.manifest` object should have been
           initialised before with a `libtlp.TLPClient.manifest_init` call. This method
           should be executed before calling the `libtlp.TLPClient.api_ingest` method.

        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        if language != None:
            self.manifest['metadata']['language'] = language
        if title != None:
            self.manifest['metadata']['title'] = title
        if topic != None:
            self.manifest['metadata']['topic'] = topic
        if keywords != None:
            self.manifest['metadata']['keywords'] = keywords
        if date != None:
            self.manifest['metadata']['date'] = date
        
   
    def manifest_add_speaker(self, speaker_id, speaker_name, email=None, gender=None):
        """Add a speaker in the metadata section of the `libtlp.TLPClient.manifest` JSON object.

	   **_speaker_id_** is the speaker ID of the media file, **_speaker_name_** is
           the full name of the speaker, **_email_** is the e-mail of the speaker, and
           **_gender_** is the gender of the speaker (*M* for Male or *F* for Female).
           **_email_** and **_gender_** are optional.

	   **Note:** The `libtlp.TLPClient.manifest` object should have been
           initialised before with a `libtlp.TLPClient.manifest_init` call. This method
           should be executed before calling the `libtlp.TLPClient.api_ingest` method.
        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        spk = {}
        spk['speaker_id'] = speaker_id
        spk['speaker_name'] = speaker_name
        if gender != None: spk['speaker_gender'] = gender
        if email != None: spk['speaker_email'] = email
        try:
            self.manifest['metadata']['speakers'].append(spk)
        except:
            self.manifest['metadata']['speakers'] = [spk]


    def manifest_set_main_media_file(self, uri):
        """Set main media file in the `libtlp.TLPClient.manifest` JSON object.

           **_uri_** can be a media file path o a media URL.

	   **Note:** The `libtlp.TLPClient.manifest` object should have been
           initialised before with a `libtlp.TLPClient.manifest_init` call. This method
           should be executed before calling the `libtlp.TLPClient.api_ingest` method.
        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        self.manifest['media'] = {}
        if self.__is_url(uri):
            self.manifest['media']['url'] = uri
        else:
            self.manifest['media']['filename'] = self.__get_file_name(uri)
            self.manifest['media']['fileformat'] = self.__get_file_format(uri)
            self.manifest['media']['md5'] = self.__md5sum(uri)
            self.__manifest_files.append(uri)

            
    def manifest_add_attachment(self, uri, file_type_code, language=None, human=None):
        """Add attachment file to the `libtlp.TLPClient.manifest` JSON object.

	   **_uri_** is the attachment file path, and **_file_type_code_** must be one of
           the following values: `libtlp.TLPClient.FTYPE_CODE_MEDIA`,
           `libtlp.TLPClient.FTYPE_CODE_SLIDES`, `libtlp.TLPClient.FTYPE_CODE_DOCUMENT`,
           `libtlp.TLPClient.FTYPE_CODE_THUMBNAIL`, `libtlp.TLPClient.FTYPE_CODE_SUBS`,
           `libtlp.TLPClient.FTYPE_CODE_AUDIOTRACK`,
           `libtlp.TLPClient.FTYPE_CODE_WAVEFORM`.

	   In case **_file_type_code_** = `libtlp.TLPClient.FTYPE_CODE_SUBS`
           or **_file_type_code_** = `libtlp.TLPClient.FTYPE_CODE_AUDIOTRACK`, **_language_** and **_human_**
           arguments are mandatory. The first one is the  requested subtitles language
           code in ISO 639-1 format (e.g.  "en", "es"), while **_human_** is a boolean
           variable indicationg whether the provided subtitles or audiotrack have been
           produced by a human, or have been generated automatically by a computer.

	   **Note:** The `libtlp.TLPClient.manifest` object should have been
           initialised before with a `libtlp.TLPClient.manifest_init` call. This method
           should be executed before calling the `libtlp.TLPClient.api_ingest` method.
        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        at = {}
        at['filename'] = self.__get_file_name(uri)
        at['fileformat'] = self.__get_file_format(uri)
        at['md5'] = self.__md5sum(uri)
        at['type_code'] = file_type_code
        if language != None: at['language'] = language
        if human != None: at['human'] = human
        try:
            self.manifest['attachments'].append(at)
        except:
            self.manifest['attachments'] = [at]
        self.__manifest_files.append(uri)

   
    def manifest_add_subtitles_request(self, language, system_id=None, lm_adapt=None, tl_path=None):
        """Request subtitles language in the "requested_langs" option of the `libtlp.TLPClient.manifest` JSON object.

           **_language_** is the requested subtitles language code in ISO 639-1 format (e.g.
           "en", "es").

	   Some advanced options can be provided to the Ingest Service for
           subtitles generation. **_system_id_** must be an integer value indicating the
           System ID to use, **_lm_adapt_** is a boolean variable to enable or disable the
           Language Model Adaptation technique, and **_tl_path_** must be a list of tuples
           (language, system_id) describing an alternative translation path. In this
           latter case, system_id is optional and must be set to None if is not provided. 

	   **Note:** The `libtlp.TLPClient.manifest` object should have been
           initialised before with a `libtlp.TLPClient.manifest_init` call. This method
           should be executed before calling the `libtlp.TLPClient.api_ingest` method.
        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        if 'requested_langs' not in self.manifest:
            self.manifest['requested_langs'] = {}
        if language not in self.manifest['requested_langs']:
            self.manifest['requested_langs'][language] = {}
        d = {}
        if tl_path != None:
            p = []
            for s in tl_path: # is a tuple (langcode, systemId=None)
                ds = {}
                ds['l'] = s[0]
                if s[1] != None: ds['sid'] = s[1]
                p.append(ds)
            d['tlpath'] = p
        else:
            if system_id != None: d['sid'] = system_id
            if lm_adapt != None: d['lma'] = lm_adapt
        self.manifest['requested_langs'][language]['sub'] = d 


    def manifest_add_audiotrack_request(self, language, system_id=None):
        """Request audiotrack language in the "requested_langs" option of the `libtlp.TLPClient.manifest` JSON object.

           **_language_** is the requested audiotrack language code in ISO 639-1 format (e.g.
           "en", "es").

	   Some advanced options can be provided to the Ingest Service for
           subtitles generation. **_system_id_** must be an integer value indicating the
           System ID to use.

	   **Note:** The `libtlp.TLPClient.manifest` object should have been
           initialised before with a `libtlp.TLPClient.manifest_init` call. This method
           should be executed before calling the `libtlp.TLPClient.api_ingest` method.
        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        if 'requested_langs' not in self.manifest:
            self.manifest['requested_langs'] = {}
        if language not in self.manifest['requested_langs']:
            self.manifest['requested_langs'][language] = {}
        d = {}
        if system_id != None: d['sid'] = system_id
        self.manifest['requested_langs'][language]['tts'] = d
        

    def manifest_set_options(self, transLecture=None, tL_regenerate=None, tL_force=None, delete_mode=None, test_mode=None):
        """Set Ingest Service options to the `libtlp.TLPClient.manifest` JSON object.

           **_transLecture_** is a boolean variable to enable/disable transcription and translation technologies.

	   On `libtlp.TLPClient.INGEST_OPCODE_UPDATE` operations,
           **_tL_regenerate_** option can be used to request a regeneration of
           transcriptions, translations and/or synthesized audiotracks.  Must be a list of
           keywords. Allowed Keywords are: *tx* (request regeneration of the media
           transcription), *tl* (request regeneration of media translations), *tts*
           (request regeneration of synthesized audiotracks). Also, if **_tL_force_** = *True*, 
           regeneration of automatic subtitles is forced even if there exist human-supervised subtitles.

           For the `libtlp.TLPClient.INGEST_OPCODE_DELETE` operation, the
           **_delete_mode_** argument defines the delete mode. Delete modes can be: *hard*
           (default) and *soft*.

           Finally, the **_test_mode_** argument is a boolean variable to enable/disable the Test Mode of the Ingest Service. 
           When enabled, the uploaded media will be available inmediately with an empty subtitles file. 
           This feature is very useful when executing integration tests with the /ingest interface. By default it is disabled.

	   **Note:** The `libtlp.TLPClient.manifest` object should have been
           initialised before with a `libtlp.TLPClient.manifest_init` call. This method
           should be executed before calling the `libtlp.TLPClient.api_ingest` method.
        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        if transLecture != None: self.manifest['transLecture'] = int(transLecture)
        if tL_regenerate!= None: self.manifest['tL-regenerate'] = tL_regenerate
        if tL_force != None: self.manifest['tL-force'] = int(tL_force)
        if delete_mode != None: self.manifest['delete_mode'] = delete_mode
        if test_mode != None: self.manifest['test_mode'] = test_mode


    def create_media_package(self, dest=None):
        """Creates a Media Package File from the `libtlp.TLPClient.manifest` JSON object information, returning the location of the zip package.

	   By default the media package file is created and stored in a
           temporal directory, unless you specify the destination file path with the
           optional parameter **_dest_**.
        """
        if self.manifest == None:
            raise TLPException("Manifest file was not initialized.")
        self.__tmp_dir = tempfile.mkdtemp()
        manif_fp = "%s/manifest.json" % self.__tmp_dir
        with open(manif_fp,'w') as fd:
            fd.write(json.dumps(self.manifest, indent=4, separators=(',', ': '), encoding="UTF-8", ensure_ascii=False).encode('utf-8'))
        self.__manifest_files.append(manif_fp)
        if dest == None:
            dest = "%s/mpf.zip" % self.__tmp_dir
        zf = zipfile.ZipFile(dest, mode='w')
        for f in self.__manifest_files: 
            zf.write(f, arcname=self.__get_file_name(f))
        zf.close()
        return dest


    def api_ingest(self, media_package_file=None, external_id=None, operation_code=None, email=None, su=None):
      """ Performs an API call to the /ingest interface: 

	  > *Upload media (audio/video) files and many other attachments and
	  > metadata to the TLP Server for automatic multilingual subtitling
	  > and speech synthesization.*

	  If **_media_package_file_** is not provided, then it is generated
          automatically by calling the `libtlp.TLPClient.create_media_package` method. In
          this latter case, it is assumed that at least a manifest file has been
          initialised before with the `libtlp.TLPClient.manifest_init` method.

	  By default, /ingest API call parameters *id* and *opc* are retrieved
          from the `libtlp.TLPClient.manifest` JSON object, but they can be overrided with
          the optional arguments **_external_id_** and **_operation_code_**,
          respectively. However, both arguments become mandatory in case a
          **_media_package_file_** is provided.

	  Optionally, you can provide an **_email_** addressto send
          notifications about status updates of the Ingest Service.
  
	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/ingest'
      if media_package_file != None:
          mp_fp = media_package_file
      else:
          mp_fp = self.create_media_package()
      data = open(mp_fp, 'rb').read()
      self.parameters['id'] = external_id if external_id != None else self.manifest['metadata']['external_id']
      self.parameters['opc'] = operation_code if operation_code != None else self.manifest['operation_code']
      if email != None: self.parameters['email'] = email
      if su != None: self.parameters['su'] = su
      self.__set_auth_parameters_secret_key()
      self.__call_ingest(url, data)
      self.__last_api_call = "ingest"
      if self.debug: 
          self.__generate_debug_info_api(url)
      else:
          if self.__tmp_dir != None:
              shutil.rmtree(self.__tmp_dir)
    

    def api_systems(self, su=None):
      """ Performs an API call to the /systems interface:

	  > *Get a list of all available Speech Recognition, Machine
	  > Translation, and Text-To-Speech Systems that can be applied to
	  > transcribe, translate, and synthesize a media file.*

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/systems'
      if su != None: self.parameters['su'] = su
      self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "systems"
      if self.debug: self.__generate_debug_info_api(url)
  
    def api_uploadslist(self, object_id=None, su=None):
      """ Performs an API call to the /uploadslist interface:

          > *Get a list of all user's uploads.*

	  If the optional **_object_id_** argument is given, then the Web
          Service will return a list of uploads involving the provided object ID (could
          be an Upload ID or a Media ID).

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/uploadslist'
      if object_id != None: self.parameters['object_id'] = object_id
      if su != None: self.parameters['su'] = su
      self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "uploadslist"
      if self.debug: self.__generate_debug_info_api(url)
      
 
    def api_status(self, oid, su=None):
      """ Performs an API call to the /status interface:

          > *Check the current status of a specific upload ID.*

          **_oid_** is an upload ID, returned by the /ingest interface.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/status'
      self.parameters['id'] = oid
      if su != None: self.parameters['su'] = su
      self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "status"
      if self.debug: self.__generate_debug_info_api(url)
    

    def api_langs(self, oid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /langs interface:

          > *Get a list of all subtitle and audiotrack languages available for a given media ID.*
      
          The **_oid_** parameter is the Media ID. 

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/langs'
      self.parameters['id'] = oid
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "langs"
      if self.debug: self.__generate_debug_info_api(url)
     
    def api_metadata(self, oid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /metadata interface:

          > *Get metadata and media file locations for a given media ID.*

          The **_oid_** parameter is the Media ID. 

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/metadata'
      self.parameters['id'] = oid
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "metadata"
      if self.debug: self.__generate_debug_info_api(url)
      

    def api_subs(self, oid, lang, form=None, seldata=None, segfilt=None, session_id=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /subs interface:

          > *Download current subtitles file for a given media ID and language.*

	  The **_oid_** parameter is the Media ID, and **_lang_** is the
          language code (ISO 639-1) of the requested subtitles language.

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

          The **_format_** optional parameter sets the downloaded subtitles format.
          Possbile formats are: *dfxp* (default), *srt*, *ttml*, *vtt*, *text*.

	  **_seldata_** and **_segfilt_** are also optional parameters
          corresponding to the *sel_data_policy* and *seg_filt_policy* API call
          parameters.  

	  On the one hand, **_seldata_** defines which subtitle contents are returned. Possible
          values are: *`libtlp.TLPClient.SUBS_SELDATA_ALL`*,
          *`libtlp.TLPClient.SUBS_SELDATA_FORMER`*,
          *`libtlp.TLPClient.SUBS_SELDATA_CURRENT`*.

	  On the other hand, **_segfilt_** specifies the segment text filtering
          policy. Possible values are: *`libtlp.TLPClient.SUBS_SEGFILT_EMTPY`*,
          *`libtlp.TLPClient.SUBS_SEGFILT_DISABLE`*,
          *`libtlp.TLPClient.SUBS_SEGFILT_ENABLE`*.

          A **_session_id_** argument can be provided in order to apply subtitle modifications made under the given edit session ID to the subtitles file.
 
          For further details of both API call parameters please check the full TLP API documentation.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/subs'
      Dformats = { 'dfxp':0, 'ttml':1, 'srt':2, 'vtt':3, 'text':4 }
      self.parameters['id'] = oid
      self.parameters['lang'] = lang
      if form != None: self.parameters['format'] = Dformats[form]
      if seldata != None: self.parameters['sel_data_policy'] = seldata
      if segfilt != None: self.parameters['seg_filt_policy'] = segfilt
      if session_id != None: self.parameters['session_id'] = session_id
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "subs"
      if self.debug: self.__generate_debug_info_api(url)

      
    def api_audiotrack(self, oid, lang, aid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /audiotrack interface:

          > *Download an audiotrack file for a given media ID and language.*

          The **_oid_** parameter is the Media ID, **_lang_** is the
          language code (ISO 639-1) of the requested audiotrack language, and
          **_aid_** is the audiotrack ID (retrieved from the /metadata interface).

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/audiotrack'
      self.parameters['id'] = oid
      self.parameters['lang'] = lang
      self.parameters['aid'] = aid
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "audiotrack"
      if self.debug: self.__generate_debug_info_api(url)

 
    def api_start_session(self, oid, author_id, author_conf, author_name=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /start_session interface:

          > *Starts an edition session to send and commit modifications of a subtitles file.*

          The **_oid_** parameter is the Media ID, **_author_id_** is the ID of
          the user that will edit the subtitles (typically the internal user ID that the
          API client's organisation assigns to the user), and **_author_conf_** is an
          integer value (range 0-100) that indicates the confidence level that the API
          client's organisation provide to the user.

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/start_session'
      self.parameters['id'] = oid
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      if author_name != None:  self.parameters['author_name'] = author_name
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "start_session"
      if self.debug: self.__generate_debug_info_api(url)
      if self.ret_data['rcode'] == 0:
          self.__api_mod_session_id = self.ret_data['session_id']
 
      
    def api_session_status(self, oid, author_id, author_conf, session_id=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /session_status interface:

          > *Returns the current status of the given session ID. If it is alive, it updates the last alive timestamp. This interface is commonly used to avoid the automatic end of session due to user inactivity.*

	  By default, the session ID will be the one returned after calling the
          */start_session* (`libtlp.TLPClient.start_session`) interface. However, an alternative session ID can be
	  provided via the optional **_session_id_** argument.

          The **_oid_** parameter is the Media ID, **_author_id_** is the ID of
          the user that will edit the subtitles (typically the internal user ID that the
          API client's organisation assigns to the user), and **_author_conf_** is an
          integer value (range 0-100) that indicates the confidence level that the API
          client's organisation provide to the user.

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/session_status'
      self.parameters['id'] = oid
      if session_id != None:
          self.parameters['session_id'] = session_id
      elif self.__api_mod_session_id != None:
          self.parameters['session_id'] = self.__api_mod_session_id
      else:
          raise TLPException("You must start an edit session to check session status (see api_start_session()), or to manually provide a session ID (session_id optional argument).")
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "session_status"
      if self.debug: self.__generate_debug_info_api(url)
 

    def api_mod(self, oid, lang, author_id, author_conf, txt_array, del_array, author_name=None, session_id=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1, data=None):
      """ Performs an API call to the /mod interface:

          > *Send and commit subtitle corrections made by a user under an edit session ID.*

	  By default, the session ID will be the one returned after calling the
          */start_session* (`libtlp.TLPClient.start_session`) interface. However, an alternative session ID can be
	  provided via the optional **_session_id_** argument.

	  The **_oid_** parameter is the Media ID, **_lang_** is the language
          code (ISO 639-1) of the edited subtitles language, **_author_id_** is the ID of
          the user that will edit the subtitles (typically the internal user ID that the
          API client's organisation assigns to the user), and **_author_conf_** is an
          integer value (range 0-100) that indicates the confidence level that the API
          client's organisation provide to the user.

          **_txt_array_** is a list of JSON dictionaries, where each dictionary contains the following segment edition information:

 
                         {"sI":<int>, "b":<float>, "e":<float>, "t":<str>}


          **sI** is the segment ID, **b** is the segment start time, **e** is the segment end time, and **t** is the updated segment text.
          **_txt_array_** must be an empty list if no segments where modified.

          **_del_array_** is a list containing the segment IDs (int values) to delete. It must be an empty list if no segments are being deleted.

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.

	  Alternatively, you can provide a base64-encoded JSON data parameter
          value with all required /mod parameters. In this case, all mandatory arguments can be
          set to *None*, because they are ignored.
      """
      self.__reset()
      url = self.__api_base_url+'/mod'
      if data != None:
          self.parameters = json.loads(base64.b64decode(data), encoding='utf-8')
      else:
          self.parameters['id'] = oid
          if session_id != None:
              self.parameters['session_id'] = session_id
          elif self.__api_mod_session_id != None:
              self.parameters['session_id'] = self.__api_mod_session_id
          else:
              raise TLPException("You must start an edit session to send subtitle modifications (see api_start_session()), or to manually provide a session ID (session_id optional argument).")
          self.parameters['author_id'] = author_id
          self.parameters['author_conf'] = author_conf
          self.parameters['mods'] = { lang: { 'txt':[], 'del':[] } }
          if author_name != None:  self.parameters['author_name'] = author_name
          if txt_array != None: self.parameters['mods'][lang]['txt'] = txt_array
          if del_array != None: self.parameters['mods'][lang]['del'] = del_array
          if vhash != None: self.parameters['hash'] = vhash
          if su != None: self.parameters['su'] = su
          if self.use_get_method and not(self.use_data_parameter): self.parameters['mods'] = base64.b64encode(json.dumps(self.parameters['mods'], encoding='utf-8'))
          if use_req_key:
              self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
          else:
              self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "mod"
      if self.debug: self.__generate_debug_info_api(url)
  
    def api_end_session(self, oid, author_id, author_conf, author_name=None, session_id=None, force=False, regenerate=True, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /end_session interface:

          > *Ends an existing edition session.*

	  By default, the session ID will be the one returned after calling the
          */start_session* (`libtlp.TLPClient.start_session`) interface. However, an alternative session ID can be
	  provided via the optional **_session_id_** argument.

          The **_oid_** parameter is the Media ID, **_author_id_** is the ID of
          the user that will edit the subtitles (typically the internal user ID that the
          API client's organisation assigns to the user), and **_author_conf_** is an
          integer value (range 0-100) that indicates the confidence level that the API
          client's organisation provide to the user.

	  **_force_** option should set to *True* to force the end of a session when
          the given **_author_id_** or API user are not the same that started the given
          **_session_id**.

          The **_regenerate_** option tells to the TLP Server if subtitles and/or synthesized audiotracks will be
          regenerated after ending the session. By default it is set to *True*.

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/end_session'
      self.parameters['id'] = oid
      if session_id != None:
          self.parameters['session_id'] = session_id
      elif self.__api_mod_session_id != None:
          self.parameters['session_id'] = self.__api_mod_session_id
      else:
          raise TLPException("You must start an edit session to send subtitle modifications (see api_start_session()), or to manually provide a session ID (session_id optional argument).")
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      self.parameters['force'] = int(force)
      self.parameters['regenerate'] = int(regenerate)
      if author_name != None:  self.parameters['author_name'] = author_name
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "end_session"
      if self.debug: self.__generate_debug_info_api(url)
      if self.ret_data['rcode'] == 0:
          self.__api_mod_session_id = None
       
    def api_lock_subs(self, oid, lock, author_id, author_conf, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /lock_subs interface:

          > *Allow/disallow regular users to send subtitles modifications for an specific Media ID.*

          The **_oid_** parameter is the Media ID, **_author_id_** is the ID of
          the user that will edit the subtitles (typically the internal user ID that the
          API client's organisation assigns to the user), and **_author_conf_** is an
          integer value (range 0-100) that indicates the confidence level that the API
          client's organisation provide to the user.

          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      if not(isinstance(lock, bool)):
          raise TLPException("lock must be a boolean.")
      self.__reset()
      url = self.__api_base_url+'/lock_subs'
      self.parameters['id'] = oid
      self.parameters['lock'] = int(lock)
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "lock_subs"
      if self.debug: self.__generate_debug_info_api(url)

       
    def api_edit_history(self, oid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /edit_history interface:

          > *Returns a list of all edit sessions carried out over an specific Media ID.*

	  The **_oid_** parameter is the Media ID. Optionally, a media hash
          value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/edit_history'
      self.parameters['id'] = oid
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "edit_history"
      if self.debug: self.__generate_debug_info_api(url)
  
    def api_mark_revised(self, oid, session_id, author_id, author_conf, author_name=None, revision_session_id=None, unmark=False, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /mark_revised interface:

          > *Mark/unmark an edition session as revised.*

	  **_session_id_** is the Session ID to mark/unmark as revised,
          the **_oid_** parameter is the Media ID, **_author_id_** is the ID of
          the user that will edit the subtitles (typically the internal user ID that the
          API client's organisation assigns to the user), and **_author_conf_** is an
          integer value (range 0-100) that indicates the confidence level that the API
          client's organisation provide to the user.
 
          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      if not(isinstance(unmark, bool)):
          raise TLPException("unmark must be a boolean.")
      self.__reset()
      url = self.__api_base_url+'/mark_revised'
      self.parameters['id'] = oid
      self.parameters['session_id'] = session_id
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      self.parameters['unmark'] = int(unmark)
      if author_name != None:  self.parameters['author_name'] = author_name
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "mark_revised"
      if self.debug: self.__generate_debug_info_api(url)
 
    def api_accept(self, ids, author_id, author_conf, author_name=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /accept interface:

          > *Accept modifications of one or more pending edit sessions without having to revise them.*

	  
	  The **_ids_** parameter must be a list Session IDs whose edits are
          meant to be accepted by the given Author ID.  **_author_id_** is the ID of the
          user that will edit the subtitles (typically the internal user ID that the API
          client's organisation assigns to the user), and **_author_conf_** is an integer
          value (range 0-100) that indicates the confidence level that the API client's
          organisation provide to the user.
 
          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      if not(isinstance(ids, list)):
          raise TLPException("ids must be a list.")
      self.__reset()
      url = self.__api_base_url+'/accept'
      self.parameters['id'] = ",".join([ str(x) for x in ids ])
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      if author_name != None:  self.parameters['author_name'] = author_name
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "accept"
      if self.debug: self.__generate_debug_info_api(url)
 
    def api_reject(self, ids, author_id, author_conf, author_name=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
      """ Performs an API call to the /reject interface:

          > *Reject modifications of one or more pending edit sessions without having to revise them.*

	  
	  The **_ids_** parameter must be a list Session IDs whose edits are
          meant to be rejected by the given Author ID.  **_author_id_** is the ID of the
          user that will edit the subtitles (typically the internal user ID that the API
          client's organisation assigns to the user), and **_author_conf_** is an integer
          value (range 0-100) that indicates the confidence level that the API client's
          organisation provide to the user.
 
          Optionally, a media hash value can be provided using the optional **_vhash_** parameter.

	  If **_use_req_key_** *= True*, the API call will be performed using a
          valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
          defines the *Request Key* lifetime in minutes, by default is 1 minute.

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      if not(isinstance(ids, list)):
          raise TLPException("ids must be a list.")
      self.__reset()
      url = self.__api_base_url+'/reject'
      self.parameters['id'] = ",".join([ str(x) for x in ids ])
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      if author_name != None:  self.parameters['author_name'] = author_name
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "reject"
      if self.debug: self.__generate_debug_info_api(url)

    def api_revisions(self, su=None):
      """ Performs an API call to the /revisions interface:

          > *Returns a list of all edit sessions for all API user's media files that are pending to be revised.*

	  The **_su_** (*substitute user*) option can be used by Admin users
          to be identified as another existing API user at the TLP Web Service.
      """
      self.__reset()
      url = self.__api_base_url+'/revisions'
      if su != None: self.parameters['su'] = su
      self.__set_auth_parameters_secret_key()
      self.__call(url)
      self.__last_api_call = "revisions"
      if self.debug: self.__generate_debug_info_api(url)
 
    def generate_player_url(self, oid, author_id, author_conf, session_id=None, req_key_lifetime=1440, language=None, author_name=None, start=None):
      """ Returns a valid TLP Player URL.

	  **_oid_** is the Media ID, **_author_id_** is the ID of the user that
          will edit the subtitles (typically the internal user ID that the API client's
          organisation assigns to the user), and **_author_conf_** is an integer value
          (range 0-100) that indicates the confidence level that the API client's
          organisation provide to the user. 

	  Optionally, a **_language_** ISO-639-1 code can be provided to make
          the Player load directly the specified subtitles language (if not provided, the
          Player will load the source language transcriptions). Also, you can set the
          media start time in seconds with the **_start_** parameter.

          The full name of the user that will edit the subtitles can be provided with the parameter **_author_name**.

          A **_session_id_** argument can be provided in order review subtitle modifications made under the provided edit session ID.

	  Finally, you can adjust de lifetime duration in minutes of the
          generated URL using the option **_req_key_lifetime_**. By default is set to 24
          hours (1440 minutes).
      """
      self.__reset()
      self.parameters['id'] = oid
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      if language != None: self.parameters['language'] = language
      if author_name != None: self.parameters['author_name'] = author_name
      if session_id != None: self.parameters['session_id'] = session_id
      self.__set_auth_parameters_request_key_player(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      if self.debug: self.__generate_debug_info_player()
      request_parameter = base64.b64encode(json.dumps(self.parameters, encoding='UTF-8'))
      url = "%s?request=%s" % (self.__player_base_url, request_parameter)
      if start != None:
        url += "&t=%d" % int(start)
      return url

Ancestors (in MRO)

Class variables

var FTYPE_CODE_AUDIOTRACK

Audiotrack file type code

var FTYPE_CODE_DOCUMENT

Related Text Document file type code

var FTYPE_CODE_MEDIA

Main Media file type code

var FTYPE_CODE_SLIDES

Slides file type code code

var FTYPE_CODE_SUBS

Subtitles file type code

var FTYPE_CODE_THUMBNAIL

Media thumbnail file type code

var FTYPE_CODE_WAVEFORM

Waveform file type code

var INGEST_OPCODE_CANCEL

Ingest Service Cancel Upload Operation Code: An ongoing upload will be cancelled.

var INGEST_OPCODE_DELETE

Ingest Service Delete Media Operation Code: An existing media will be deleted from the database.

var INGEST_OPCODE_NEW

Ingest Service New Media Operation Code: A new media will be processed by the Ingest Service and inserted into database.

var INGEST_OPCODE_UPDATE

Ingest Service Update Media Operation Code: An existing media will be updated after processing the input data by the Ingest Service.

var SUBS_SEGFILT_DISABLE

Segment text filtering policy: Filtering disabled.

var SUBS_SEGFILT_EMTPY

Segment text filtering policy: Empty all segments (removes text from all segments).

var SUBS_SEGFILT_ENABLE

Segment text filtering policy: Filters out special annotations.

var SUBS_SELDATA_ALL

Subtitle contents to be returned: Return both former and current contents (only for DFXP format).

var SUBS_SELDATA_CURRENT

Subtitle contents to be returned: Return current contents (current status of supervision of the subtitles).

var SUBS_SELDATA_FORMER

Subtitle contents to be returned: Return former contents (automatic transcription or translation).

Instance variables

var debug

Enable/Disable generation of debug information.

var debug_info

Debug information of the last performed API call / Generation of Player URL.

var manifest

Manifest JSON object.

var parameters

Dictionary with API query parameters.

var ret_content_type

Mime-type of the data returned by the last performed API call.

var ret_data

Data returned by the last performed API call. If the response was a JSON object, ret_data becomes a a parsed JSON object (dictionary or list, depending on the JSON).

var use_data_parameter

Use a single "data" parameter on HTTP GET calls instead multiple GET parameters.

var use_get_method

Use HTTP GET Method instead of POST.

Methods

def __init__(

self, api_base_url, player_base_url, api_user, api_secret_key)

Creates a TLPClient class instance. Parameters:

  • api_base_url: Base URL to the transLectures-UPV Platform's Web Service.
  • player_base_url: Base URL to the transLectures-UPV Platform's Player.
  • api_user: API username / TLP username.
  • api_secret_key: API Secret Key.
def __init__(self, api_base_url, player_base_url, api_user, api_secret_key):
    """
    Creates a TLPClient class instance. Parameters:
    - **_api_base_url_**: Base URL to the transLectures-UPV Platform's Web Service.
    - **_player_base_url_**: Base URL to the transLectures-UPV Platform's Player.
    - **_api_user_**: API username / TLP username.
    - **_api_secret_key_**: API Secret Key.
    """
    self.__manifest_files = None
    self.__last_api_call = None
    self.__tmp_dir = None
    self.__session = None
    self.__response = None
    self.__http_auth_enabled = False
    self.__http_user = None
    self.__http_pass = None
    self.__api_mod_session_id = None
    self.__api_base_url = api_base_url
    self.__player_base_url = player_base_url
    self.__api_user = api_user
    self.__api_secret_key = api_secret_key
    self.use_get_method = False
    """Use HTTP GET Method instead of POST."""
    self.use_data_parameter = True
    """Use a single "data" parameter on HTTP GET calls instead multiple GET parameters."""
    self.parameters = None
    """Dictionary with API query parameters."""
    self.ret_data = None
    """Data returned by the last performed API call. If the response was a JSON object, *ret_data* becomes a a parsed JSON object (dictionary or list, depending on the JSON)."""
    self.ret_content_type = None
    """Mime-type of the data returned by the last performed API call."""
    self.debug = False
    """Enable/Disable generation of debug information."""
    self.debug_info = None
    """Debug information of the last performed API call / Generation of Player URL."""
    self.manifest = None
    """Manifest JSON object."""

def api_accept(

self, ids, author_id, author_conf, author_name=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1)

Performs an API call to the /accept interface:

Accept modifications of one or more pending edit sessions without having to revise them.

The ids parameter must be a list Session IDs whose edits are meant to be accepted by the given Author ID. author_id is the ID of the user that will edit the subtitles (typically the internal user ID that the API client's organisation assigns to the user), and author_conf is an integer value (range 0-100) that indicates the confidence level that the API client's organisation provide to the user.

Optionally, a media hash value can be provided using the optional vhash parameter.

If use_req_key = True, the API call will be performed using a valid Request Key as authentication token instead of the Secret Key. req_key_lifetime defines the Request Key lifetime in minutes, by default is 1 minute.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_accept(self, ids, author_id, author_conf, author_name=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
  """ Performs an API call to the /accept interface:
      > *Accept modifications of one or more pending edit sessions without having to revise them.*
he **_ids_** parameter must be a list Session IDs whose edits are
      meant to be accepted by the given Author ID.  **_author_id_** is the ID of the
      user that will edit the subtitles (typically the internal user ID that the API
      client's organisation assigns to the user), and **_author_conf_** is an integer
      value (range 0-100) that indicates the confidence level that the API client's
      organisation provide to the user.
      Optionally, a media hash value can be provided using the optional **_vhash_** parameter.
f **_use_req_key_** *= True*, the API call will be performed using a
      valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
      defines the *Request Key* lifetime in minutes, by default is 1 minute.
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  if not(isinstance(ids, list)):
      raise TLPException("ids must be a list.")
  self.__reset()
  url = self.__api_base_url+'/accept'
  self.parameters['id'] = ",".join([ str(x) for x in ids ])
  self.parameters['author_id'] = author_id
  self.parameters['author_conf'] = author_conf
  if author_name != None:  self.parameters['author_name'] = author_name
  if vhash != None: self.parameters['hash'] = vhash
  if su != None: self.parameters['su'] = su
  if use_req_key:
      self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
  else:
      self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "accept"
  if self.debug: self.__generate_debug_info_api(url)

def api_audiotrack(

self, oid, lang, aid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1)

Performs an API call to the /audiotrack interface:

Download an audiotrack file for a given media ID and language.

The oid parameter is the Media ID, lang is the language code (ISO 639-1) of the requested audiotrack language, and aid is the audiotrack ID (retrieved from the /metadata interface).

Optionally, a media hash value can be provided using the optional vhash parameter.

If use_req_key = True, the API call will be performed using a valid Request Key as authentication token instead of the Secret Key. req_key_lifetime defines the Request Key lifetime in minutes, by default is 1 minute.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_audiotrack(self, oid, lang, aid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
  """ Performs an API call to the /audiotrack interface:
      > *Download an audiotrack file for a given media ID and language.*
      The **_oid_** parameter is the Media ID, **_lang_** is the
      language code (ISO 639-1) of the requested audiotrack language, and
      **_aid_** is the audiotrack ID (retrieved from the /metadata interface).
      Optionally, a media hash value can be provided using the optional **_vhash_** parameter.
f **_use_req_key_** *= True*, the API call will be performed using a
      valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
      defines the *Request Key* lifetime in minutes, by default is 1 minute.
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  self.__reset()
  url = self.__api_base_url+'/audiotrack'
  self.parameters['id'] = oid
  self.parameters['lang'] = lang
  self.parameters['aid'] = aid
  if vhash != None: self.parameters['hash'] = vhash
  if su != None: self.parameters['su'] = su
  if use_req_key:
      self.__set_auth_parameters_request_key_api(req_key_lifetime, oid)
  else:
      self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "audiotrack"
  if self.debug: self.__generate_debug_info_api(url)

def api_edit_history(

self, oid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1)

Performs an API call to the /edit_history interface:

Returns a list of all edit sessions carried out over an specific Media ID.

The oid parameter is the Media ID. Optionally, a media hash value can be provided using the optional vhash parameter.

If use_req_key = True, the API call will be performed using a valid Request Key as authentication token instead of the Secret Key. req_key_lifetime defines the Request Key lifetime in minutes, by default is 1 minute.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_edit_history(self, oid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
  """ Performs an API call to the /edit_history interface:
      > *Returns a list of all edit sessions carried out over an specific Media ID.*
he **_oid_** parameter is the Media ID. Optionally, a media hash
      value can be provided using the optional **_vhash_** parameter.
f **_use_req_key_** *= True*, the API call will be performed using a
      valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
      defines the *Request Key* lifetime in minutes, by default is 1 minute.
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  self.__reset()
  url = self.__api_base_url+'/edit_history'
  self.parameters['id'] = oid
  if vhash != None: self.parameters['hash'] = vhash
  if su != None: self.parameters['su'] = su
  if use_req_key:
      self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
  else:
      self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "edit_history"
  if self.debug: self.__generate_debug_info_api(url)

def api_end_session(

self, oid, author_id, author_conf, author_name=None, session_id=None, force=False, regenerate=True, vhash=None, su=None, use_req_key=False, req_key_lifetime=1)

Performs an API call to the /end_session interface:

Ends an existing edition session.

By default, the session ID will be the one returned after calling the /start_session (libtlp.TLPClient.start_session) interface. However, an alternative session ID can be provided via the optional session_id argument.

The oid parameter is the Media ID, author_id is the ID of the user that will edit the subtitles (typically the internal user ID that the API client's organisation assigns to the user), and author_conf is an integer value (range 0-100) that indicates the confidence level that the API client's organisation provide to the user.

force option should set to True to force the end of a session when the given author_id or API user are not the same that started the given _session_id.

The regenerate option tells to the TLP Server if subtitles and/or synthesized audiotracks will be regenerated after ending the session. By default it is set to True.

Optionally, a media hash value can be provided using the optional vhash parameter.

If use_req_key = True, the API call will be performed using a valid Request Key as authentication token instead of the Secret Key. req_key_lifetime defines the Request Key lifetime in minutes, by default is 1 minute.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_end_session(self, oid, author_id, author_conf, author_name=None, session_id=None, force=False, regenerate=True, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
  """ Performs an API call to the /end_session interface:
      > *Ends an existing edition session.*
y default, the session ID will be the one returned after calling the
      */start_session* (`libtlp.TLPClient.start_session`) interface. However, an alternative session ID can be
rovided via the optional **_session_id_** argument.
      The **_oid_** parameter is the Media ID, **_author_id_** is the ID of
      the user that will edit the subtitles (typically the internal user ID that the
      API client's organisation assigns to the user), and **_author_conf_** is an
      integer value (range 0-100) that indicates the confidence level that the API
      client's organisation provide to the user.
*_force_** option should set to *True* to force the end of a session when
      the given **_author_id_** or API user are not the same that started the given
      **_session_id**.
      The **_regenerate_** option tells to the TLP Server if subtitles and/or synthesized audiotracks will be
      regenerated after ending the session. By default it is set to *True*.
      Optionally, a media hash value can be provided using the optional **_vhash_** parameter.
f **_use_req_key_** *= True*, the API call will be performed using a
      valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
      defines the *Request Key* lifetime in minutes, by default is 1 minute.
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  self.__reset()
  url = self.__api_base_url+'/end_session'
  self.parameters['id'] = oid
  if session_id != None:
      self.parameters['session_id'] = session_id
  elif self.__api_mod_session_id != None:
      self.parameters['session_id'] = self.__api_mod_session_id
  else:
      raise TLPException("You must start an edit session to send subtitle modifications (see api_start_session()), or to manually provide a session ID (session_id optional argument).")
  self.parameters['author_id'] = author_id
  self.parameters['author_conf'] = author_conf
  self.parameters['force'] = int(force)
  self.parameters['regenerate'] = int(regenerate)
  if author_name != None:  self.parameters['author_name'] = author_name
  if vhash != None: self.parameters['hash'] = vhash
  if su != None: self.parameters['su'] = su
  if use_req_key:
      self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
  else:
      self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "end_session"
  if self.debug: self.__generate_debug_info_api(url)
  if self.ret_data['rcode'] == 0:
      self.__api_mod_session_id = None

def api_ingest(

self, media_package_file=None, external_id=None, operation_code=None, email=None, su=None)

Performs an API call to the /ingest interface:

Upload media (audio/video) files and many other attachments and metadata to the TLP Server for automatic multilingual subtitling and speech synthesization.

If media_package_file is not provided, then it is generated automatically by calling the create_media_package method. In this latter case, it is assumed that at least a manifest file has been initialised before with the manifest_init method.

By default, /ingest API call parameters id and opc are retrieved from the manifest JSON object, but they can be overrided with the optional arguments external_id and operation_code, respectively. However, both arguments become mandatory in case a media_package_file is provided.

Optionally, you can provide an email addressto send notifications about status updates of the Ingest Service.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_ingest(self, media_package_file=None, external_id=None, operation_code=None, email=None, su=None):
  """ Performs an API call to the /ingest interface: 
 *Upload media (audio/video) files and many other attachments and
 metadata to the TLP Server for automatic multilingual subtitling
 and speech synthesization.*
f **_media_package_file_** is not provided, then it is generated
      automatically by calling the `libtlp.TLPClient.create_media_package` method. In
      this latter case, it is assumed that at least a manifest file has been
      initialised before with the `libtlp.TLPClient.manifest_init` method.
y default, /ingest API call parameters *id* and *opc* are retrieved
      from the `libtlp.TLPClient.manifest` JSON object, but they can be overrided with
      the optional arguments **_external_id_** and **_operation_code_**,
      respectively. However, both arguments become mandatory in case a
      **_media_package_file_** is provided.
ptionally, you can provide an **_email_** addressto send
      notifications about status updates of the Ingest Service.
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  self.__reset()
  url = self.__api_base_url+'/ingest'
  if media_package_file != None:
      mp_fp = media_package_file
  else:
      mp_fp = self.create_media_package()
  data = open(mp_fp, 'rb').read()
  self.parameters['id'] = external_id if external_id != None else self.manifest['metadata']['external_id']
  self.parameters['opc'] = operation_code if operation_code != None else self.manifest['operation_code']
  if email != None: self.parameters['email'] = email
  if su != None: self.parameters['su'] = su
  self.__set_auth_parameters_secret_key()
  self.__call_ingest(url, data)
  self.__last_api_call = "ingest"
  if self.debug: 
      self.__generate_debug_info_api(url)
  else:
      if self.__tmp_dir != None:
          shutil.rmtree(self.__tmp_dir)

def api_langs(

self, oid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1)

Performs an API call to the /langs interface:

Get a list of all subtitle and audiotrack languages available for a given media ID.

The oid parameter is the Media ID.

Optionally, a media hash value can be provided using the optional vhash parameter.

If use_req_key = True, the API call will be performed using a valid Request Key as authentication token instead of the Secret Key. req_key_lifetime defines the Request Key lifetime in minutes, by default is 1 minute.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_langs(self, oid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
  """ Performs an API call to the /langs interface:
      > *Get a list of all subtitle and audiotrack languages available for a given media ID.*
  
      The **_oid_** parameter is the Media ID. 
      Optionally, a media hash value can be provided using the optional **_vhash_** parameter.
f **_use_req_key_** *= True*, the API call will be performed using a
      valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
      defines the *Request Key* lifetime in minutes, by default is 1 minute.
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  self.__reset()
  url = self.__api_base_url+'/langs'
  self.parameters['id'] = oid
  if vhash != None: self.parameters['hash'] = vhash
  if su != None: self.parameters['su'] = su
  if use_req_key:
      self.__set_auth_parameters_request_key_api(req_key_lifetime, oid)
  else:
      self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "langs"
  if self.debug: self.__generate_debug_info_api(url)

def api_lock_subs(

self, oid, lock, author_id, author_conf, vhash=None, su=None, use_req_key=False, req_key_lifetime=1)

Performs an API call to the /lock_subs interface:

Allow/disallow regular users to send subtitles modifications for an specific Media ID.

The oid parameter is the Media ID, author_id is the ID of the user that will edit the subtitles (typically the internal user ID that the API client's organisation assigns to the user), and author_conf is an integer value (range 0-100) that indicates the confidence level that the API client's organisation provide to the user.

Optionally, a media hash value can be provided using the optional vhash parameter.

If use_req_key = True, the API call will be performed using a valid Request Key as authentication token instead of the Secret Key. req_key_lifetime defines the Request Key lifetime in minutes, by default is 1 minute.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_lock_subs(self, oid, lock, author_id, author_conf, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
  """ Performs an API call to the /lock_subs interface:
      > *Allow/disallow regular users to send subtitles modifications for an specific Media ID.*
      The **_oid_** parameter is the Media ID, **_author_id_** is the ID of
      the user that will edit the subtitles (typically the internal user ID that the
      API client's organisation assigns to the user), and **_author_conf_** is an
      integer value (range 0-100) that indicates the confidence level that the API
      client's organisation provide to the user.
      Optionally, a media hash value can be provided using the optional **_vhash_** parameter.
f **_use_req_key_** *= True*, the API call will be performed using a
      valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
      defines the *Request Key* lifetime in minutes, by default is 1 minute.
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  if not(isinstance(lock, bool)):
      raise TLPException("lock must be a boolean.")
  self.__reset()
  url = self.__api_base_url+'/lock_subs'
  self.parameters['id'] = oid
  self.parameters['lock'] = int(lock)
  self.parameters['author_id'] = author_id
  self.parameters['author_conf'] = author_conf
  if vhash != None: self.parameters['hash'] = vhash
  if su != None: self.parameters['su'] = su
  if use_req_key:
      self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
  else:
      self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "lock_subs"
  if self.debug: self.__generate_debug_info_api(url)

def api_mark_revised(

self, oid, session_id, author_id, author_conf, author_name=None, revision_session_id=None, unmark=False, vhash=None, su=None, use_req_key=False, req_key_lifetime=1)

Performs an API call to the /mark_revised interface:

Mark/unmark an edition session as revised.

session_id is the Session ID to mark/unmark as revised, the oid parameter is the Media ID, author_id is the ID of the user that will edit the subtitles (typically the internal user ID that the API client's organisation assigns to the user), and author_conf is an integer value (range 0-100) that indicates the confidence level that the API client's organisation provide to the user.

Optionally, a media hash value can be provided using the optional vhash parameter.

If use_req_key = True, the API call will be performed using a valid Request Key as authentication token instead of the Secret Key. req_key_lifetime defines the Request Key lifetime in minutes, by default is 1 minute.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_mark_revised(self, oid, session_id, author_id, author_conf, author_name=None, revision_session_id=None, unmark=False, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
  """ Performs an API call to the /mark_revised interface:
      > *Mark/unmark an edition session as revised.*
*_session_id_** is the Session ID to mark/unmark as revised,
      the **_oid_** parameter is the Media ID, **_author_id_** is the ID of
      the user that will edit the subtitles (typically the internal user ID that the
      API client's organisation assigns to the user), and **_author_conf_** is an
      integer value (range 0-100) that indicates the confidence level that the API
      client's organisation provide to the user.
      Optionally, a media hash value can be provided using the optional **_vhash_** parameter.
f **_use_req_key_** *= True*, the API call will be performed using a
      valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
      defines the *Request Key* lifetime in minutes, by default is 1 minute.
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  if not(isinstance(unmark, bool)):
      raise TLPException("unmark must be a boolean.")
  self.__reset()
  url = self.__api_base_url+'/mark_revised'
  self.parameters['id'] = oid
  self.parameters['session_id'] = session_id
  self.parameters['author_id'] = author_id
  self.parameters['author_conf'] = author_conf
  self.parameters['unmark'] = int(unmark)
  if author_name != None:  self.parameters['author_name'] = author_name
  if vhash != None: self.parameters['hash'] = vhash
  if su != None: self.parameters['su'] = su
  if use_req_key:
      self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
  else:
      self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "mark_revised"
  if self.debug: self.__generate_debug_info_api(url)

def api_metadata(

self, oid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1)

Performs an API call to the /metadata interface:

Get metadata and media file locations for a given media ID.

The oid parameter is the Media ID.

Optionally, a media hash value can be provided using the optional vhash parameter.

If use_req_key = True, the API call will be performed using a valid Request Key as authentication token instead of the Secret Key. req_key_lifetime defines the Request Key lifetime in minutes, by default is 1 minute.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_metadata(self, oid, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
  """ Performs an API call to the /metadata interface:
      > *Get metadata and media file locations for a given media ID.*
      The **_oid_** parameter is the Media ID. 
      Optionally, a media hash value can be provided using the optional **_vhash_** parameter.
f **_use_req_key_** *= True*, the API call will be performed using a
      valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
      defines the *Request Key* lifetime in minutes, by default is 1 minute.
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  self.__reset()
  url = self.__api_base_url+'/metadata'
  self.parameters['id'] = oid
  if vhash != None: self.parameters['hash'] = vhash
  if su != None: self.parameters['su'] = su
  if use_req_key:
      self.__set_auth_parameters_request_key_api(req_key_lifetime, oid)
  else:
      self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "metadata"
  if self.debug: self.__generate_debug_info_api(url)

def api_mod(

self, oid, lang, author_id, author_conf, txt_array, del_array, author_name=None, session_id=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1, data=None)

Performs an API call to the /mod interface:

Send and commit subtitle corrections made by a user under an edit session ID.

By default, the session ID will be the one returned after calling the /start_session (libtlp.TLPClient.start_session) interface. However, an alternative session ID can be provided via the optional session_id argument.

The oid parameter is the Media ID, lang is the language code (ISO 639-1) of the edited subtitles language, author_id is the ID of the user that will edit the subtitles (typically the internal user ID that the API client's organisation assigns to the user), and author_conf is an integer value (range 0-100) that indicates the confidence level that the API client's organisation provide to the user.

txt_array is a list of JSON dictionaries, where each dictionary contains the following segment edition information:

           {"sI":<int>, "b":<float>, "e":<float>, "t":<str>}

sI is the segment ID, b is the segment start time, e is the segment end time, and t is the updated segment text. txt_array must be an empty list if no segments where modified.

del_array is a list containing the segment IDs (int values) to delete. It must be an empty list if no segments are being deleted.

Optionally, a media hash value can be provided using the optional vhash parameter.

If use_req_key = True, the API call will be performed using a valid Request Key as authentication token instead of the Secret Key. req_key_lifetime defines the Request Key lifetime in minutes, by default is 1 minute.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

Alternatively, you can provide a base64-encoded JSON data parameter value with all required /mod parameters. In this case, all mandatory arguments can be set to None, because they are ignored.

def api_mod(self, oid, lang, author_id, author_conf, txt_array, del_array, author_name=None, session_id=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1, data=None):
  """ Performs an API call to the /mod interface:
      > *Send and commit subtitle corrections made by a user under an edit session ID.*
y default, the session ID will be the one returned after calling the
      */start_session* (`libtlp.TLPClient.start_session`) interface. However, an alternative session ID can be
rovided via the optional **_session_id_** argument.
he **_oid_** parameter is the Media ID, **_lang_** is the language
      code (ISO 639-1) of the edited subtitles language, **_author_id_** is the ID of
      the user that will edit the subtitles (typically the internal user ID that the
      API client's organisation assigns to the user), and **_author_conf_** is an
      integer value (range 0-100) that indicates the confidence level that the API
      client's organisation provide to the user.
      **_txt_array_** is a list of JSON dictionaries, where each dictionary contains the following segment edition information:
                     {"sI":<int>, "b":<float>, "e":<float>, "t":<str>}
      **sI** is the segment ID, **b** is the segment start time, **e** is the segment end time, and **t** is the updated segment text.
      **_txt_array_** must be an empty list if no segments where modified.
      **_del_array_** is a list containing the segment IDs (int values) to delete. It must be an empty list if no segments are being deleted.
      Optionally, a media hash value can be provided using the optional **_vhash_** parameter.
f **_use_req_key_** *= True*, the API call will be performed using a
      valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
      defines the *Request Key* lifetime in minutes, by default is 1 minute.
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
lternatively, you can provide a base64-encoded JSON data parameter
      value with all required /mod parameters. In this case, all mandatory arguments can be
      set to *None*, because they are ignored.
  """
  self.__reset()
  url = self.__api_base_url+'/mod'
  if data != None:
      self.parameters = json.loads(base64.b64decode(data), encoding='utf-8')
  else:
      self.parameters['id'] = oid
      if session_id != None:
          self.parameters['session_id'] = session_id
      elif self.__api_mod_session_id != None:
          self.parameters['session_id'] = self.__api_mod_session_id
      else:
          raise TLPException("You must start an edit session to send subtitle modifications (see api_start_session()), or to manually provide a session ID (session_id optional argument).")
      self.parameters['author_id'] = author_id
      self.parameters['author_conf'] = author_conf
      self.parameters['mods'] = { lang: { 'txt':[], 'del':[] } }
      if author_name != None:  self.parameters['author_name'] = author_name
      if txt_array != None: self.parameters['mods'][lang]['txt'] = txt_array
      if del_array != None: self.parameters['mods'][lang]['del'] = del_array
      if vhash != None: self.parameters['hash'] = vhash
      if su != None: self.parameters['su'] = su
      if self.use_get_method and not(self.use_data_parameter): self.parameters['mods'] = base64.b64encode(json.dumps(self.parameters['mods'], encoding='utf-8'))
      if use_req_key:
          self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
      else:
          self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "mod"
  if self.debug: self.__generate_debug_info_api(url)

def api_reject(

self, ids, author_id, author_conf, author_name=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1)

Performs an API call to the /reject interface:

Reject modifications of one or more pending edit sessions without having to revise them.

The ids parameter must be a list Session IDs whose edits are meant to be rejected by the given Author ID. author_id is the ID of the user that will edit the subtitles (typically the internal user ID that the API client's organisation assigns to the user), and author_conf is an integer value (range 0-100) that indicates the confidence level that the API client's organisation provide to the user.

Optionally, a media hash value can be provided using the optional vhash parameter.

If use_req_key = True, the API call will be performed using a valid Request Key as authentication token instead of the Secret Key. req_key_lifetime defines the Request Key lifetime in minutes, by default is 1 minute.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_reject(self, ids, author_id, author_conf, author_name=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
  """ Performs an API call to the /reject interface:
      > *Reject modifications of one or more pending edit sessions without having to revise them.*
he **_ids_** parameter must be a list Session IDs whose edits are
      meant to be rejected by the given Author ID.  **_author_id_** is the ID of the
      user that will edit the subtitles (typically the internal user ID that the API
      client's organisation assigns to the user), and **_author_conf_** is an integer
      value (range 0-100) that indicates the confidence level that the API client's
      organisation provide to the user.
      Optionally, a media hash value can be provided using the optional **_vhash_** parameter.
f **_use_req_key_** *= True*, the API call will be performed using a
      valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
      defines the *Request Key* lifetime in minutes, by default is 1 minute.
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  if not(isinstance(ids, list)):
      raise TLPException("ids must be a list.")
  self.__reset()
  url = self.__api_base_url+'/reject'
  self.parameters['id'] = ",".join([ str(x) for x in ids ])
  self.parameters['author_id'] = author_id
  self.parameters['author_conf'] = author_conf
  if author_name != None:  self.parameters['author_name'] = author_name
  if vhash != None: self.parameters['hash'] = vhash
  if su != None: self.parameters['su'] = su
  if use_req_key:
      self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
  else:
      self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "reject"
  if self.debug: self.__generate_debug_info_api(url)

def api_revisions(

self, su=None)

Performs an API call to the /revisions interface:

Returns a list of all edit sessions for all API user's media files that are pending to be revised.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_revisions(self, su=None):
  """ Performs an API call to the /revisions interface:
      > *Returns a list of all edit sessions for all API user's media files that are pending to be revised.*
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  self.__reset()
  url = self.__api_base_url+'/revisions'
  if su != None: self.parameters['su'] = su
  self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "revisions"
  if self.debug: self.__generate_debug_info_api(url)

def api_session_status(

self, oid, author_id, author_conf, session_id=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1)

Performs an API call to the /session_status interface:

Returns the current status of the given session ID. If it is alive, it updates the last alive timestamp. This interface is commonly used to avoid the automatic end of session due to user inactivity.

By default, the session ID will be the one returned after calling the /start_session (libtlp.TLPClient.start_session) interface. However, an alternative session ID can be provided via the optional session_id argument.

The oid parameter is the Media ID, author_id is the ID of the user that will edit the subtitles (typically the internal user ID that the API client's organisation assigns to the user), and author_conf is an integer value (range 0-100) that indicates the confidence level that the API client's organisation provide to the user.

Optionally, a media hash value can be provided using the optional vhash parameter.

If use_req_key = True, the API call will be performed using a valid Request Key as authentication token instead of the Secret Key. req_key_lifetime defines the Request Key lifetime in minutes, by default is 1 minute.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_session_status(self, oid, author_id, author_conf, session_id=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
  """ Performs an API call to the /session_status interface:
      > *Returns the current status of the given session ID. If it is alive, it updates the last alive timestamp. This interface is commonly used to avoid the automatic end of session due to user inactivity.*
y default, the session ID will be the one returned after calling the
      */start_session* (`libtlp.TLPClient.start_session`) interface. However, an alternative session ID can be
rovided via the optional **_session_id_** argument.
      The **_oid_** parameter is the Media ID, **_author_id_** is the ID of
      the user that will edit the subtitles (typically the internal user ID that the
      API client's organisation assigns to the user), and **_author_conf_** is an
      integer value (range 0-100) that indicates the confidence level that the API
      client's organisation provide to the user.
      Optionally, a media hash value can be provided using the optional **_vhash_** parameter.
f **_use_req_key_** *= True*, the API call will be performed using a
      valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
      defines the *Request Key* lifetime in minutes, by default is 1 minute.
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  self.__reset()
  url = self.__api_base_url+'/session_status'
  self.parameters['id'] = oid
  if session_id != None:
      self.parameters['session_id'] = session_id
  elif self.__api_mod_session_id != None:
      self.parameters['session_id'] = self.__api_mod_session_id
  else:
      raise TLPException("You must start an edit session to check session status (see api_start_session()), or to manually provide a session ID (session_id optional argument).")
  self.parameters['author_id'] = author_id
  self.parameters['author_conf'] = author_conf
  if vhash != None: self.parameters['hash'] = vhash
  if su != None: self.parameters['su'] = su
  if use_req_key:
      self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
  else:
      self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "session_status"
  if self.debug: self.__generate_debug_info_api(url)

def api_start_session(

self, oid, author_id, author_conf, author_name=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1)

Performs an API call to the /start_session interface:

Starts an edition session to send and commit modifications of a subtitles file.

The oid parameter is the Media ID, author_id is the ID of the user that will edit the subtitles (typically the internal user ID that the API client's organisation assigns to the user), and author_conf is an integer value (range 0-100) that indicates the confidence level that the API client's organisation provide to the user.

Optionally, a media hash value can be provided using the optional vhash parameter.

If use_req_key = True, the API call will be performed using a valid Request Key as authentication token instead of the Secret Key. req_key_lifetime defines the Request Key lifetime in minutes, by default is 1 minute.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_start_session(self, oid, author_id, author_conf, author_name=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
  """ Performs an API call to the /start_session interface:
      > *Starts an edition session to send and commit modifications of a subtitles file.*
      The **_oid_** parameter is the Media ID, **_author_id_** is the ID of
      the user that will edit the subtitles (typically the internal user ID that the
      API client's organisation assigns to the user), and **_author_conf_** is an
      integer value (range 0-100) that indicates the confidence level that the API
      client's organisation provide to the user.
      Optionally, a media hash value can be provided using the optional **_vhash_** parameter.
f **_use_req_key_** *= True*, the API call will be performed using a
      valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
      defines the *Request Key* lifetime in minutes, by default is 1 minute.
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  self.__reset()
  url = self.__api_base_url+'/start_session'
  self.parameters['id'] = oid
  self.parameters['author_id'] = author_id
  self.parameters['author_conf'] = author_conf
  if author_name != None:  self.parameters['author_name'] = author_name
  if vhash != None: self.parameters['hash'] = vhash
  if su != None: self.parameters['su'] = su
  if use_req_key:
      self.__set_auth_parameters_request_key_api(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
  else:
      self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "start_session"
  if self.debug: self.__generate_debug_info_api(url)
  if self.ret_data['rcode'] == 0:
      self.__api_mod_session_id = self.ret_data['session_id']

def api_status(

self, oid, su=None)

Performs an API call to the /status interface:

Check the current status of a specific upload ID.

oid is an upload ID, returned by the /ingest interface.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_status(self, oid, su=None):
  """ Performs an API call to the /status interface:
      > *Check the current status of a specific upload ID.*
      **_oid_** is an upload ID, returned by the /ingest interface.
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  self.__reset()
  url = self.__api_base_url+'/status'
  self.parameters['id'] = oid
  if su != None: self.parameters['su'] = su
  self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "status"
  if self.debug: self.__generate_debug_info_api(url)

def api_subs(

self, oid, lang, form=None, seldata=None, segfilt=None, session_id=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1)

Performs an API call to the /subs interface:

Download current subtitles file for a given media ID and language.

The oid parameter is the Media ID, and lang is the language code (ISO 639-1) of the requested subtitles language.

Optionally, a media hash value can be provided using the optional vhash parameter.

The format optional parameter sets the downloaded subtitles format. Possbile formats are: dfxp (default), srt, ttml, vtt, text.

seldata and segfilt are also optional parameters corresponding to the sel_data_policy and seg_filt_policy API call parameters.

On the one hand, seldata defines which subtitle contents are returned. Possible values are: SUBS_SELDATA_ALL, SUBS_SELDATA_FORMER, SUBS_SELDATA_CURRENT.

On the other hand, segfilt specifies the segment text filtering policy. Possible values are: SUBS_SEGFILT_EMTPY, SUBS_SEGFILT_DISABLE, SUBS_SEGFILT_ENABLE.

A session_id argument can be provided in order to apply subtitle modifications made under the given edit session ID to the subtitles file.

For further details of both API call parameters please check the full TLP API documentation.

If use_req_key = True, the API call will be performed using a valid Request Key as authentication token instead of the Secret Key. req_key_lifetime defines the Request Key lifetime in minutes, by default is 1 minute.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_subs(self, oid, lang, form=None, seldata=None, segfilt=None, session_id=None, vhash=None, su=None, use_req_key=False, req_key_lifetime=1):
  """ Performs an API call to the /subs interface:
      > *Download current subtitles file for a given media ID and language.*
he **_oid_** parameter is the Media ID, and **_lang_** is the
      language code (ISO 639-1) of the requested subtitles language.
      Optionally, a media hash value can be provided using the optional **_vhash_** parameter.
      The **_format_** optional parameter sets the downloaded subtitles format.
      Possbile formats are: *dfxp* (default), *srt*, *ttml*, *vtt*, *text*.
*_seldata_** and **_segfilt_** are also optional parameters
      corresponding to the *sel_data_policy* and *seg_filt_policy* API call
      parameters.  
n the one hand, **_seldata_** defines which subtitle contents are returned. Possible
      values are: *`libtlp.TLPClient.SUBS_SELDATA_ALL`*,
      *`libtlp.TLPClient.SUBS_SELDATA_FORMER`*,
      *`libtlp.TLPClient.SUBS_SELDATA_CURRENT`*.
n the other hand, **_segfilt_** specifies the segment text filtering
      policy. Possible values are: *`libtlp.TLPClient.SUBS_SEGFILT_EMTPY`*,
      *`libtlp.TLPClient.SUBS_SEGFILT_DISABLE`*,
      *`libtlp.TLPClient.SUBS_SEGFILT_ENABLE`*.
      A **_session_id_** argument can be provided in order to apply subtitle modifications made under the given edit session ID to the subtitles file.
      For further details of both API call parameters please check the full TLP API documentation.
f **_use_req_key_** *= True*, the API call will be performed using a
      valid *Request Key* as authentication token instead of the *Secret Key*. **_req_key_lifetime_**
      defines the *Request Key* lifetime in minutes, by default is 1 minute.
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  self.__reset()
  url = self.__api_base_url+'/subs'
  Dformats = { 'dfxp':0, 'ttml':1, 'srt':2, 'vtt':3, 'text':4 }
  self.parameters['id'] = oid
  self.parameters['lang'] = lang
  if form != None: self.parameters['format'] = Dformats[form]
  if seldata != None: self.parameters['sel_data_policy'] = seldata
  if segfilt != None: self.parameters['seg_filt_policy'] = segfilt
  if session_id != None: self.parameters['session_id'] = session_id
  if vhash != None: self.parameters['hash'] = vhash
  if su != None: self.parameters['su'] = su
  if use_req_key:
      self.__set_auth_parameters_request_key_api(req_key_lifetime, oid)
  else:
      self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "subs"
  if self.debug: self.__generate_debug_info_api(url)

def api_systems(

self, su=None)

Performs an API call to the /systems interface:

Get a list of all available Speech Recognition, Machine Translation, and Text-To-Speech Systems that can be applied to transcribe, translate, and synthesize a media file.

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_systems(self, su=None):
  """ Performs an API call to the /systems interface:
 *Get a list of all available Speech Recognition, Machine
 Translation, and Text-To-Speech Systems that can be applied to
 transcribe, translate, and synthesize a media file.*
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  self.__reset()
  url = self.__api_base_url+'/systems'
  if su != None: self.parameters['su'] = su
  self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "systems"
  if self.debug: self.__generate_debug_info_api(url)

def api_uploadslist(

self, object_id=None, su=None)

Performs an API call to the /uploadslist interface:

Get a list of all user's uploads.

If the optional object_id argument is given, then the Web Service will return a list of uploads involving the provided object ID (could be an Upload ID or a Media ID).

The su (substitute user) option can be used by Admin users to be identified as another existing API user at the TLP Web Service.

def api_uploadslist(self, object_id=None, su=None):
  """ Performs an API call to the /uploadslist interface:
      > *Get a list of all user's uploads.*
f the optional **_object_id_** argument is given, then the Web
      Service will return a list of uploads involving the provided object ID (could
      be an Upload ID or a Media ID).
he **_su_** (*substitute user*) option can be used by Admin users
      to be identified as another existing API user at the TLP Web Service.
  """
  self.__reset()
  url = self.__api_base_url+'/uploadslist'
  if object_id != None: self.parameters['object_id'] = object_id
  if su != None: self.parameters['su'] = su
  self.__set_auth_parameters_secret_key()
  self.__call(url)
  self.__last_api_call = "uploadslist"
  if self.debug: self.__generate_debug_info_api(url)

def create_media_package(

self, dest=None)

Creates a Media Package File from the manifest JSON object information, returning the location of the zip package.

By default the media package file is created and stored in a temporal directory, unless you specify the destination file path with the optional parameter dest.

def create_media_package(self, dest=None):
    """Creates a Media Package File from the `libtlp.TLPClient.manifest` JSON object information, returning the location of the zip package.
By default the media package file is created and stored in a
       temporal directory, unless you specify the destination file path with the
       optional parameter **_dest_**.
    """
    if self.manifest == None:
        raise TLPException("Manifest file was not initialized.")
    self.__tmp_dir = tempfile.mkdtemp()
    manif_fp = "%s/manifest.json" % self.__tmp_dir
    with open(manif_fp,'w') as fd:
        fd.write(json.dumps(self.manifest, indent=4, separators=(',', ': '), encoding="UTF-8", ensure_ascii=False).encode('utf-8'))
    self.__manifest_files.append(manif_fp)
    if dest == None:
        dest = "%s/mpf.zip" % self.__tmp_dir
    zf = zipfile.ZipFile(dest, mode='w')
    for f in self.__manifest_files: 
        zf.write(f, arcname=self.__get_file_name(f))
    zf.close()
    return dest

def disable_http_auth(

self)

Disable HTTP Authentication for all API calls

def disable_http_auth(self):
    """Disable HTTP Authentication for all API calls"""
    self.__http_user = None
    self.__http_pass = None
    self.__http_auth_enabled = False

def enable_http_auth(

self, http_user, http_pass)

Use HTTP Authentication for all API calls.

http_user is the HTTP Authentication username, while http_pass is the corresponding user password.

def enable_http_auth(self, http_user, http_pass):
    """Use HTTP Authentication for all API calls.
       
       **_http_user_** is the HTTP Authentication username, while **_http_pass_** is the corresponding user password.
    """
    self.__http_user = http_user
    self.__http_pass = http_pass
    self.__http_auth_enabled = True

def gen_request_key(

self, oid, expire, author=None, author_conf=None)

Returns a valid request key to be used as an API authentication token.

oid is the object ID that will be queried (id API call parameter), and expire is the UNIX timestamp of the expiration time of the key. With these two parameters is generated the basic request key.

If author (author_id API parameter) is supplied, then the full request key is generated using this parameter plus author_conf (author_conf API parameter).

def gen_request_key(self, oid, expire, author=None, author_conf=None):
    """Returns a valid request key to be used as an API authentication token.
**_oid_** is the object ID that will be queried (*id* API call
       parameter), and **_expire_** is the UNIX timestamp of the expiration time of
       the key. With these two parameters is generated the *basic request key*.
       If **_author_** (*author_id* API parameter) is supplied, then the *full request key* is generated 
       using this parameter plus **_author_conf_** (*author_conf* API parameter).
    """
    s1 = hashlib.sha1()
    s1.update(oid + str(expire) + self.__api_user + self.__api_secret_key)
    rk = s1.hexdigest()
    if author != None:
      s2 = hashlib.sha1()
      s2.update(author + str(author_conf) + str(expire) + self.__api_user + self.__api_secret_key)
      rk += s2.hexdigest()
    return rk

def generate_player_url(

self, oid, author_id, author_conf, session_id=None, req_key_lifetime=1440, language=None, author_name=None, start=None)

Returns a valid TLP Player URL.

oid is the Media ID, author_id is the ID of the user that will edit the subtitles (typically the internal user ID that the API client's organisation assigns to the user), and author_conf is an integer value (range 0-100) that indicates the confidence level that the API client's organisation provide to the user.

Optionally, a language ISO-639-1 code can be provided to make the Player load directly the specified subtitles language (if not provided, the Player will load the source language transcriptions). Also, you can set the media start time in seconds with the start parameter.

The full name of the user that will edit the subtitles can be provided with the parameter _author_name.

A session_id argument can be provided in order review subtitle modifications made under the provided edit session ID.

Finally, you can adjust de lifetime duration in minutes of the generated URL using the option req_key_lifetime. By default is set to 24 hours (1440 minutes).

def generate_player_url(self, oid, author_id, author_conf, session_id=None, req_key_lifetime=1440, language=None, author_name=None, start=None):
  """ Returns a valid TLP Player URL.
*_oid_** is the Media ID, **_author_id_** is the ID of the user that
      will edit the subtitles (typically the internal user ID that the API client's
      organisation assigns to the user), and **_author_conf_** is an integer value
      (range 0-100) that indicates the confidence level that the API client's
      organisation provide to the user. 
ptionally, a **_language_** ISO-639-1 code can be provided to make
      the Player load directly the specified subtitles language (if not provided, the
      Player will load the source language transcriptions). Also, you can set the
      media start time in seconds with the **_start_** parameter.
      The full name of the user that will edit the subtitles can be provided with the parameter **_author_name**.
      A **_session_id_** argument can be provided in order review subtitle modifications made under the provided edit session ID.
inally, you can adjust de lifetime duration in minutes of the
      generated URL using the option **_req_key_lifetime_**. By default is set to 24
      hours (1440 minutes).
  """
  self.__reset()
  self.parameters['id'] = oid
  self.parameters['author_id'] = author_id
  self.parameters['author_conf'] = author_conf
  if language != None: self.parameters['language'] = language
  if author_name != None: self.parameters['author_name'] = author_name
  if session_id != None: self.parameters['session_id'] = session_id
  self.__set_auth_parameters_request_key_player(req_key_lifetime, oid, author=author_id, author_conf=author_conf)
  if self.debug: self.__generate_debug_info_player()
  request_parameter = base64.b64encode(json.dumps(self.parameters, encoding='UTF-8'))
  url = "%s?request=%s" % (self.__player_base_url, request_parameter)
  if start != None:
    url += "&t=%d" % int(start)
  return url

def get_printable_manifest(

self)

Returns a printable, user friendly version of the manifest JSON object (stored in the manifest class member).

def get_printable_manifest(self):
     """Returns a printable, user friendly version of the manifest JSON object (stored in the `libtlp.TLPClient.manifest` class member).
     """
     if self.manifest != None:
         return json.dumps(self.manifest, indent=4)
     else:
         raise TLPException("Manifest file was not initialized.")

def get_printable_response_data(

self)

Returns a printable, user friendly version of the response data from the last API call (stored in the ret_data class member).

def get_printable_response_data(self):
     """Returns a printable, user friendly version of the response data from the 
        last API call (stored in the `libtlp.TLPClient.ret_data` class member).
     """
     if self.ret_data == None:
        raise TLPException("No response data available (have you called any API interface before?).")
     if self.ret_content_type.find("application/json") >= 0:
         return json.dumps(self.ret_data, indent=4)
     else:
         return self.ret_data

def manifest_add_attachment(

self, uri, file_type_code, language=None, human=None)

Add attachment file to the manifest JSON object.

uri is the attachment file path, and file_type_code must be one of the following values: FTYPE_CODE_MEDIA, FTYPE_CODE_SLIDES, FTYPE_CODE_DOCUMENT, FTYPE_CODE_THUMBNAIL, FTYPE_CODE_SUBS, FTYPE_CODE_AUDIOTRACK, FTYPE_CODE_WAVEFORM.

In case file_type_code = FTYPE_CODE_SUBS or file_type_code = FTYPE_CODE_AUDIOTRACK, language and human arguments are mandatory. The first one is the requested subtitles language code in ISO 639-1 format (e.g. "en", "es"), while human is a boolean variable indicationg whether the provided subtitles or audiotrack have been produced by a human, or have been generated automatically by a computer.

Note: The manifest object should have been initialised before with a manifest_init call. This method should be executed before calling the api_ingest method.

def manifest_add_attachment(self, uri, file_type_code, language=None, human=None):
    """Add attachment file to the `libtlp.TLPClient.manifest` JSON object.
**_uri_** is the attachment file path, and **_file_type_code_** must be one of
       the following values: `libtlp.TLPClient.FTYPE_CODE_MEDIA`,
       `libtlp.TLPClient.FTYPE_CODE_SLIDES`, `libtlp.TLPClient.FTYPE_CODE_DOCUMENT`,
       `libtlp.TLPClient.FTYPE_CODE_THUMBNAIL`, `libtlp.TLPClient.FTYPE_CODE_SUBS`,
       `libtlp.TLPClient.FTYPE_CODE_AUDIOTRACK`,
       `libtlp.TLPClient.FTYPE_CODE_WAVEFORM`.
In case **_file_type_code_** = `libtlp.TLPClient.FTYPE_CODE_SUBS`
       or **_file_type_code_** = `libtlp.TLPClient.FTYPE_CODE_AUDIOTRACK`, **_language_** and **_human_**
       arguments are mandatory. The first one is the  requested subtitles language
       code in ISO 639-1 format (e.g.  "en", "es"), while **_human_** is a boolean
       variable indicationg whether the provided subtitles or audiotrack have been
       produced by a human, or have been generated automatically by a computer.
**Note:** The `libtlp.TLPClient.manifest` object should have been
       initialised before with a `libtlp.TLPClient.manifest_init` call. This method
       should be executed before calling the `libtlp.TLPClient.api_ingest` method.
    """
    if self.manifest == None:
        raise TLPException("Manifest file was not initialized.")
    at = {}
    at['filename'] = self.__get_file_name(uri)
    at['fileformat'] = self.__get_file_format(uri)
    at['md5'] = self.__md5sum(uri)
    at['type_code'] = file_type_code
    if language != None: at['language'] = language
    if human != None: at['human'] = human
    try:
        self.manifest['attachments'].append(at)
    except:
        self.manifest['attachments'] = [at]
    self.__manifest_files.append(uri)

def manifest_add_audiotrack_request(

self, language, system_id=None)

Request audiotrack language in the "requested_langs" option of the manifest JSON object.

language is the requested audiotrack language code in ISO 639-1 format (e.g. "en", "es").

Some advanced options can be provided to the Ingest Service for subtitles generation. system_id must be an integer value indicating the System ID to use.

Note: The manifest object should have been initialised before with a manifest_init call. This method should be executed before calling the api_ingest method.

def manifest_add_audiotrack_request(self, language, system_id=None):
    """Request audiotrack language in the "requested_langs" option of the `libtlp.TLPClient.manifest` JSON object.
       **_language_** is the requested audiotrack language code in ISO 639-1 format (e.g.
       "en", "es").
Some advanced options can be provided to the Ingest Service for
       subtitles generation. **_system_id_** must be an integer value indicating the
       System ID to use.
**Note:** The `libtlp.TLPClient.manifest` object should have been
       initialised before with a `libtlp.TLPClient.manifest_init` call. This method
       should be executed before calling the `libtlp.TLPClient.api_ingest` method.
    """
    if self.manifest == None:
        raise TLPException("Manifest file was not initialized.")
    if 'requested_langs' not in self.manifest:
        self.manifest['requested_langs'] = {}
    if language not in self.manifest['requested_langs']:
        self.manifest['requested_langs'][language] = {}
    d = {}
    if system_id != None: d['sid'] = system_id
    self.manifest['requested_langs'][language]['tts'] = d

def manifest_add_speaker(

self, speaker_id, speaker_name, email=None, gender=None)

Add a speaker in the metadata section of the manifest JSON object.

speaker_id is the speaker ID of the media file, speaker_name is the full name of the speaker, email is the e-mail of the speaker, and gender is the gender of the speaker (M for Male or F for Female). email and gender are optional.

Note: The manifest object should have been initialised before with a manifest_init call. This method should be executed before calling the api_ingest method.

def manifest_add_speaker(self, speaker_id, speaker_name, email=None, gender=None):
    """Add a speaker in the metadata section of the `libtlp.TLPClient.manifest` JSON object.
**_speaker_id_** is the speaker ID of the media file, **_speaker_name_** is
       the full name of the speaker, **_email_** is the e-mail of the speaker, and
       **_gender_** is the gender of the speaker (*M* for Male or *F* for Female).
       **_email_** and **_gender_** are optional.
**Note:** The `libtlp.TLPClient.manifest` object should have been
       initialised before with a `libtlp.TLPClient.manifest_init` call. This method
       should be executed before calling the `libtlp.TLPClient.api_ingest` method.
    """
    if self.manifest == None:
        raise TLPException("Manifest file was not initialized.")
    spk = {}
    spk['speaker_id'] = speaker_id
    spk['speaker_name'] = speaker_name
    if gender != None: spk['speaker_gender'] = gender
    if email != None: spk['speaker_email'] = email
    try:
        self.manifest['metadata']['speakers'].append(spk)
    except:
        self.manifest['metadata']['speakers'] = [spk]

def manifest_add_subtitles_request(

self, language, system_id=None, lm_adapt=None, tl_path=None)

Request subtitles language in the "requested_langs" option of the manifest JSON object.

language is the requested subtitles language code in ISO 639-1 format (e.g. "en", "es").

Some advanced options can be provided to the Ingest Service for subtitles generation. system_id must be an integer value indicating the System ID to use, lm_adapt is a boolean variable to enable or disable the Language Model Adaptation technique, and tl_path must be a list of tuples (language, system_id) describing an alternative translation path. In this latter case, system_id is optional and must be set to None if is not provided.

Note: The manifest object should have been initialised before with a manifest_init call. This method should be executed before calling the api_ingest method.

def manifest_add_subtitles_request(self, language, system_id=None, lm_adapt=None, tl_path=None):
    """Request subtitles language in the "requested_langs" option of the `libtlp.TLPClient.manifest` JSON object.
       **_language_** is the requested subtitles language code in ISO 639-1 format (e.g.
       "en", "es").
Some advanced options can be provided to the Ingest Service for
       subtitles generation. **_system_id_** must be an integer value indicating the
       System ID to use, **_lm_adapt_** is a boolean variable to enable or disable the
       Language Model Adaptation technique, and **_tl_path_** must be a list of tuples
       (language, system_id) describing an alternative translation path. In this
       latter case, system_id is optional and must be set to None if is not provided. 
**Note:** The `libtlp.TLPClient.manifest` object should have been
       initialised before with a `libtlp.TLPClient.manifest_init` call. This method
       should be executed before calling the `libtlp.TLPClient.api_ingest` method.
    """
    if self.manifest == None:
        raise TLPException("Manifest file was not initialized.")
    if 'requested_langs' not in self.manifest:
        self.manifest['requested_langs'] = {}
    if language not in self.manifest['requested_langs']:
        self.manifest['requested_langs'][language] = {}
    d = {}
    if tl_path != None:
        p = []
        for s in tl_path: # is a tuple (langcode, systemId=None)
            ds = {}
            ds['l'] = s[0]
            if s[1] != None: ds['sid'] = s[1]
            p.append(ds)
        d['tlpath'] = p
    else:
        if system_id != None: d['sid'] = system_id
        if lm_adapt != None: d['lma'] = lm_adapt
    self.manifest['requested_langs'][language]['sub'] = d 

def manifest_init(

self, operation_code, external_id)

Initalize the manifest JSON object.

Allowed operation_code values are: INGEST_OPCODE_NEW, INGEST_OPCODE_UPDATE, INGEST_OPCODE_DELETE, INGEST_OPCODE_CANCEL.

external_id must be a Media ID or an existing upload ID if operation_code is INGEST_OPCODE_CANCEL.

Note: This method should be executed before calling the api_ingest method and any manifest_* class methods.

def manifest_init(self, operation_code, external_id):
    """Initalize the `libtlp.TLPClient.manifest` JSON object.
Allowed **_operation_code_** values are: `libtlp.TLPClient.INGEST_OPCODE_NEW`,
       `libtlp.TLPClient.INGEST_OPCODE_UPDATE`,
       `libtlp.TLPClient.INGEST_OPCODE_DELETE`,
       `libtlp.TLPClient.INGEST_OPCODE_CANCEL`.
       **_external_id_** must be a Media ID or an existing upload ID if **_operation_code_** is `libtlp.TLPClient.INGEST_OPCODE_CANCEL`.
       **Note:** This method should be executed before calling the `libtlp.TLPClient.api_ingest` method and any *manifest_\** class methods.
    """
    self.__tmp_dir = None
    self.__manifest_files = []
    self.manifest = {}
    self.manifest['operation_code'] = operation_code
    self.manifest['metadata'] = {}
    self.manifest['metadata']['external_id'] = external_id

def manifest_set_main_media_file(

self, uri)

Set main media file in the manifest JSON object.

uri can be a media file path o a media URL.

Note: The manifest object should have been initialised before with a manifest_init call. This method should be executed before calling the api_ingest method.

def manifest_set_main_media_file(self, uri):
    """Set main media file in the `libtlp.TLPClient.manifest` JSON object.
       **_uri_** can be a media file path o a media URL.
**Note:** The `libtlp.TLPClient.manifest` object should have been
       initialised before with a `libtlp.TLPClient.manifest_init` call. This method
       should be executed before calling the `libtlp.TLPClient.api_ingest` method.
    """
    if self.manifest == None:
        raise TLPException("Manifest file was not initialized.")
    self.manifest['media'] = {}
    if self.__is_url(uri):
        self.manifest['media']['url'] = uri
    else:
        self.manifest['media']['filename'] = self.__get_file_name(uri)
        self.manifest['media']['fileformat'] = self.__get_file_format(uri)
        self.manifest['media']['md5'] = self.__md5sum(uri)
        self.__manifest_files.append(uri)

def manifest_set_metadata(

self, language=None, title=None, topic=None, keywords=None, date=None)

Set metadata in the manifest JSON object.

language is the Media language code in ISO 639-1 format (e.g. "en", "es"), title is the title of the media, topic is the topic of the media, keywords are the media keywords, and date is the publication date of the media.

All arguments are optional, but language and title arguments are mandatory for INGEST_OPCODE_NEW operations.

Note: The manifest object should have been initialised before with a manifest_init call. This method should be executed before calling the api_ingest method.

def manifest_set_metadata(self, language=None, title=None, topic=None, keywords=None, date=None):
    """Set metadata in the `libtlp.TLPClient.manifest` JSON object.
**_language_** is the Media language code in ISO 639-1 format (e.g.
       "en", "es"), **_title_** is the title of the media, **_topic_** is the topic of
       the media, **_keywords_** are the media keywords, and **_date_** is the
       publication date of the media. 
All arguments are optional, but **_language_** and **_title_**
       arguments are mandatory for `libtlp.TLPClient.INGEST_OPCODE_NEW` operations.
**Note:** The `libtlp.TLPClient.manifest` object should have been
       initialised before with a `libtlp.TLPClient.manifest_init` call. This method
       should be executed before calling the `libtlp.TLPClient.api_ingest` method.
    """
    if self.manifest == None:
        raise TLPException("Manifest file was not initialized.")
    if language != None:
        self.manifest['metadata']['language'] = language
    if title != None:
        self.manifest['metadata']['title'] = title
    if topic != None:
        self.manifest['metadata']['topic'] = topic
    if keywords != None:
        self.manifest['metadata']['keywords'] = keywords
    if date != None:
        self.manifest['metadata']['date'] = date

def manifest_set_options(

self, transLecture=None, tL_regenerate=None, tL_force=None, delete_mode=None, test_mode=None)

Set Ingest Service options to the manifest JSON object.

transLecture is a boolean variable to enable/disable transcription and translation technologies.

On INGEST_OPCODE_UPDATE operations, tL_regenerate option can be used to request a regeneration of transcriptions, translations and/or synthesized audiotracks. Must be a list of keywords. Allowed Keywords are: tx (request regeneration of the media transcription), tl (request regeneration of media translations), tts (request regeneration of synthesized audiotracks). Also, if tL_force = True, regeneration of automatic subtitles is forced even if there exist human-supervised subtitles.

For the INGEST_OPCODE_DELETE operation, the delete_mode argument defines the delete mode. Delete modes can be: hard (default) and soft.

Finally, the test_mode argument is a boolean variable to enable/disable the Test Mode of the Ingest Service. When enabled, the uploaded media will be available inmediately with an empty subtitles file. This feature is very useful when executing integration tests with the /ingest interface. By default it is disabled.

Note: The manifest object should have been initialised before with a manifest_init call. This method should be executed before calling the api_ingest method.

def manifest_set_options(self, transLecture=None, tL_regenerate=None, tL_force=None, delete_mode=None, test_mode=None):
    """Set Ingest Service options to the `libtlp.TLPClient.manifest` JSON object.
       **_transLecture_** is a boolean variable to enable/disable transcription and translation technologies.
On `libtlp.TLPClient.INGEST_OPCODE_UPDATE` operations,
       **_tL_regenerate_** option can be used to request a regeneration of
       transcriptions, translations and/or synthesized audiotracks.  Must be a list of
       keywords. Allowed Keywords are: *tx* (request regeneration of the media
       transcription), *tl* (request regeneration of media translations), *tts*
       (request regeneration of synthesized audiotracks). Also, if **_tL_force_** = *True*, 
       regeneration of automatic subtitles is forced even if there exist human-supervised subtitles.
       For the `libtlp.TLPClient.INGEST_OPCODE_DELETE` operation, the
       **_delete_mode_** argument defines the delete mode. Delete modes can be: *hard*
       (default) and *soft*.
       Finally, the **_test_mode_** argument is a boolean variable to enable/disable the Test Mode of the Ingest Service. 
       When enabled, the uploaded media will be available inmediately with an empty subtitles file. 
       This feature is very useful when executing integration tests with the /ingest interface. By default it is disabled.
**Note:** The `libtlp.TLPClient.manifest` object should have been
       initialised before with a `libtlp.TLPClient.manifest_init` call. This method
       should be executed before calling the `libtlp.TLPClient.api_ingest` method.
    """
    if self.manifest == None:
        raise TLPException("Manifest file was not initialized.")
    if transLecture != None: self.manifest['transLecture'] = int(transLecture)
    if tL_regenerate!= None: self.manifest['tL-regenerate'] = tL_regenerate
    if tL_force != None: self.manifest['tL-force'] = int(tL_force)
    if delete_mode != None: self.manifest['delete_mode'] = delete_mode
    if test_mode != None: self.manifest['test_mode'] = test_mode

def save_response_data(

self, dest)

Saves the response data from the last API call (stored in the ret_data class member) into the destination dest file.

def save_response_data(self, dest):
     """Saves the response data from the last API call (stored in the `libtlp.TLPClient.ret_data` 
        class member) into the destination **_dest_** file.
     """
     with open(dest,'wb') as fd:
         fd.write(self.get_printable_response_data())

class TLPException

Generic TLP Exception

class TLPException(Exception):
    """Generic TLP Exception"""
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return self.msg

Ancestors (in MRO)

  • TLPException
  • exceptions.Exception
  • exceptions.BaseException
  • __builtin__.object

Class variables

var args

var message

Instance variables

var msg

Methods

def __init__(

self, msg)

def __init__(self, msg):
    self.msg = msg