├── tests
├── __init__.py
└── testTTSAudio.py
├── txt2SpeechBot
├── helpers
│ ├── __init__.py
│ ├── logger.py
│ ├── utils.py
│ ├── loggerFormatter.py
│ ├── fileProcessing.py
│ ├── constants.py
│ ├── user.py
│ ├── literalConstants.py
│ └── database.py
├── __init__.py
├── textToSpeech
│ ├── __init__.py
│ ├── language.py
│ └── ttsAudio.py
├── audioStore
│ ├── __init__.py
│ ├── audio.py
│ └── storedAudio.py
└── ttsbot.py
├── text_to_speech.png
├── .github
└── FUNDING.yml
├── .gitignore
├── docs
├── source
│ └── index.rst
└── .readthedocs.yml
├── README.md
├── database.sql
└── LICENSE
/tests/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # @Author: gmm96
3 |
--------------------------------------------------------------------------------
/txt2SpeechBot/helpers/__init__.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
--------------------------------------------------------------------------------
/text_to_speech.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gmm96/Txt2SpeechBot/HEAD/text_to_speech.png
--------------------------------------------------------------------------------
/txt2SpeechBot/__init__.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | # @Author: gmm96
4 |
--------------------------------------------------------------------------------
/txt2SpeechBot/textToSpeech/__init__.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3´
2 | # -*- coding: utf-8 -*-
3 | # @Author: gmm96
4 |
--------------------------------------------------------------------------------
/txt2SpeechBot/audioStore/__init__.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | # @Author: gmm96
4 |
5 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | patreon: gmm96
2 |
3 | custom:
4 | - "https://paypal.me/gmm96"
5 | - "https://www.buymeacoffee.com/gmm96"
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.*~
2 | *.pyc
3 | *.iml
4 | *.txt
5 | data/
6 | analyze/
7 | bin/
8 | .idea/
9 | .handler-saves/
10 | notify_failure.sh
--------------------------------------------------------------------------------
/docs/source/index.rst:
--------------------------------------------------------------------------------
1 | .. s documentation master file, created by
2 | sphinx-quickstart on Sun May 9 12:58:49 2021.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | Welcome to s's documentation!
7 | =============================
8 |
9 | .. toctree::
10 | :maxdepth: 4
11 | :caption: Contents:
12 |
13 | modules
14 |
15 |
16 | Indices and tables
17 | ==================
18 |
19 | * :ref:`genindex`
20 | * :ref:`modindex`
21 | * :ref:`search`
22 |
--------------------------------------------------------------------------------
/docs/.readthedocs.yml:
--------------------------------------------------------------------------------
1 | # .readthedocs.yml
2 | # Read the Docs configuration file
3 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
4 |
5 | # Required
6 | version: 2
7 |
8 | # Build documentation in the docs/ directory with Sphinx
9 | sphinx:
10 | configuration: docs/conf.py
11 |
12 | # Build documentation with MkDocs
13 | #mkdocs:
14 | # configuration: mkdocs.yml
15 |
16 | # Optionally build your docs in additional formats such as PDF and ePub
17 | formats: all
18 |
19 | # Optionally set the version of Python and requirements required to build your docs
20 | python:
21 | version: 3.7
22 | install:
23 | - requirements: docs/requirements.txt
24 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # [@Txt2SpeechBot](https://t.me/Txt2SpeechBot)
2 |
3 | Repository for the only Text to Speech Telegram Inline Bot.
4 |
5 | This inline bot ([@Txt2SpeechBot](https://t.me/Txt2SpeechBot)) translates your text messages into audios.
6 | It takes the audios from Goole Text To Speech API on a improved way to send them quickly, without downloading them in the VPS.
7 | For more details, you can see the source code.
8 |
9 | ## Main use
10 |
11 | If you want to say "Hello" to somebody, you have to type...
12 |
13 | ```
14 | @Txt2SpeechBot Hello
15 | ```
16 |
17 | ... in any chat, choose the language and enjoy it :)
18 |
19 | Languages are shown in usage order. For example, if the most used language by you is the Spanish, it will be shown the first one.
20 | This is to help you getting a better experience using the bot.
21 |
22 |
23 | #### Supported laguanges
24 |
25 | If you miss your local language and you want it to be added, feel free to contact me through telegram [@supremoh](https://t.me/supremoh).
26 | Right now, the supported languages are the next:
27 |
28 | * Arabic
29 | * German
30 | * English
31 | * Spanish
32 | * French
33 | * Italian
34 | * Portuguese
35 | * Greek
36 | * Russian
37 | * Turkish
38 | * Chinese
39 | * Japanese
40 |
41 | ## Predifined audios
42 |
43 | It also has some predifined audios made for fun.
44 | They will appear every time you type the bot's name without any additional text.
45 | If you would want to add an audio to this menu, don't hesitate to contact me on telegram ([@supremoh](https://t.me/supremoh)).
46 | I will decide if it is suitable for the bot.
47 |
48 |
49 |
50 | * This bot collects some data for its proper operation. If you use it, you're accepting this fact.
--------------------------------------------------------------------------------
/txt2SpeechBot/helpers/logger.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | File containing Logger class.
6 | """
7 |
8 | import logging
9 | import os
10 | import sys
11 | from helpers.loggerFormatter import LoggerFormatter
12 |
13 |
14 | class Logger:
15 | """
16 | Custom logger class to automatize the process of application logging
17 |
18 | The main purpose of this class is to set up a channel to logging file in disk. It also provides
19 | the option to display the messages in the standard output, as well as a custom formatter based
20 | on logging level, so every message type has a proper way to be displayed. You can access the
21 | logging object by parameter logger.
22 | """
23 |
24 | BASE_PATH: str = os.getcwd() + "/"
25 | """ Root project directory path. """
26 |
27 | def __init__(self, name: str, file: str, level: int = logging.INFO) -> None:
28 | """
29 | Creates a logger channel ready to record different actions.
30 |
31 | :param name: Name of the logger.
32 | :param file: Path to logger file in disk.
33 | :param level: Sets the threshold of the logger, defaults to logging.INFO.
34 | """
35 | self.filename: str = Logger.BASE_PATH + file
36 | self.name: str = name
37 | self.level: int = level
38 | self.handler: logging.FileHandler = logging.FileHandler(self.filename)
39 | self.handler.setFormatter(LoggerFormatter())
40 | self.logger: logging.Logger = logging.getLogger(self.name)
41 | self.logger.setLevel(self.level)
42 | self.logger.addHandler(self.handler)
43 |
44 | def log_also_to_stdout(self) -> None:
45 | """
46 | Add a channel to the logger to display its messages also in standard output.
47 | """
48 | self.logger.addHandler(logging.StreamHandler(sys.stdout))
49 |
--------------------------------------------------------------------------------
/txt2SpeechBot/helpers/utils.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | File containing Utils class.
6 | """
7 |
8 | import uuid
9 | from telebot import types
10 | from helpers.constants import Constants
11 | from helpers.database import Database
12 |
13 |
14 | class Utils:
15 | """
16 | Python class to perform basic operations with Telegram objects.
17 | """
18 |
19 | @staticmethod
20 | def create_db_conn() -> Database:
21 | """
22 | Create a Database object to connect to the application database.
23 |
24 | :return: Database object connection.
25 | :rtype: Database.
26 | """
27 | return Database(Constants.DB_CREDENTIALS[0], Constants.DB_CREDENTIALS[1],
28 | Constants.DB_CREDENTIALS[2], Constants.DB_CREDENTIALS[3])
29 |
30 | @staticmethod
31 | def generate_unique_str() -> str:
32 | """
33 | Generates a random UUID.
34 |
35 | :return: Random identifier.
36 | :rtype: Str.
37 | """
38 | return str(uuid.uuid4())
39 |
40 | @staticmethod
41 | def record_message(msg: types.Message) -> None:
42 | """
43 | Records a message for logging purposes.
44 |
45 | :param msg: Telegram message.
46 | """
47 | if msg.content_type == 'text':
48 | if msg.chat.type == Constants.ChatType.PRIVATE:
49 | text = "%s (%s): %s" % (msg.from_user.username, str(msg.chat.id), msg.text)
50 | else:
51 | text = "%s (%s) in %s [%s]: %s" % (msg.from_user.username, str(msg.from_user.id), msg.chat.title,
52 | str(msg.chat.id), msg.text)
53 | Constants.MSG_LOG.logger.info(text)
54 |
55 | @staticmethod
56 | def record_query(query: types.InlineQuery) -> None:
57 | """
58 | Records a query for logging purposes.
59 |
60 | :param query: Telegram inline query.
61 | """
62 | text = "%s (%s) %s" % (query.from_user.username, str(query.from_user.id), query.query)
63 | Constants.QRY_LOG.logger.info(text)
64 |
--------------------------------------------------------------------------------
/database.sql:
--------------------------------------------------------------------------------
1 | --
2 | -- Structure for table `User_Info`
3 | --
4 | CREATE TABLE `User_Info` (
5 | `row_id` int(10) NOT NULL AUTO_INCREMENT COMMENT 'Row number',
6 | `id` varchar(15) NOT NULL COMMENT 'User id',
7 | `username` varchar(32) DEFAULT NULL COMMENT 'Username',
8 | `first_name` varchar(255) DEFAULT NULL,
9 | `last_name` varchar(255) DEFAULT NULL COMMENT 'Second name',
10 | PRIMARY KEY(`id`),
11 | UNIQUE KEY `row_id`(`row_id`)
12 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Info about every user that uses at least once the bot';
13 |
14 |
15 |
16 | --
17 | -- Structure for table `Lan_Results`
18 | --
19 | CREATE TABLE `Lan_Results` (
20 | `row_id` int(10) NOT NULL AUTO_INCREMENT COMMENT 'Row number',
21 | `id` varchar(15) NOT NULL COMMENT 'User id',
22 | `Ar` int(11) NOT NULL DEFAULT 0 COMMENT 'Arabic',
23 | `De-de` int(11) NOT NULL DEFAULT 0 COMMENT 'German',
24 | `En-uk` int(11) NOT NULL DEFAULT 0 COMMENT 'English UK',
25 | `En-us` int(11) NOT NULL DEFAULT 0 COMMENT 'English US',
26 | `Es-es` int(11) NOT NULL DEFAULT 0 COMMENT 'Español ES',
27 | `Es-mx` int(11) NOT NULL DEFAULT 0 COMMENT 'Español MX',
28 | `Fr-fr` int(11) NOT NULL DEFAULT 0 COMMENT 'French',
29 | `It-it` int(11) NOT NULL DEFAULT 0 COMMENT 'Italian',
30 | `Pt-pt` int(11) NOT NULL DEFAULT 0 COMMENT 'Portuguese',
31 | `El-gr` int(11) NOT NULL DEFAULT 0 COMMENT 'Greek',
32 | `Ru-ru` int(11) NOT NULL DEFAULT 0 COMMENT 'Russian',
33 | `Tr-tr` int(11) NOT NULL DEFAULT 0 COMMENT 'Turkish',
34 | `Zh-cn` int(11) NOT NULL DEFAULT 0 COMMENT 'Chinese',
35 | `Ja` int(11) NOT NULL DEFAULT 0 COMMENT 'Japanese',
36 | `Pl` int(11) NOT NULL DEFAULT 0 COMMENT 'Polish',
37 | PRIMARY KEY(`id`),
38 | UNIQUE KEY `row_id`(`row_id`),
39 | FOREIGN KEY(`id`) REFERENCES `User_Info`(`id`) ON DELETE CASCADE
40 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Chosen languages by user';
41 |
42 |
43 |
44 | --
45 | -- Structure for table `Own_Audios`
46 | --
47 | CREATE TABLE `Own_Audios` (
48 | `row_id` int(10) NOT NULL AUTO_INCREMENT COMMENT 'Row number',
49 | `file_id` varchar(300) NOT NULL COMMENT 'Telegram file id',
50 | `id` varchar(15) NOT NULL COMMENT 'User id',
51 | `description` varchar(30) NOT NULL COMMENT 'Short description of the audio',
52 | `duration` int(11) NOT NULL COMMENT 'Audio duration in seconds',
53 | `size` int(11) NOT NULL COMMENT 'File size in bytes',
54 | `user_audio_id` int(11) NOT NULL COMMENT 'User audio identification',
55 | `times_used` int(11) NOT NULL DEFAULT 0 COMMENT 'Times that audio has been used by user',
56 | PRIMARY KEY(`id`, `file_id`),
57 | UNIQUE KEY `row_id`(`row_id`),
58 | FOREIGN KEY(`id`) REFERENCES `User_Info`(`id`) ON DELETE CASCADE
59 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Stores the information of own user audios';
--------------------------------------------------------------------------------
/txt2SpeechBot/helpers/loggerFormatter.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | File containing LoggerFormatter class.
6 | """
7 |
8 | import logging
9 |
10 |
11 | class LoggerFormatter(logging.Formatter):
12 | """
13 | Custom formatter class for logging purposes.
14 |
15 | This class allows us to set up different messages for every level of the logger object, this is
16 | why format method is overridden. We can also modify the date format of the logging object, so
17 | it can work with every localization. Formats are attached to the class as class fields.
18 |
19 | Need to add .%(msecs)03d' to every format str after asctime if wanna modify the date format and
20 | append milliseconds value
21 | """
22 |
23 | COMMON_FMT: str = "\n%(asctime)s.%(msecs)03d | %(levelname)s | " + \
24 | "File: %(filename)s, Func: %(funcName)s, Line: %(lineno)d" + \
25 | "\n%(message)s\n"
26 | """Common format used for every logging message except next exceptions."""
27 |
28 | WRN_FMT: str = "%(asctime)s.%(msecs)03d | %(levelname)s | %(message)s"
29 | """Format to be displayed in warning messages."""
30 |
31 | INFO_FMT: str = "%(asctime)s.%(msecs)03d | %(message)s"
32 | """Format to be displayed in information messages."""
33 |
34 | SP_DATE_FMT: str = "%d/%m/%Y %H:%M:%S"
35 | """Date format in Spanish."""
36 |
37 | def __init__(self, fmt: str = None, date_fmt: str = None) -> None:
38 | """
39 | Creates a custom formatter for a logging object.
40 |
41 | :param fmt: Common format to be displayed. If no value, COMMON_FMT value is set.
42 | :param date_fmt: Date format to be displayed in messages. If no value, SP_DATE_FMT value is set.
43 | """
44 | fmt = fmt if fmt else LoggerFormatter.COMMON_FMT
45 | date_fmt = date_fmt if date_fmt else LoggerFormatter.SP_DATE_FMT
46 | super().__init__(fmt=fmt, datefmt=date_fmt, style='%')
47 |
48 | def format(self, record: logging.LogRecord) -> str:
49 | """
50 | Sets a different format for every logging level.
51 |
52 | :param record: Message to record in the logger.
53 | :return: Formatted message.
54 | :rtype: Str.
55 | """
56 | original_fmt = self._style._fmt
57 | if record.levelno == logging.INFO:
58 | self._style._fmt = LoggerFormatter.INFO_FMT
59 | elif record.levelno == logging.WARNING:
60 | self._style._fmt = LoggerFormatter.WRN_FMT
61 | elif record.levelno == logging.ERROR:
62 | self._style._fmt = LoggerFormatter.COMMON_FMT
63 | result = logging.Formatter.format(self, record)
64 | self._style._fmt = original_fmt
65 | return result
66 |
--------------------------------------------------------------------------------
/txt2SpeechBot/audioStore/audio.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | File containing Audio class.
6 | """
7 |
8 | from operator import attrgetter
9 | from typing import List, Tuple
10 |
11 |
12 | class Audio:
13 | """
14 | Python class to represent a cached audio in Telegram system.
15 |
16 | These audios aren't written in disk, they're cached in Telegram system, so we can use them
17 | without the requirement of downloading the file in our filesystem.
18 | """
19 |
20 | def __init__(self, file_id: str = "", user_id: str = "", description: str = "", duration: int = 0,
21 | size: int = 0, user_audio_id: int = 0, callback_code: str = 0, times_used: int = 0) -> None:
22 | """
23 | Creates a object that represent a cached audio in Telegram.
24 |
25 | :param file_id: File identifier.
26 | :param user_id: Telegram user identifier.
27 | :param description: Description of the audio.
28 | :param duration: Duration in seconds.
29 | :param size: Size in bytes.
30 | :param user_audio_id: Identifier of the audio in the user's list.
31 | :param callback_code: Callback code to obtain the description.
32 | :param times_used: Number of times the audio has been used.
33 | """
34 | self.file_id = file_id
35 | self.user_id = user_id
36 | self.description = description
37 | self.duration = duration
38 | self.size = size
39 | self.user_audio_id = user_audio_id
40 | self.callback_code = callback_code
41 | self.times_used = times_used
42 |
43 | @classmethod
44 | def get_audio_list_for_inline_results(cls, db_result: List[Tuple[str, str, int, str, int]]) -> 'List[Audio]':
45 | """
46 | Returns a list of stored audios for a user so he can use them.
47 |
48 | :param db_result: Result from database to create inline results.
49 | :return: List with stored audios.
50 | :rtype: List[Audio].
51 | """
52 | return sorted([cls(
53 | file_id=audio_tuple[0],
54 | description=audio_tuple[1],
55 | user_audio_id=audio_tuple[2],
56 | callback_code=audio_tuple[3],
57 | times_used=audio_tuple[4]
58 | ) for audio_tuple in db_result],
59 | key=attrgetter("times_used")
60 | )
61 |
62 | @classmethod
63 | def get_audio_list_for_listing(cls, db_result: List[Tuple]) -> 'List[Audio]':
64 | """
65 | Returns a list of stored audios for a user so he can view and check them.
66 |
67 | :param db_result: Result from database to create audio listing.
68 | :return: List with stored audios.
69 | :rtype: List[Audio].
70 | """
71 | return [cls(
72 | file_id=audio_tuple[0],
73 | description=audio_tuple[1],
74 | duration=audio_tuple[2],
75 | size=audio_tuple[3]
76 | ) for audio_tuple in db_result
77 | ]
78 |
79 | def record_use(self) -> int:
80 | """
81 | Updates times used to add one and returns the updated value.
82 |
83 | :return: Updated times_used parameter.
84 | :rtype: int.
85 | """
86 | self.times_used += 1
87 | return self.times_used
88 |
--------------------------------------------------------------------------------
/txt2SpeechBot/helpers/fileProcessing.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | File containing FileProcessing class.
6 | """
7 |
8 | import json
9 | from typing import Optional, List, Tuple, Dict, Union
10 | from pathlib import Path
11 | from helpers.literalConstants import LiteralConstants
12 |
13 |
14 | class FileProcessing:
15 | """
16 | Python class to read and write from files in filesystem.
17 |
18 | This is just a simple class to perform read and write actions in files in disk. It has support
19 | for regular files as txt, json files and raw files so you can get the bytes of them. File
20 | descriptor won't be generated in instance creation, so a new one will be created every time you
21 | make an operation.
22 | """
23 |
24 | BASE_PATH: str = str(Path(__file__).parent.parent.parent.resolve()) + "/"
25 | """ Path to the root project directory. """
26 |
27 | def __init__(self, path: str, file_type: LiteralConstants.FileType) -> None:
28 | """
29 | Opens a file to perform operations on it.
30 |
31 | :param path: Path to filename.
32 | :param file_type: REG or JSON or BYTES.
33 | """
34 | self.path: str = FileProcessing.BASE_PATH + path
35 | self.file_type: LiteralConstants.FileType = file_type
36 |
37 | def read_file(self) -> Optional[Union[str, List, Tuple, Dict, bytes]]:
38 | """
39 | Reads the content of a specified file in the filesystem and returns it.
40 |
41 | :return: Content taken from the file.
42 | :rtype: Str or list or tuple or dict or bytes or None.
43 | """
44 | try:
45 | file = open(self.path, 'r') if self.file_type != LiteralConstants.FileType.BYTES else open(self.path, 'rb')
46 | if self.file_type == LiteralConstants.FileType.REG or self.file_type == LiteralConstants.FileType.BYTES:
47 | return file.read()
48 | elif self.file_type == LiteralConstants.FileType.JSON:
49 | return json.load(file)
50 | except EnvironmentError:
51 | LiteralConstants.STA_LOG.logger.exception(LiteralConstants.ExceptionMessages.FILE_CANT_OPEN, exc_info=True)
52 | return None
53 | else:
54 | file.close()
55 |
56 | def write_file(self, data: Union[str, List, Tuple, Dict]) -> bool:
57 | """
58 | Writes the given data into a specified file of filesystem and returns the result of the
59 | operation.
60 |
61 | :param data: Data to be written into the file.
62 | :return: True if write operation is ok, False otherwise.
63 | :rtype: Bool.
64 | """
65 | try:
66 | file = open(self.path, 'w') if self.file_type != LiteralConstants.FileType.BYTES else open(self.path, 'wb')
67 | if self.file_type == LiteralConstants.FileType.REG or self.file_type == LiteralConstants.FileType.BYTES:
68 | file.write(data)
69 | return True
70 | elif self.file_type == LiteralConstants.FileType.JSON:
71 | json.dump(data, file)
72 | return True
73 | except EnvironmentError:
74 | LiteralConstants.STA_LOG.logger.exception(LiteralConstants.ExceptionMessages.FILE_CANT_WRITE, exc_info=True)
75 | return False
76 | else:
77 | file.close()
78 |
--------------------------------------------------------------------------------
/txt2SpeechBot/helpers/constants.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | File containing Constants class.
6 | """
7 |
8 | from typing import List
9 | from helpers.literalConstants import LiteralConstants
10 | from helpers.fileProcessing import FileProcessing
11 |
12 |
13 | class Constants(LiteralConstants):
14 | """
15 | Constant values shared to all project.
16 |
17 | Class that contains the MySQL statements of this project and some constant values that needs to be
18 | read from the disk. It inheritances from the LiteralConstants class, so all its values can be accessed.
19 | """
20 |
21 | TOKEN: str = FileProcessing(LiteralConstants.FilePath.TOKEN, LiteralConstants.FileType.REG).read_file().rstrip()
22 | DB_CREDENTIALS: List[str] = FileProcessing(LiteralConstants.FilePath.DB, LiteralConstants.FileType.JSON).read_file()
23 | TTS_STR: str = FileProcessing(LiteralConstants.FilePath.TTS, LiteralConstants.FileType.REG).read_file()
24 | HELP_MSG: str = FileProcessing(LiteralConstants.FilePath.HELP_MSG, LiteralConstants.FileType.REG).read_file()
25 |
26 | class DBStatements:
27 | """ MySQL statements to perform operations in Database system. """
28 |
29 | USER_READ: str = """SELECT * FROM User_Info WHERE id = '%s'"""
30 | USER_INSERT: str = """INSERT INTO User_Info(id, username, first_name, last_name) VALUES ('%s', '%s', '%s', '%s')"""
31 | USER_UPDATE: str = """UPDATE User_Info SET username = '%s', first_name = '%s', last_name = '%s' WHERE id = '%s'"""
32 | """ Table User_Info """
33 |
34 | AUDIOS_READ_FOR_QUERY_BUILD: str = """SELECT `file_id`, `description`, `user_audio_id`, `callback_code`, `times_used` FROM Own_Audios WHERE id = '%s'"""
35 | AUDIOS_READ_FOR_CHOSEN_RESULT: str = """SELECT `file_id`, `times_used` FROM Own_Audios WHERE id = '%s' AND user_audio_id = '%i'"""
36 | AUDIOS_READ_FOR_CALLBACK_QUERY: str = """SELECT `description` FROM Own_Audios WHERE callback_code = '%s'"""
37 | AUDIOS_READ_COUNT: str = """SELECT COUNT(`file_id`) FROM Own_Audios WHERE id = '%s'"""
38 | AUDIOS_READ_FOR_CHECKING: str = """SELECT `file_id` FROM Own_Audios WHERE id = '%s' AND description = '%s'"""
39 | AUDIOS_READ_FOR_LISTING: str = """SELECT `file_id`, `description`, `duration`, `size` FROM Own_Audios WHERE id = '%s'"""
40 | AUDIOS_READ_FOR_REMOVING: str = """SELECT `file_id`, `description` FROM Own_Audios WHERE id = '%s'"""
41 | AUDIOS_READ_USER_IDS: str = """SELECT `user_audio_id` FROM Own_Audios WHERE id = '%s'"""
42 | AUDIOS_INSERT: str = """INSERT INTO Own_Audios(file_id, id, description, duration, size, user_audio_id, callback_code) VALUES ('%s', '%s', '%s', '%i', '%i', '%i', '%s')"""
43 | AUDIOS_UPDATE_FOR_CHOSEN_RESULT: str = """UPDATE Own_Audios SET `times_used` = '%i' WHERE file_id = '%s'"""
44 | AUDIOS_REMOVE: str = """DELETE FROM Own_Audios WHERE id = '%s' AND description = '%s'"""
45 | AUDIOS_REMOVE_ALL: str = """DELETE FROM Own_Audios WHERE id = '%s'"""
46 | """ Table Own_Audios """
47 |
48 | LAN_READ: str = """SELECT `""" + """`, `""".join(LiteralConstants.SORTED_LANGUAGES.values()) \
49 | + """` FROM Lan_Results WHERE id = '%s'"""
50 | LAN_INSERT: str = """INSERT INTO Lan_Results(id) VALUES('%s')"""
51 | LAN_UPDATE_FOR_CHOSEN_RESULT: str = """UPDATE Lan_Results SET `%s` = '%d' WHERE id = '%s'"""
52 | """ Table Lan_Results """
53 |
--------------------------------------------------------------------------------
/txt2SpeechBot/textToSpeech/language.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | File containing Language class.
6 | """
7 |
8 | from operator import attrgetter
9 | from typing import List, Tuple
10 | from helpers.constants import Constants
11 |
12 |
13 | class Language:
14 | """
15 | Python class to represent a language in a Text to Speech Telegram Bot.
16 |
17 | A language instance contains a set of language title, language code and the number of times the
18 | language has been used by a certain user.
19 | """
20 |
21 | def __init__(self, title: str = '', code: str = '', times_used: int = 0) -> None:
22 | """
23 | Creates a language object ready to be used.
24 |
25 | :param title: Title of the language.
26 | :param code: Language code identifier.
27 | :param times_used: Number of times the language has been used.
28 | """
29 | self.title = title
30 | self.code = code
31 | self.times_used = times_used
32 |
33 | @classmethod
34 | def get_languages_sorted_alphabetically(cls) -> 'List[Language]':
35 | """
36 | Creates a list of languages sorted alphabetically based on title parameter.
37 |
38 | :return: List of languages sorted alphabetically.
39 | :rtype: List[Language].
40 | """
41 | return sorted(
42 | [cls(title, code) for title, code in Constants.SORTED_LANGUAGES.items()],
43 | key=attrgetter("title"),
44 | )
45 |
46 | @classmethod
47 | def get_languages_sorted_for_user(cls, db_result: Tuple[int]) -> 'List[Language]':
48 | """
49 | Creates a list of languages sorted for user input.
50 |
51 | This methods generates a list of languages sorted based in times_used parameter, being the
52 | firsts those which has been used more times.
53 |
54 | :param db_result: Result from database.
55 | :return: List of languages sorted for user.
56 | :rtype: List[Language].
57 | """
58 | return sorted(
59 | [cls(title, code, db_result[i]) for i, (title, code) in enumerate(Constants.SORTED_LANGUAGES.items())],
60 | key=attrgetter("times_used"),
61 | reverse=True
62 | )
63 |
64 | def record_use(self) -> int:
65 | """
66 | Updates times used to add one and returns the updated value.
67 |
68 | :return: Updated times_used parameter.
69 | :rtype: int.
70 | """
71 |
72 | self.times_used += 1
73 | return self.times_used
74 |
75 | def __str__(self) -> str:
76 | """
77 | String value of the language object.
78 |
79 | :return: String value.
80 | :rtype: Str.
81 | """
82 | return "Language %s \t|\t Code %s \t|\t Times used %i\n" % (self.title, self.code, self.times_used)
83 |
84 | def __repr__(self) -> str:
85 | """
86 | Small string value to represent a language object.
87 |
88 | :return: String representation.
89 | :rtype: Str.
90 | """
91 | return "Lang %s \t|\t Code %s \t|\t Used %i\n" % (self.title, self.code, self.times_used)
92 |
93 | @staticmethod
94 | def get_language_index_in_list(languages: 'List[Language]', lang_code: str) -> int:
95 | """
96 | Get the index of a Language in a list of them based on language code.
97 |
98 | :param languages: List of languages.
99 | :param lang_code: Language code identifier.
100 | :return: Position in list if exists, -1 if it doesn't exist.
101 | """
102 | try:
103 | return [language.code for language in languages].index(lang_code)
104 | except ValueError:
105 | return -1
106 |
--------------------------------------------------------------------------------
/txt2SpeechBot/helpers/user.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | File containing User class.
6 | """
7 |
8 | from telebot import types
9 | from typing import Optional
10 | from helpers.constants import Constants
11 | from helpers.database import Database
12 | from helpers.utils import Utils
13 |
14 |
15 | class User:
16 | """
17 | Python class to represent an user in our bot application system.
18 |
19 | This class could be considered as an additional layer between Telegram user and users stored
20 | in database. Created to simplify the way we deal with users in our application.
21 | """
22 |
23 | def __init__(self, internal_id: str = "", user_id: str = "", username: str = "", first_name: str = "",
24 | last_name: str = "") -> None:
25 | """
26 | Creates a object that represent an user of the application.
27 |
28 | :param internal_id: Internal bot user identifier.
29 | :param user_id: Telegram user identifier.
30 | :param username: Telegram username.
31 | :param first_name: Telegram user's first name.
32 | :param last_name: Telegram user's second name.
33 | """
34 | self.internal_id = internal_id
35 | self.user_id = user_id
36 | self.username = username
37 | self.first_name = first_name
38 | self.last_name = last_name
39 |
40 | def __eq__(self, other_user: 'User') -> bool:
41 | """
42 | Checks if two instances of this class have equal values, so it could be considered the same
43 | user.
44 |
45 | :param other_user: User to check equality.
46 | :return: True if users have same values, False in other case.
47 | :rtype: Bool.
48 | """
49 | if type(self) is not type(other_user):
50 | return False
51 |
52 | return self.user_id == other_user.user_id and \
53 | self.username == other_user.username and \
54 | self.first_name == other_user.first_name and \
55 | self.last_name == other_user.last_name
56 |
57 | @classmethod
58 | def get_user_from_db(cls, user_id: str) -> Optional['User']:
59 | """
60 | Returns an user instance from database based on Telegram user identifier. If the user does
61 | not exist or did not use previously the bot application, returns None.
62 |
63 | :param user_id: Telegram user identifier.
64 | :return: User if exists records in database with Telegram user identifier.
65 | :rtype: User if exists, None in other case.
66 | """
67 | db_conn = Utils.create_db_conn()
68 | sql_read = Constants.DBStatements.USER_READ % str(user_id)
69 | result = db_conn.read_one(sql_read)
70 | return cls(
71 | internal_id=result[0],
72 | user_id=result[1],
73 | username=result[2],
74 | first_name=result[3],
75 | last_name=result[4]
76 | ) if result else None
77 |
78 | @classmethod
79 | def get_user_from_telegram_user(cls, user: types.User) -> 'User':
80 | """
81 | Returns a user instance based on Telegram user attached to a message or query.
82 |
83 | :param user: Telegram user from message or query.
84 | :return: User instance based on Telegram system.
85 | :rtype: User.
86 | """
87 | return cls(
88 | user_id=str(user.id),
89 | username=Database.db_str(user.username),
90 | first_name=Database.db_str(user.first_name),
91 | last_name=Database.db_str(user.last_name)
92 | )
93 |
94 | def store(self) -> None:
95 | """
96 | Initializes and stores an user in our bot application.
97 | """
98 | db_conn = Utils.create_db_conn()
99 | sql_insert_user_info = Constants.DBStatements.USER_INSERT % (self.user_id, self.username,
100 | self.first_name, self.last_name)
101 | sql_insert_chosen_result = Constants.DBStatements.LAN_INSERT % self.user_id
102 | db_conn.write_all(sql_insert_user_info)
103 | db_conn.write_all(sql_insert_chosen_result)
104 |
105 | def update(self) -> None:
106 | """
107 | Updates user's parameters in database.
108 | """
109 | sql_update = Constants.DBStatements.USER_UPDATE % (self.username, self.first_name, self.last_name, self.user_id)
110 | db_conn = Utils.create_db_conn()
111 | db_conn.write_all(sql_update)
112 |
113 | @staticmethod
114 | def validate_user_from_telegram(user: types.User) -> None:
115 | """
116 | Checks if user has previous records in Database and stores any parameter changes.
117 |
118 | :param user: Telegram user from message or query.
119 | """
120 | telegram_user = User.get_user_from_telegram_user(user)
121 | db_user = User.get_user_from_db(user.id)
122 | if db_user:
123 | if db_user != telegram_user:
124 | telegram_user.update()
125 | else:
126 | telegram_user.store()
127 |
--------------------------------------------------------------------------------
/txt2SpeechBot/helpers/literalConstants.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | File containing LiteralConstants class.
6 | """
7 |
8 | import enum
9 | from collections import OrderedDict
10 | from operator import itemgetter
11 | from typing import Dict, List
12 | from helpers.logger import Logger
13 |
14 |
15 | class LiteralConstants:
16 | """
17 | Basic constants for the working of the project.
18 |
19 | All these constants are written in this python file shared across the project.
20 | """
21 |
22 | class FileType(enum.Enum):
23 | """ Enumerable with different file types that can be handled by the project. """
24 | REG = 1
25 | JSON = 2
26 | BYTES = 3
27 |
28 | class ChatType:
29 | """ Supported telegram chat types by the bot. """
30 | PRIVATE: str = "private"
31 | GROUP: str = "group"
32 |
33 | class BotCommands:
34 | """ Available commands for Txt2SpeechBot. """
35 | HELP: str = "help"
36 | START: str = "start"
37 | ADD_AUDIO: str = "addaudio"
38 | LST_AUDIO: str = "listaudio"
39 | RM_AUDIO: str = "rmaudio"
40 | RM_ALL_AUDIOS: str = "rmallaudios"
41 |
42 | class BotAnswers:
43 | """ Bot answers to user interaction. """
44 | SEND_AUDIO: str = "Send audio or voice note."
45 | MAX_OWN_AUDIOS: str = "Sorry, you reached maximun number of stored audios (50). Try removing some of them with /rmaudio command."
46 | PROVIDE_DESC: str = "Saved!\n\nProvide now a short description for the audio. 30 character allowed."
47 | NOT_AUDIO: str = "Audio file are not detected. Are you sure you've uploaded the correct file? Try it again with /addaudio command."
48 | WRONG_DESC: str = "Wrong input. Write a short description to save the audio. 30 characters maximum."
49 | USED_DESC: str = "Description is already in use. Please, write another one."
50 | SAVED: str = "Saved audio with description: \"%s\""
51 | LST_NONE_AUDIO: str = "Sorry, you don't have any uploaded audio... Try to upload one with /addaudio command."
52 | RM_AUDIO: str = "Send the description of the audio you want to remove."
53 | RM_ALL_AUDIO: str = "Are you completely sure you want to delete all your audios? Answer 'CONFIRM' in uppercase to verify this action."
54 | RM_ALL_NOT_CONFIRM: str = "You should have answered 'CONFIRM' to validate the deletion. Canceling action."
55 | RM_DESC_NOT_TEXT: str = "Wrong input. Send the description of the audio you want to remove. Try again /rmaudio."
56 | RM_USED_DESC: str = "No audio with the provided description. Please, send the correct description. Try again /rmaudio."
57 | DELETED_AUDIO: str = "The file was deleted from your audios."
58 | DELETED_ALL_AUDIO: str = "All your audios were deleted successfully."
59 |
60 | class FilePath:
61 | """ File path to required project files. """
62 | TOKEN: str = "data/token.txt"
63 | DB: str = "data/db.json"
64 | TTS: str = "data/magic.txt"
65 | HELP_MSG: str = "data/help.txt"
66 | STA_LOG: str = "data/status.log"
67 | MSG_LOG: str = "data/messages.log"
68 | QRY_LOG: str = "data/queries.log"
69 |
70 | class ExceptionMessages:
71 | """ Messages to be sent when a exception occurs. """
72 | DB_CONNECTED: str = "DB | Connected to MySQL database server, version "
73 | DB_UNCONNECTED: str = "DB | Error while trying to connect to MySQL database server\nError: "
74 | DB_DISCONNECTED: str = "DB | Disconnected from MySQL database server"
75 | DB_READ: str = "DB | Unable to fetch data from database\nSQL query: "
76 | DB_WRITE: str = "DB | Unable to write data in database\nSQL query: "
77 | FILE_CANT_OPEN: str = "File | Unable to open requested file\n"
78 | FILE_CANT_WRITE: str = "File | Unable to write provided data in this file\n"
79 | AUDIO_ERROR: str = "AUDIO | Unable to open file with mimetype %s\n"
80 | UNEXPECTED_ERROR: str = "Error | An unexpected error has occured\n"
81 |
82 | STA_LOG: Logger = Logger("Status log", FilePath.STA_LOG)
83 | MSG_LOG: Logger = Logger("Message logger", FilePath.MSG_LOG)
84 | QRY_LOG: Logger = Logger("Query logger", FilePath.QRY_LOG)
85 |
86 | MAX_QUERIES: int = 100000
87 |
88 | LANGUAGES: Dict[str, str] = {
89 | "AR العربية": "Ar",
90 | "Deutsch DE": "De-de",
91 | "English UK": "En-uk",
92 | "English US": "En-us",
93 | "Español ES": "Es-es",
94 | "Español MX": "Es-mx",
95 | "Français FR": "Fr-fr",
96 | "Italiano IT": "It-it",
97 | "Português PT": "Pt-pt",
98 | "ελληνικά GR": "El-gr",
99 | "русский RU": "Ru-ru",
100 | "Türkçe TR": "Tr-tr",
101 | "汉语 ZH": "Zh-cn",
102 | "日本語 JA": "Ja",
103 | "Polski PL": "Pl"
104 | }
105 | # noinspection PyTypeChecker
106 | SORTED_LANGUAGES: OrderedDict = OrderedDict(sorted(LANGUAGES.items(), key=itemgetter(0)))
107 |
108 | PROBLEMATIC_CHARS: Dict[str, str] = {
109 | "\n": " ",
110 | "’": "'",
111 | "‘": "'",
112 | "\"": "'",
113 | "“": "'",
114 | "”": "'",
115 | "…": "...",
116 | "<": "",
117 | ">": "",
118 | "#": "",
119 | "%": "",
120 | "{": "",
121 | "}": "",
122 | "|": "",
123 | "^": "",
124 | "~": "",
125 | "[": "",
126 | "]": "",
127 | "`": "",
128 | ";": "",
129 | "/": ""
130 | } # ? : @ = &
131 |
132 | CONTENT_TYPES: List[str] = ['audio', 'voice', 'video']
133 | MIME_TYPES: List[str] = ['audio', 'video']
134 |
--------------------------------------------------------------------------------
/txt2SpeechBot/helpers/database.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | File containing Database class.
6 | """
7 |
8 | import re
9 | import mysql.connector as mysqldb
10 | from mysql.connector.errors import Error as MySQLdbError
11 | from typing import Optional, List, Tuple, Union
12 | from helpers.constants import Constants
13 |
14 |
15 | class Database:
16 | """
17 | Python class to perform a different set of operations in a MySQL Database.
18 |
19 | This class provides a simpler way to interact with application database than the common python
20 | MySQL connectors. The connection is done as soon as you create an instance, but cursors are
21 | created in every method to avoid errors (such as cursor disconnection, trying to perform more
22 | that one operation at the same time, etc). It also deals with instance deleting, lost connection
23 | and provides a method to prepare a string for database.
24 | """
25 |
26 | def __init__(self, host: str, user: str, password: str, database: str) -> None:
27 | """
28 | Opens a connection to a MySQL Database system prepared to work.
29 |
30 | :param host: Host address to Database machine.
31 | :param user: Username used for login in Database system.
32 | :param password: Password used for login in Database system.
33 | :param database: Database where the connection will point.
34 | """
35 | self.host: str = host
36 | self.user: str = user
37 | self.database: str = database
38 | self.connection: Optional[mysqldb.MySQLConnection] = None
39 | self.connect_to_db(password)
40 |
41 | def __del__(self) -> None:
42 | """
43 | Closes a Database connection when the object is moved to the garbage collector.
44 | """
45 | self.disconnect_from_db()
46 |
47 | def connect_to_db(self, password: str) -> None:
48 | """
49 | Tries to connect to a specific Database is connections is not already done.
50 |
51 | :param password: Password used for login in Database system.
52 | """
53 | try:
54 | if not self.connection or self.connection.is_closed():
55 | self.connection = mysqldb.connect(host=self.host, user=self.user,
56 | password=password, database=self.database)
57 | except MySQLdbError:
58 | Constants.STA_LOG.logger.error(Constants.ExceptionMessages.DB_UNCONNECTED, exc_info=True)
59 |
60 | def disconnect_from_db(self) -> None:
61 | """
62 | Closes a Database connection.
63 | """
64 | self.connection.close()
65 |
66 | def read_all(self, read_query: str) -> List[Tuple]:
67 | """
68 | Executes a read operation and returns all rows of a query result set.
69 |
70 | :param read_query: MySQL read statement.
71 | :return: Query result set from execution of a MySQL statement.
72 | :rtype: List[tuple] or empty list[].
73 | """
74 | self.test_connection_and_reconnect_if_necessary()
75 | cursor = None
76 | try:
77 | cursor = self.connection.cursor(buffered=True)
78 | cursor.execute(read_query)
79 | result = cursor.fetchall()
80 | return result
81 | except MySQLdbError:
82 | Constants.STA_LOG.logger.exception(Constants.ExceptionMessages.DB_READ + read_query, exc_info=True)
83 | return []
84 | finally:
85 | if cursor:
86 | cursor.close()
87 |
88 | def read_one(self, read_query: str) -> Optional[Tuple]:
89 | """
90 | Executes a read operation and returns just one row of the query result set.
91 |
92 | :param read_query: MySQL read statement.
93 | :return: Query result row from execution of a MySQL statement.
94 | :rtype: Tuple[] or None.
95 | """
96 | self.test_connection_and_reconnect_if_necessary()
97 | cursor = None
98 | try:
99 | cursor = self.connection.cursor(buffered=True)
100 | cursor.execute(read_query)
101 | result = cursor.fetchone()
102 | return result
103 | except MySQLdbError:
104 | Constants.STA_LOG.logger.exception(Constants.ExceptionMessages.DB_READ + read_query, exc_info=True)
105 | return None
106 | finally:
107 | if cursor:
108 | cursor.close()
109 |
110 | def write_all(self, write_query: str) -> Union[int, bool]:
111 | """
112 | Executes an insert or update operation and returns the number of modified rows or False if
113 | the operation does not change anything.
114 |
115 | :param write_query: MySQL insert or update statement.
116 | :return: Number of modified rows or False if no changes were done.
117 | :rtype: Int or bool.
118 | """
119 | self.test_connection_and_reconnect_if_necessary()
120 | cursor = None
121 | try:
122 | cursor = self.connection.cursor(buffered=True)
123 | cursor.execute(write_query)
124 | self.connection.commit()
125 | return cursor.rowcount
126 | except MySQLdbError:
127 | if self.connection.is_connected():
128 | self.connection.rollback()
129 | Constants.STA_LOG.logger.exception(Constants.ExceptionMessages.DB_WRITE + write_query, exc_info=True)
130 | return False
131 | finally:
132 | if cursor:
133 | cursor.close()
134 |
135 | def test_connection_and_reconnect_if_necessary(self) -> None:
136 | """
137 | Tests if connection is available and reconnects if the connections has been lost.
138 | """
139 | if not self.connection or self.connection.is_closed():
140 | try:
141 | self.connection.ping(reconnect=True, attempts=5, delay=0)
142 | except MySQLdbError:
143 | Constants.STA_LOG.logger.error(Constants.ExceptionMessages.DB_UNCONNECTED, exc_info=True)
144 |
145 | @staticmethod
146 | def db_str(text: str) -> str:
147 | """
148 | Translates a string to make it compatible with the Database system.
149 |
150 | :param text: string to be translated
151 | :return: String prepared for Database manipulation.
152 | :rtype: Str.
153 | """
154 | if text:
155 | return re.sub('[^A-Za-z0-9ñ\s]+', '', text)
156 | else:
157 | return text or ''
158 |
--------------------------------------------------------------------------------
/txt2SpeechBot/audioStore/storedAudio.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | File containing StoredAudio class.
6 | """
7 |
8 | from telebot import types
9 | from typing import List, Optional, Union, Tuple
10 | from helpers.constants import Constants
11 | from helpers.database import Database
12 | from helpers.utils import Utils
13 | from audioStore.audio import Audio
14 |
15 |
16 | class StoredAudio:
17 | """
18 | Python class to manipulate a stored audio in a Telegram bot.
19 |
20 | This class could be considered as a set of utilities to deal with cached audios in Telegram
21 | system. Its main purpose it's to deal with inline queries, chosen inline queries and callback
22 | queries, but it also has auxiliary methods that complement its business logic, as some tools
23 | to check the mime type or which kind of file is attached to a Telegram message.
24 | """
25 |
26 | SIZE_LIMIT = 20 * 1024 * 1024
27 | """Limit in bytes for the file size."""
28 |
29 | @staticmethod
30 | def create_inline_results_stored_audio(query: types.InlineQuery) \
31 | -> List[Union[types.InlineQueryResultCachedVoice, types.InlineQueryResultArticle]]:
32 | """
33 | Creates and returns inline results for a user to answer an inline query about stored audios.
34 |
35 | :param query: Telegram inline query.
36 | :return: Inline results to answer a query.
37 | :rtype: List [types.InlineQueryResultCachedVoice or types.InlineQueryResultArticle]
38 | """
39 | db_conn = Utils.create_db_conn()
40 | sql_read = Constants.DBStatements.AUDIOS_READ_FOR_QUERY_BUILD % str(query.from_user.id)
41 | result = db_conn.read_all(sql_read)
42 | if len(result) > 0:
43 | return StoredAudio.__create_inline_results_with_audios(result)
44 | else:
45 | return StoredAudio.__create_inline_results_no_audios()
46 |
47 | @staticmethod
48 | def __create_inline_results_with_audios(db_result: List[Tuple]) -> List[types.InlineQueryResultCachedVoice]:
49 | """
50 | Returns inline results for an user with stored audios.
51 |
52 | :return: Inline results to answer a query.
53 | :rtype: List[types.InlineQueryResultCachedVoice]
54 | """
55 | inline_results = []
56 | audios = Audio.get_audio_list_for_inline_results(db_result)
57 | for audio in audios:
58 | markup = types.InlineKeyboardMarkup()
59 | markup.add(types.InlineKeyboardButton("Description", callback_data=audio.callback_code))
60 | inline_results.append(types.InlineQueryResultCachedVoice(
61 | str(audio.user_audio_id), audio.file_id, audio.description, reply_markup=markup
62 | ))
63 | return inline_results
64 |
65 | @staticmethod
66 | def __create_inline_results_no_audios() -> List[types.InlineQueryResultArticle]:
67 | """
68 | Returns inline results for an user without stored audios.
69 |
70 | :return: Inline results to answer a query.
71 | :rtype: List[types.InlineQueryResultArticle]
72 | """
73 | msg_if_clicked = types.InputTextMessageContent(Constants.HELP_MSG)
74 | inline_results = [
75 | types.InlineQueryResultArticle(1, "No entries for personal audios", msg_if_clicked),
76 | types.InlineQueryResultArticle(2, "You can type to get a TextToSpeech audio", msg_if_clicked),
77 | types.InlineQueryResultArticle(3, "Or add a personal audio chatting me privately", msg_if_clicked)
78 | ]
79 | return inline_results
80 |
81 | @staticmethod
82 | def update_chosen_results_stored_audio(chosen_result: types.ChosenInlineResult) -> None:
83 | """
84 | Update the number of times a stored audio has been used based on a chosen inline result.
85 |
86 | :param chosen_result: Telegram chosen inline result.
87 | """
88 | db_conn = Utils.create_db_conn()
89 | sql_read = Constants.DBStatements.AUDIOS_READ_FOR_CHOSEN_RESULT % (str(chosen_result.from_user.id),
90 | int(chosen_result.result_id))
91 | result = db_conn.read_one(sql_read)
92 | if result:
93 | audio = Audio(file_id=result[0], times_used=result[1])
94 | sql_update = Constants.DBStatements.AUDIOS_UPDATE_FOR_CHOSEN_RESULT % (audio.record_use(), audio.file_id)
95 | db_conn.write_all(sql_update)
96 |
97 | @staticmethod
98 | def get_callback_query_stored_audio(callback_code: str) -> Optional[str]:
99 | """
100 | Returns the description of a stored audio based on the callback query code.
101 |
102 | :param callback_code: Callback code.
103 | :return: Stored audio description.
104 | :rtype: Str if exists audio with same callback code, None in other case.
105 | """
106 | db_conn = Utils.create_db_conn()
107 | audio = Audio(callback_code=callback_code)
108 | result = db_conn.read_one(Constants.DBStatements.AUDIOS_READ_FOR_CALLBACK_QUERY % callback_code)
109 | if result:
110 | audio.description = result[0]
111 | return audio.description
112 | else:
113 | return None
114 |
115 | @staticmethod
116 | def get_stored_audio_free_id(taken_ids: List[int]) -> Optional[int]:
117 | """
118 | Returns the first and lowest available stored audio identifier for a certain user.
119 |
120 | :param taken_ids: List of identifiers in use.
121 | :return: Stored user audio identifier.
122 | :rtype: Int if available user identifier, None in other case.
123 | """
124 | current_id, max_id = 1, 51
125 | while current_id in taken_ids and current_id < max_id:
126 | current_id += 1
127 | return current_id if current_id < max_id else None
128 |
129 | @staticmethod
130 | def get_stored_audios_listing(user_id: str, db_conn: Database) -> Optional[str]:
131 | """
132 | Returns a string containing a resume of all audios uploaded by a user.
133 |
134 | :param user_id: Telegram user identifier.
135 | :param db_conn: Database object
136 | :return: Str if exists audios, None in other case.
137 | """
138 | result = db_conn.read_all(Constants.DBStatements.AUDIOS_READ_FOR_LISTING % user_id)
139 | if len(result) == 0:
140 | return None
141 | audios = Audio.get_audio_list_for_listing(result)
142 | message = "These are your stored audios.\n\n"
143 | for index, audio in enumerate(audios):
144 | message += "%i.- %s \t|\t %i s \t|\t %.2fKB\n" % (index + 1, audio.description,
145 | audio.duration, audio.size / 1024.0)
146 | return message
147 |
148 | @staticmethod
149 | def is_file_valid_telegram_voice(content_type: str) -> bool:
150 | """
151 | Checks if file is a compatible Telegram voice audio.
152 |
153 | :param content_type: Type of content.
154 | :return: True if it is a voice, False in other case.
155 | :rtype: Bool.
156 | """
157 | return content_type == 'voice'
158 |
159 | @staticmethod
160 | def validate_multimedia_file(msg: types.Message) -> bool:
161 | """
162 | Checks and validates a multimedia file to be processed.
163 |
164 | :param msg: Telegram message.
165 | :return: True if it is valid, False in other case.
166 | :rtype: Bool
167 | """
168 | return StoredAudio.is_file_multimedia(msg) and \
169 | StoredAudio.has_multimedia_file_proper_size(msg)
170 |
171 | @staticmethod
172 | def is_file_multimedia(msg: types.Message) -> bool:
173 | """
174 | Scans Telegram message content type to check if has a multimedia attached file.
175 |
176 | :param msg: Telegram message.
177 | :return: True if it is multimedia, False in other case.
178 | :rtype: Bool
179 | """
180 | return msg.content_type in Constants.CONTENT_TYPES or StoredAudio.is_document_multimedia_file(msg)
181 |
182 | @staticmethod
183 | def has_multimedia_file_proper_size(msg: types.Message) -> bool:
184 | """
185 | Checks if the attached file to a Telegram message has lower size than limit.
186 |
187 | :param msg: Telegram message.
188 | :return: True if file size is lower than limit, False in other case.
189 | :rtype: Bool
190 | """
191 | return StoredAudio.get_file_link(msg).file_size <= StoredAudio.SIZE_LIMIT
192 |
193 | @staticmethod
194 | def is_document_multimedia_file(msg: types.Message) -> bool:
195 | """
196 | Checks if a Telegram document attached to a Telegram message is a multimedia file.
197 |
198 | :param msg: Telegram message.
199 | :return: True if it is multimedia, False in other case.
200 | :rtype: Bool.
201 | """
202 | if msg.content_type == 'document':
203 | file_type = StoredAudio.get_type_from_mime_type(msg.document.mime_type)
204 | if file_type in Constants.MIME_TYPES:
205 | return True
206 |
207 | return False
208 |
209 | @staticmethod
210 | def get_type_from_mime_type(mime_type: str) -> str:
211 | """
212 | Returns the type of file according to the mime_type.
213 |
214 | :param mime_type: File's mime type.
215 | :return: Type of file.
216 | :rtype: Str.
217 | """
218 | return mime_type.split('/')[0]
219 |
220 | @staticmethod
221 | def get_file_link(msg: types.Message) -> Union[types.Voice, types.Audio, types.Video, types.Document]:
222 | """
223 | Returns a file link from a Telegram message based on the content file type.
224 |
225 | :param msg: Telegram message.
226 | :return: Link to the contained file.
227 | :rtype: Voice, audio, video or document.
228 | """
229 | if msg.content_type == 'voice':
230 | return msg.voice
231 | elif msg.content_type == 'audio':
232 | return msg.audio
233 | elif msg.content_type == 'video':
234 | return msg.video
235 | elif msg.content_type == 'document':
236 | return msg.document
237 |
--------------------------------------------------------------------------------
/tests/testTTSAudio.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | import unittest
5 |
6 | import requests
7 | import io
8 | from telebot import types
9 | from unittest.mock import Mock
10 | from pydub import AudioSegment
11 | from collections import OrderedDict
12 | from txt2SpeechBot.helpers.constants import Constants
13 | from txt2SpeechBot.helpers import TTSAudio
14 | from txt2SpeechBot.helpers.utils import Utils
15 |
16 |
17 | class TestTTSAudio(unittest.TestCase):
18 |
19 | def setUp(self) -> None:
20 | self.user_id: str = '6216877'
21 | self.query_random: str = 'May I stand unshaken'
22 | self.query_chinese: str = '我可以坚定不移吗'
23 | self.query_arabic1: str = 'هل لي أن أقف غير مهتز'
24 | self.query_arabic2: str = 'ذَلِكَ الْكِتَابُ لَا رَيْبَ فِيهِ هُدًى لِلْمُتَّقِينَ'
25 | self.query_japanese: str = '揺るぎなく立っていてもいいですか'
26 | self.query_russian: str = 'могу я стоять непоколебимо'
27 | self.query_greek: str = 'μπορώ να μείνω αναστατωμένος'
28 | self.query_turkish: str = 'sarsılmadan durabilir miyim'
29 | self.query_spanish: str = "Alguna query random que lleve la ñ de España"
30 | self.queries: OrderedDict = OrderedDict()
31 |
32 | for _ in list(range(Constants.MAX_QUERIES)):
33 | self.queries[Utils.generate_unique_str()] = self.query_random
34 |
35 | def test_inline_results_for_tts_audios(self):
36 | query = self.__create_query(self.query_random, self.user_id)
37 | lan_titles = Constants.LANGUAGES.keys()
38 | inline_results = TTSAudio.create_inline_results_tts_audio(query, self.queries)
39 | if not TTSAudio.is_arabic(query.query):
40 | self.assertEqual(len(inline_results), len(Constants.LANGUAGES))
41 | for counter, result in enumerate(inline_results):
42 | self.assertIsInstance(result, types.InlineQueryResultVoice)
43 | self.assertEqual(str(counter + 1), result.id)
44 | self.assertIn(result.title, lan_titles)
45 | self.assertEqual(200, requests.get(result.voice_url).status_code)
46 | else:
47 | self.assertEqual(1, len(inline_results))
48 | self.assertIsInstance(inline_results[0], types.InlineQueryResultVoice)
49 | self.assertEqual(str(1), inline_results[0].id)
50 | self.assertIn(inline_results[0].title, lan_titles)
51 | self.assertEqual(200, requests.get(inline_results[0].voice_url).status_code)
52 |
53 | def test_store_tts_query(self):
54 | queries_empty = OrderedDict()
55 | queries_full = self.queries
56 | code_for_empty = TTSAudio.store_tts_query(self.query_chinese, queries_empty)
57 | code_for_full = TTSAudio.store_tts_query(self.query_random, queries_full)
58 | self.assertEqual(1, len(queries_empty))
59 | self.assertEqual(Constants.MAX_QUERIES, len(queries_full))
60 | self.assertEqual(self.query_chinese, queries_empty[code_for_empty])
61 | self.assertEqual(self.query_random, queries_full[code_for_full])
62 |
63 | def test_get_callback_query_tts_audio(self):
64 | callback_code1 = list(self.queries.keys())[0]
65 | callback_code2 = list(self.queries.keys())[len(self.queries) - 1]
66 | callback_code3 = 'Not found callback code'
67 | query1 = TTSAudio.get_callback_query_tts_audio(callback_code1, self.queries)
68 | query2 = TTSAudio.get_callback_query_tts_audio(callback_code2, self.queries)
69 | query3 = TTSAudio.get_callback_query_tts_audio(callback_code3, self.queries)
70 | self.assertEqual(self.queries[callback_code1], query1)
71 | self.assertEqual(self.queries[callback_code2], query2)
72 | self.assertIsNone(query3)
73 |
74 | def test_generate_voice_content_english(self):
75 | languages = Constants.LANGUAGES.values()
76 | content = TTSAudio.generate_voice_content(self.query_random)
77 | for lan in languages:
78 | response = requests.get(content + lan)
79 | self.assertEqual(200, response.status_code)
80 | self.assertGreater(int(response.headers['content-length']) / 1024, 1, "English typo, %s lan" % lan)
81 | audio = AudioSegment.from_file(io.BytesIO(response.content))
82 | self.assertGreater(audio.duration_seconds, 1)
83 |
84 | def test_generate_voice_content_chinese(self):
85 | languages = Constants.LANGUAGES.values()
86 | content = TTSAudio.generate_voice_content(self.query_chinese)
87 | for lan in languages:
88 | response = requests.get(content + lan)
89 | self.assertEqual(200, response.status_code)
90 | self.assertGreater(int(response.headers['content-length']) / 1024, 1, "Chinese typo, %s lan" % lan)
91 | audio = AudioSegment.from_file(io.BytesIO(response.content))
92 | self.assertGreater(audio.duration_seconds, 1)
93 |
94 | def test_generate_voice_content_arabic(self):
95 | languages = Constants.LANGUAGES.values()
96 | content = TTSAudio.generate_voice_content(self.query_arabic1)
97 | for lan in languages:
98 | response = requests.get(content + lan)
99 | self.assertEqual(200, response.status_code)
100 | self.assertGreater(int(response.headers['content-length']) / 1024, 1, "Arabic typo, %s lan" % lan)
101 | audio = AudioSegment.from_file(io.BytesIO(response.content))
102 | self.assertGreater(audio.duration_seconds, 1)
103 |
104 | def test_generate_voice_content_japanese(self):
105 | languages = Constants.LANGUAGES.values()
106 | content = TTSAudio.generate_voice_content(self.query_japanese)
107 | for lan in languages:
108 | response = requests.get(content + lan)
109 | self.assertEqual(200, response.status_code)
110 | self.assertGreater(int(response.headers['content-length']) / 1024, 1, "Japanese typo, %s lan" % lan)
111 | audio = AudioSegment.from_file(io.BytesIO(response.content))
112 | self.assertGreater(audio.duration_seconds, 1)
113 |
114 | def test_generate_voice_content_russian(self):
115 | languages = Constants.LANGUAGES.values()
116 | content = TTSAudio.generate_voice_content(self.query_russian)
117 | for lan in languages:
118 | response = requests.get(content + lan)
119 | self.assertEqual(200, response.status_code)
120 | self.assertGreater(int(response.headers['content-length']) / 1024, 1, "Russian typo, %s lan" % lan)
121 | audio = AudioSegment.from_file(io.BytesIO(response.content))
122 | self.assertGreater(audio.duration_seconds, 1)
123 |
124 | def test_generate_voice_content_greek(self):
125 | languages = Constants.LANGUAGES.values()
126 | content = TTSAudio.generate_voice_content(self.query_greek)
127 | for lan in languages:
128 | response = requests.get(content + lan)
129 | self.assertEqual(200, response.status_code)
130 | self.assertGreater(int(response.headers['content-length']) / 1024, 1, "Greek typo, %s lan" % lan)
131 | audio = AudioSegment.from_file(io.BytesIO(response.content))
132 | self.assertGreater(audio.duration_seconds, 1)
133 |
134 | def test_generate_voice_content_turkish(self):
135 | languages = Constants.LANGUAGES.values()
136 | content = TTSAudio.generate_voice_content(self.query_turkish)
137 | for lan in languages:
138 | response = requests.get(content + lan)
139 | self.assertEqual(200, response.status_code)
140 | self.assertGreater(int(response.headers['content-length']) / 1024, 1, "Turkish typo, %s lan" % lan)
141 | audio = AudioSegment.from_file(io.BytesIO(response.content))
142 | self.assertGreater(audio.duration_seconds, 1)
143 |
144 | def test_generate_voice_content_spanish(self):
145 | languages = Constants.LANGUAGES.values()
146 | content = TTSAudio.generate_voice_content(self.query_spanish)
147 | for lan in languages:
148 | response = requests.get(content + lan)
149 | self.assertEqual(200, response.status_code)
150 | self.assertGreater(int(response.headers['content-length']) / 1024, 1, "Spanish typo, %s lan" % lan)
151 | audio = AudioSegment.from_file(io.BytesIO(response.content))
152 | self.assertGreater(audio.duration_seconds, 1)
153 |
154 | def test_is_arabic(self):
155 | text1 = self.query_arabic1
156 | text2 = 'asdffas' + self.query_arabic2 + 'falsd'
157 | text3 = '344.23' + self.query_arabic2 + '534-<5'
158 | text4 = self.query_chinese
159 | text5 = ''
160 | self.assertTrue(TTSAudio.is_arabic(text1))
161 | self.assertTrue(TTSAudio.is_arabic(text2))
162 | self.assertTrue(TTSAudio.is_arabic(text3))
163 | self.assertFalse(TTSAudio.is_arabic(text4))
164 | self.assertFalse(TTSAudio.is_arabic(text5))
165 |
166 | def test_is_japanese(self):
167 | text1 = self.query_japanese
168 | text2 = 'asdffas' + self.query_japanese + 'falsd'
169 | text3 = '34.43e' + self.query_japanese + '5e34<5'
170 | text4 = self.query_chinese
171 | text5 = ''
172 | self.assertTrue(TTSAudio.is_japanese(text1))
173 | self.assertTrue(TTSAudio.is_japanese(text2))
174 | self.assertTrue(TTSAudio.is_japanese(text3))
175 | self.assertFalse(TTSAudio.is_japanese(text4))
176 | self.assertFalse(TTSAudio.is_japanese(text5))
177 |
178 | def test_is_chinese(self):
179 | text1 = self.query_chinese
180 | text2 = 'asdffas' + self.query_chinese + 'falsd'
181 | text3 = '34.43e' + self.query_chinese + '5e34<5'
182 | text4 = self.query_arabic2
183 | text5 = ''
184 | self.assertTrue(TTSAudio.is_chinese(text1))
185 | self.assertTrue(TTSAudio.is_chinese(text2))
186 | self.assertTrue(TTSAudio.is_chinese(text3))
187 | self.assertFalse(TTSAudio.is_chinese(text4))
188 | self.assertFalse(TTSAudio.is_chinese(text5))
189 |
190 | @staticmethod
191 | def __create_query(query: str, user_id: str):
192 | mocked_query = Mock(types.InlineQuery)
193 | mocked_query.from_user = Mock(types.User)
194 | mocked_query.query = query
195 | mocked_query.from_user.id = user_id
196 | return mocked_query
197 |
198 |
199 | if __name__ == '__main__':
200 | unittest.main()
201 |
--------------------------------------------------------------------------------
/txt2SpeechBot/textToSpeech/ttsAudio.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | File containing TTSAudio class.
6 | """
7 |
8 | import re
9 | import urllib.parse
10 | from telebot import types
11 | from collections import OrderedDict
12 | from typing import List, Optional, Tuple
13 | from helpers.constants import Constants
14 | from helpers.utils import Utils
15 | from textToSpeech.language import Language
16 |
17 |
18 | class TTSAudio:
19 | """
20 | Python class to manipulate a cached text to speech audio.
21 |
22 | This class could be considered as a set of utilities to deal and create cached audios in
23 | Telegram system by a text to speech approach. It main purpose it's to deal with inline queries,
24 | chosen inline queries and callback queries, but it also has auxiliary methods that complements
25 | its business logic, as some tools to check the x based on the type of characters
26 | attached to the Telegram message.
27 | """
28 |
29 | REGEX_JAPANESE: str = "[\u3040-\u30ff]"
30 | """Regex to find Japanese characters."""
31 | REGEX_CHINESE: str = "[\u4e00-\u9FFF]"
32 | """Regex to find Chinese characters."""
33 | REGEX_KOREAN: str = "[\uac00-\ud7a3]"
34 | """Regex to find Korean characters."""
35 | REGEX_ARABIC: str = "[\u0600-\u06ff]|[\u0750-\u077f]|[\ufb50-\ufbc1]|[\ufbd3-\ufd3f]|" + \
36 | "[\ufd50-\ufd8f]|[\ufd92-\ufdc7]|[\ufe70-\ufefc]|[\uFDF0-\uFDFD]"
37 | """Regex to find Arabic characters."""
38 |
39 | @staticmethod
40 | def create_inline_results_tts_audio(query: types.InlineQuery, queries: OrderedDict
41 | ) -> List[types.InlineQueryResultVoice]:
42 | """
43 | Creates and returns inline results for a user to answer an inline query about text to
44 | speech audios.
45 |
46 | :param query: Telegram inline query.
47 | :param queries: Dictionary that contains all created callbacks.
48 | :return: Inline results to answer a query.
49 | :rtype: List [types.InlineQueryResultVoice].
50 | """
51 | db_conn = Utils.create_db_conn()
52 | markup = types.InlineKeyboardMarkup()
53 | magic = TTSAudio.generate_voice_content(query.query)
54 | markup.add(types.InlineKeyboardButton("Text", callback_data=TTSAudio.store_tts_query(query.query, queries)))
55 | sql_read = Constants.DBStatements.LAN_READ % str(query.from_user.id)
56 | result = db_conn.read_one(sql_read)
57 | if result:
58 | return TTSAudio.__create_inline_results_with_db_entry(query.query, magic, markup, result)
59 | else:
60 | return TTSAudio.__create_inline_results_without_db_entry(query.query, magic, markup)
61 |
62 | @staticmethod
63 | def __create_inline_results_without_db_entry(query: str, magic: str, markup: types.InlineKeyboardMarkup,
64 | ) -> List[types.InlineQueryResultVoice]:
65 | """
66 | Returns inline results for an user without previous records in database.
67 |
68 | :param query: String used in the query.
69 | :param magic: String used to point the queries.
70 | :param markup: Button attached to the audio to get its description.
71 | :return: Inline results to answer a query.
72 | :rtype: List[types.InlineQueryResultVoice].
73 | """
74 | languages = Language.get_languages_sorted_alphabetically()
75 | return TTSAudio.__build_all_inline_results(query, languages, magic, markup)
76 |
77 | @staticmethod
78 | def __create_inline_results_with_db_entry(query: str, magic: str, markup: types.InlineKeyboardMarkup,
79 | db_result: Tuple[int]) -> List[types.InlineQueryResultVoice]:
80 | """
81 | Returns inline results for an user with previous records in database.
82 |
83 | :param query: String used in the query.
84 | :param magic: String used to point the queries.
85 | :param markup: Button attached to the audio to get its description.
86 | :param db_result: Tuple that contains the number of times a user utilized every x.
87 | :return: Inline results to answer a query.
88 | :rtype: List[types.InlineQueryResultVoice].
89 | """
90 | user_sorted_lang = Language.get_languages_sorted_for_user(db_result)
91 | return TTSAudio.__build_all_inline_results(query, user_sorted_lang, magic, markup)
92 |
93 | @staticmethod
94 | def __build_all_inline_results(query: str, languages: List[Language], magic: str,
95 | markup: types.InlineKeyboardMarkup) -> List[types.InlineQueryResultVoice]:
96 | """
97 | Builds and returns all possible inline results for a certain query.
98 |
99 | :param query: Query to be processed.
100 | :param languages: List of sorted Languages.
101 | :param magic: String used to point queries.
102 | :param markup: Inline keyboard markup.
103 | :return: List of inline results.
104 | :rtype: List[types.InlineQueryResultVoice].
105 | """
106 | inline_results = []
107 | if TTSAudio.is_arabic(query):
108 | inline_results.append(TTSAudio.__build_language_inline_result(languages, 'Ar', magic, markup))
109 | elif TTSAudio.is_cjk(query):
110 | cjk_langs = list(filter(lambda x: x.code == 'Ja' or x.code == 'Zh-cn', languages))
111 | for lang in cjk_langs:
112 | inline_results.append(TTSAudio.__build_language_inline_result(languages, lang.code, magic, markup))
113 | else:
114 | for index, language in enumerate(languages):
115 | inline_results.append(types.InlineQueryResultVoice(
116 | str(index + 1),
117 | magic + language.code,
118 | language.title,
119 | reply_markup=markup
120 | ))
121 | return inline_results
122 |
123 | @staticmethod
124 | def __build_language_inline_result(sorted_languages: List[Language], lang_code: str, url_prefix: str,
125 | markup: types.InlineKeyboardMarkup) -> types.InlineQueryResultVoice:
126 | """
127 | Finds the index of a x code in collection sorted_languages and returns an inline
128 | result for that specific x.
129 |
130 | :param sorted_languages: List of sorted Languages.
131 | :param lang_code: Language for the inline result.
132 | :param url_prefix: Url prefix.
133 | :param markup: Inline keyboard markup.
134 | :return: Inline result.
135 | :rtype: types.InlineQueryResultVoice
136 | """
137 | lang_index = Language.get_language_index_in_list(sorted_languages, lang_code)
138 | return types.InlineQueryResultVoice(
139 | str(lang_index + 1),
140 | url_prefix + sorted_languages[lang_index].code,
141 | sorted_languages[lang_index].title,
142 | reply_markup=markup
143 | )
144 |
145 | @staticmethod
146 | def update_chosen_results_tts_audio(chosen_result: types.ChosenInlineResult) -> None:
147 | """
148 | Update the number of times a x has been used based on a chosen inline result.
149 |
150 | :param chosen_result: Telegram chosen inline result.
151 | """
152 | db_conn = Utils.create_db_conn()
153 | sql_read = Constants.DBStatements.LAN_READ % str(chosen_result.from_user.id)
154 | result = db_conn.read_one(sql_read)
155 | if result:
156 | sorted_languages = Language.get_languages_sorted_for_user(result)
157 | lan = sorted_languages[int(chosen_result.result_id) - 1].code
158 | times = sorted_languages[int(chosen_result.result_id) - 1].record_use()
159 | sql_update = Constants.DBStatements.LAN_UPDATE_FOR_CHOSEN_RESULT % (lan, times, chosen_result.from_user.id)
160 | db_conn.write_all(sql_update)
161 |
162 | @staticmethod
163 | def store_tts_query(text: str, queries: OrderedDict) -> str:
164 | """
165 | Stores a text to speech query in a dictionary to use it later for callback query.
166 |
167 | :param text: Query from the user.
168 | :param queries: Query dictionary.
169 | :return: Code to identify query made by user.
170 | :rtype: Str.
171 | """
172 | code_id = Utils.generate_unique_str()
173 | if len(queries) >= Constants.MAX_QUERIES:
174 | queries.pop(next(reversed(queries)))
175 | queries[code_id] = text
176 | return code_id
177 |
178 | @staticmethod
179 | def get_callback_query_tts_audio(callback_code: str, queries: OrderedDict) -> Optional[str]:
180 | """
181 | Returns the text content of a text to speech audio based on the query done.
182 |
183 | :param callback_code: Callback code.
184 | :param queries: Dictionary that contains all created callbacks.
185 | :return: Text to speech audio description.
186 | :rtype: Str if exists audio with same callback code, None in other case.
187 | """
188 | try:
189 | return queries[callback_code]
190 | except KeyError:
191 | return None
192 |
193 | @staticmethod
194 | def generate_voice_content(query: str) -> str:
195 | """
196 | Generates and returns the prepared link to obtain all the possible audios.
197 |
198 | :param query:
199 | :return:
200 | """
201 | normalized_text = urllib.parse.quote(query)
202 | return Constants.TTS_STR.format(query=normalized_text)
203 |
204 | @staticmethod
205 | def is_arabic(text: str) -> bool:
206 | """
207 | Returns true is text contains Arabic x characters, false in other case.
208 |
209 | :param text: text to be checked.
210 | :return: True if is Arabic, false in other case.
211 | """
212 | return bool(re.search(TTSAudio.REGEX_ARABIC, text))
213 |
214 | @staticmethod
215 | def is_japanese(text: str) -> bool:
216 | """
217 | Returns true is text contains Japanese x characters, false in other case.
218 |
219 | :param text: text to be checked.
220 | :return: True if is Japanese, false in other case.
221 | """
222 | return bool(re.search(TTSAudio.REGEX_JAPANESE, text))
223 |
224 | @staticmethod
225 | def is_chinese(text: str) -> bool:
226 | """
227 | Returns true is text contains Chinese x characters, false in other case.
228 |
229 | :param text: text to be checked.
230 | :return: True if is Chinese, false in other case.
231 | """
232 | return bool(re.search(TTSAudio.REGEX_CHINESE, text))
233 |
234 | @staticmethod
235 | def is_korean(text: str) -> bool:
236 | """
237 | Returns true is text contains Korean x characters, false in other case.
238 |
239 | :param text: text to be checked.
240 | :return: True if is Korean, false in other case.
241 | """
242 | return bool(re.search(TTSAudio.REGEX_KOREAN, text))
243 |
244 | @staticmethod
245 | def is_cjk(text: str) -> bool:
246 | """
247 | Returns true is text contains Chinese, Japanese, Korean or other Chinese derivatives characters,
248 | false in other case.
249 |
250 | :param text: text to be checked.
251 | :return: True if is CJK, false in other case.
252 | """
253 |
254 | # regex = "/[\u3000-\u303F]|[\u3040-\u309F]|[\u30A0-\u30FF]|[\uFF00-\uFFEF]" + \
255 | # "|[\u4E00-\u9FAF]|[\u2605-\u2606]|[\u2190-\u2195]|\u203B/g"
256 | return TTSAudio.is_korean(text) or TTSAudio.is_japanese(text) or TTSAudio.is_chinese(text)
257 |
--------------------------------------------------------------------------------
/txt2SpeechBot/ttsbot.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | File containing Text_To_Speech_Bot class.
6 | """
7 |
8 | import requests
9 | import time
10 | import telebot
11 | import magic
12 | from telebot import types
13 | from typing import List, Callable, Dict, Optional
14 | from collections import OrderedDict
15 | from pydub import AudioSegment
16 | from io import BytesIO
17 | from helpers.constants import Constants
18 | from helpers.database import Database
19 | from helpers.utils import Utils
20 | from helpers.user import User
21 | from textToSpeech.ttsAudio import TTSAudio
22 | from audioStore.storedAudio import StoredAudio
23 |
24 |
25 | # region Bot Class
26 |
27 | class Text_To_Speech_Bot(TTSAudio, StoredAudio):
28 | """
29 | Python helper class to manipulate a text to speech bot using Telegram API.
30 | """
31 |
32 | def __init__(self, bot: telebot.TeleBot):
33 | """
34 | Creates and properly initializes a Telegram inline bot ready to be used.
35 |
36 | :param bot: Telegram bot from API.
37 | """
38 | self.bot: telebot.TeleBot = bot
39 | self.bot.set_update_listener(self.listener)
40 | self.bot.enable_save_next_step_handlers(delay=3)
41 | self.bot.load_next_step_handlers()
42 | self.queries: OrderedDict = OrderedDict()
43 | self.next_step_focused: Dict[str, types.Message] = {}
44 | Constants.MSG_LOG.log_also_to_stdout()
45 | Constants.QRY_LOG.log_also_to_stdout()
46 | Constants.STA_LOG.log_also_to_stdout()
47 |
48 | def listener(self, messages: List) -> None:
49 | """
50 | Listens and deals with all Telegram messages processed by bot.
51 |
52 | :param messages: List of Telegram messages.
53 | """
54 | for msg in messages:
55 | User.validate_user_from_telegram(msg.from_user)
56 | Utils.record_message(msg)
57 |
58 | def get_callback_query(self, callback: types.CallbackQuery) -> str:
59 | """
60 | Returns the description of an audio sent by bot.
61 |
62 | :param callback: Callback query to answer.
63 | :return: Audio description.
64 | :rtype: Str.
65 | """
66 | if text := self.get_callback_query_stored_audio(callback.data):
67 | return text
68 | elif text := self.get_callback_query_tts_audio(callback.data, self.queries):
69 | return text
70 | else:
71 | return ""
72 |
73 | def next_step(self, input_msg: types.Message, text_to_send: str, function: Callable) -> None:
74 | """
75 | Register the next action the bot should take. This method is helpful for multiple steps
76 | processes.
77 |
78 | :param input_msg: Telegram user message to reply.
79 | :param text_to_send: Text to be sent in bot reply.
80 | :param function: Next step to be processed.
81 | """
82 | reply = self.bot.reply_to(input_msg, text_to_send, reply_markup=types.ForceReply(selective=False))
83 | self.bot.register_next_step_handler(reply, function)
84 |
85 | def convert_to_voice(self, desc_msg: types.Message, file_msg: types.Message) -> Optional[types.Message]:
86 | """
87 | Converts any supported multimedia file in a Telegram compatible voice format.
88 |
89 | :param desc_msg: Telegram message containing audio description.
90 | :param file_msg: Telegram message containing audio file.
91 | """
92 | file_link = self.get_file_link(file_msg)
93 | downloaded_file = self.bot.download_file(self.bot.get_file(file_link.file_id).file_path)
94 | self.bot.send_message(file_msg.from_user.id, "Parsing file to telegram voice format")
95 | try:
96 | song = AudioSegment.from_file(BytesIO(downloaded_file))
97 | io_file = BytesIO()
98 | song.export(io_file, format="ogg", codec="libvorbis")
99 | except:
100 | mimetype = magic.from_buffer(downloaded_file, mime=True)
101 | Constants.STA_LOG.logger.exception(Constants.ExceptionMessages.AUDIO_ERROR % mimetype, exc_info=True)
102 | self.bot.send_message(6216877, 'Error trying to parse file with mimetype %s.' % mimetype)
103 | self.bot.reply_to(file_msg, "Unknown file format %s. Please, send another media file." % mimetype)
104 | return None
105 | else:
106 | new_msg = self.bot.send_voice(file_msg.from_user.id, io_file.read())
107 | self.next_step_focused[str(desc_msg.from_user.id)] = new_msg
108 | return new_msg
109 |
110 | # endregion
111 |
112 |
113 | my_bot = telebot.TeleBot(Constants.TOKEN)
114 | tts = Text_To_Speech_Bot(my_bot)
115 |
116 |
117 | # region Inline Mode
118 |
119 | @my_bot.inline_handler(lambda query: 0 <= len(query.query) <= 201)
120 | def query_handler(query: types.InlineQuery) -> None:
121 | """
122 | Answers with different purpose audios an inline query from an user.
123 |
124 | :param query: Telegram query.
125 | """
126 | User.validate_user_from_telegram(query.from_user)
127 | Utils.record_query(query)
128 | if not query.query:
129 | inline_results = tts.create_inline_results_stored_audio(query)
130 | else:
131 | inline_results = tts.create_inline_results_tts_audio(query, tts.queries)
132 | try:
133 | tts.bot.answer_inline_query(str(query.id), inline_results, cache_time=1)
134 | except Exception as query_exc:
135 | Constants.STA_LOG.logger.exception('Query: "' + query.query + '"', exc_info=True)
136 | tts.bot.send_message(6216877, 'Query: "' + query.query + '"\n' + str(query_exc))
137 |
138 |
139 | @my_bot.chosen_inline_handler(func=lambda chosen_inline_result: True)
140 | def chosen_result_handler(chosen_inline_result: types.ChosenInlineResult) -> None:
141 | """
142 | Updates previous database record with the selected inline result.
143 |
144 | :param chosen_inline_result: Telegram chosen inline result.
145 | """
146 | if len(chosen_inline_result.query) == 0:
147 | tts.update_chosen_results_stored_audio(chosen_inline_result)
148 | else:
149 | tts.update_chosen_results_tts_audio(chosen_inline_result)
150 | # tts.bot.send_message(6216877, 'a' + str(chosen_inline_result))
151 |
152 |
153 | @my_bot.callback_query_handler(func=lambda call: True)
154 | def callback_query_handler(callback: types.CallbackQuery) -> None:
155 | """
156 | Provides the user a description of the sent audio.
157 |
158 | :param callback: Telegram callback query.
159 | """
160 | text = tts.get_callback_query(callback)
161 | if len(text) > 54:
162 | tts.bot.answer_callback_query(callback.id, text, show_alert=True)
163 | else:
164 | tts.bot.answer_callback_query(callback.id, text)
165 |
166 | # endregion
167 |
168 |
169 | # region Bot Commands
170 |
171 | @my_bot.message_handler(commands=[Constants.BotCommands.START, Constants.BotCommands.HELP])
172 | def command_help(msg: types.Message) -> None: # TODO improve help message
173 | """
174 | Answers the user with a help message to help him to understand the purpose of this bot.
175 |
176 | :param msg: Telegram message with /help command.
177 | """
178 | tts.bot.send_message(msg.from_user.id, Constants.HELP_MSG)
179 |
180 |
181 | @my_bot.message_handler(commands=[Constants.BotCommands.ADD_AUDIO])
182 | def add_audio_start(msg: types.Message) -> None:
183 | """
184 | Initializes the process of audio uploading for user (1/3 Add Audio).
185 |
186 | :param msg: Telegram message with /addaudio command.
187 | """
188 | db_conn = Utils.create_db_conn()
189 | result = db_conn.read_one(Constants.DBStatements.AUDIOS_READ_COUNT % str(msg.from_user.id))
190 | if result and result[0] < 50:
191 | tts.next_step(msg, Constants.BotAnswers.SEND_AUDIO, add_audio_file)
192 | else:
193 | tts.bot.reply_to(msg, Constants.BotAnswers.MAX_OWN_AUDIOS)
194 |
195 |
196 | def add_audio_file(msg: types.Message) -> None:
197 | """
198 | Validates file received from user (2/3 Add Audio).
199 |
200 | :param msg: Telegram message with attached file.
201 | """
202 | if tts.validate_multimedia_file(msg):
203 | tts.next_step_focused[str(msg.from_user.id)] = msg
204 | tts.next_step(msg, Constants.BotAnswers.PROVIDE_DESC, add_audio_description)
205 | else:
206 | tts.bot.reply_to(msg, Constants.BotAnswers.NOT_AUDIO)
207 |
208 |
209 | def add_audio_description(msg: types.Message) -> None:
210 | """
211 | Downloads audio file and saves it with its respective description (3/3 Add Audio).
212 |
213 | :param msg: Telegram message with audio description.
214 | """
215 | db_conn = Utils.create_db_conn()
216 | description = Database.db_str(msg.text.strip())
217 | if msg.content_type == 'text' and len(description) <= 30:
218 | user_id = str(msg.from_user.id)
219 | result = db_conn.read_one(Constants.DBStatements.AUDIOS_READ_FOR_CHECKING % (user_id, description))
220 | if result is None:
221 | file_message = tts.next_step_focused[str(msg.from_user.id)]
222 | if not tts.is_file_valid_telegram_voice(file_message.content_type):
223 | file_message = tts.convert_to_voice(msg, file_message)
224 | if not file_message:
225 | return
226 |
227 | file_link = file_message.voice
228 | db_return = db_conn.read_all(Constants.DBStatements.AUDIOS_READ_USER_IDS % user_id)
229 | if len(db_return) > 0:
230 | taken_ids = [audio_id[0] for audio_id in db_return]
231 | user_audio_id = tts.get_stored_audio_free_id(taken_ids)
232 | else:
233 | user_audio_id = 1
234 | callback_code = Utils.generate_unique_str()
235 | db_conn.write_all(Constants.DBStatements.AUDIOS_INSERT % (file_link.file_id, user_id,
236 | description, file_link.duration,
237 | file_link.file_size, user_audio_id,
238 | callback_code))
239 | tts.bot.reply_to(file_message, Constants.BotAnswers.SAVED % description)
240 | else:
241 | tts.next_step(msg, Constants.BotAnswers.USED_DESC, add_audio_description)
242 | else:
243 | tts.next_step(msg, Constants.BotAnswers.WRONG_DESC, add_audio_description)
244 |
245 |
246 | @my_bot.message_handler(commands=[Constants.BotCommands.LST_AUDIO])
247 | def list_stored_audios(msg: types.Message) -> None:
248 | """
249 | Lists all the stored audios by a certain user and their details.
250 |
251 | :param msg: Telegram message with /listaudios command.
252 | """
253 | db_conn = Utils.create_db_conn()
254 | audio_str_list = tts.get_stored_audios_listing(str(msg.from_user.id), db_conn)
255 | if audio_str_list:
256 | tts.bot.reply_to(msg, audio_str_list)
257 | else:
258 | tts.bot.reply_to(msg, Constants.BotAnswers.LST_NONE_AUDIO)
259 |
260 |
261 | @my_bot.message_handler(commands=[Constants.BotCommands.RM_AUDIO])
262 | def rm_audio_start(msg: types.Message) -> None:
263 | """
264 | Lists all the stored audios by a certain user asks him to delete one of them
265 | (1/2 Remove One Audio).
266 |
267 | :param msg: Telegram message with /rmaudio command.
268 | """
269 | list_stored_audios(msg)
270 | db_conn = Utils.create_db_conn()
271 | result = db_conn.read_one(Constants.DBStatements.AUDIOS_READ_FOR_REMOVING % str(msg.from_user.id))
272 | if result:
273 | tts.next_step(msg, Constants.BotAnswers.RM_AUDIO, rm_audio_select)
274 |
275 |
276 | def rm_audio_select(msg: types.Message) -> None:
277 | """
278 | Removes an uploaded audio by a determined user if description equals the received
279 | message from that user (2/2 Remove One Audio).
280 |
281 | :param msg: Telegram message with removing confirmation.
282 | """
283 | if msg.content_type == 'text' and msg.text:
284 | db_conn = Utils.create_db_conn()
285 | audio_to_rm = Database.db_str(msg.text.strip())
286 | user_id = str(msg.from_user.id)
287 | result = db_conn.read_one(Constants.DBStatements.AUDIOS_READ_FOR_CHECKING % (user_id, audio_to_rm))
288 | if result:
289 | db_conn.write_all(Constants.DBStatements.AUDIOS_REMOVE % (user_id, audio_to_rm))
290 | tts.bot.reply_to(msg, Constants.BotAnswers.DELETED_AUDIO)
291 | else:
292 | tts.bot.reply_to(msg, Constants.BotAnswers.RM_USED_DESC)
293 | else:
294 | tts.bot.reply_to(msg, Constants.BotAnswers.RM_DESC_NOT_TEXT)
295 |
296 |
297 | @my_bot.message_handler(commands=[Constants.BotCommands.RM_ALL_AUDIOS])
298 | def rm_all_audios(msg: types.Message) -> None:
299 | """
300 | Lists all the stored audios by a certain user asks him to delete all of them.
301 | (2/2 Remove All Audios)
302 |
303 | :param msg: Telegram message with /rmallaudios command.
304 | """
305 | list_stored_audios(msg)
306 | db_conn = Utils.create_db_conn()
307 | result = db_conn.read_one(Constants.DBStatements.AUDIOS_READ_FOR_REMOVING % str(msg.from_user.id))
308 | if result:
309 | tts.next_step(msg, Constants.BotAnswers.RM_ALL_AUDIO, confirm_rm_all_audios)
310 |
311 |
312 | def confirm_rm_all_audios(msg: types.Message) -> None:
313 | """
314 | Removes all previous uploaded audios by a determined user (2/2 Remove All Audios).
315 |
316 | :param msg: Telegram message with removing confirmation.
317 | """
318 | if msg.content_type == 'text' and msg.text and msg.text.strip() == 'CONFIRM':
319 | db_conn = Utils.create_db_conn()
320 | remove_result = db_conn.write_all(Constants.DBStatements.AUDIOS_REMOVE_ALL % str(msg.from_user.id))
321 | if remove_result:
322 | tts.bot.reply_to(msg, Constants.BotAnswers.DELETED_ALL_AUDIO)
323 | else:
324 | tts.bot.reply_to(msg, Constants.BotAnswers.RM_ALL_NOT_CONFIRM)
325 |
326 | # endregion
327 |
328 |
329 | while True:
330 | try:
331 | tts.bot.polling(none_stop=True)
332 | except requests.exceptions.ConnectionError as requests_exc:
333 | Constants.STA_LOG.logger.exception(Constants.ExceptionMessages.UNEXPECTED_ERROR, exc_info=True)
334 | time.sleep(10)
335 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------