-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
287 lines (251 loc) · 11.7 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import logging
import os
import sys
import subprocess
import time
import io
import argparse
import configparser
import uuid
import posthog
from PySide6.QtWidgets import *
from PySide6.QtCore import *
import sqlite3
# Hide Pygame support prompt
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
import pygame
pygame.mixer.init()
def ynbox(message: str, header: str, timeout: int = 10000):
try:
ynInstance = QMessageBox(None)
ynInstance.setWindowTitle(header)
ynInstance.setText(message)
ynInstance.setStandardButtons(QMessageBox.StandardButton.Yes)
ynInstance.addButton(QMessageBox.StandardButton.No)
timer = QTimer(None)
timer.singleShot(timeout, lambda: ynInstance.button(QMessageBox.StandardButton.No).animateClick())
return ynInstance.exec() == QMessageBox.StandardButton.Yes
except Exception as error:
logging.error("Message Error: {}".format(error), exc_info=True)
def msgbox(message: str, header: str, timeout: int = 10000):
try:
msgInstance = QMessageBox(None)
msgInstance.setWindowTitle(header)
msgInstance.setText(message)
msgInstance.setStandardButtons(QMessageBox.StandardButton.Ok)
timer = QTimer(None)
timer.singleShot(timeout, lambda: msgInstance.button(QMessageBox.StandardButton.Ok).animateClick())
return msgInstance.exec() == QMessageBox.StandardButton.Ok
except Exception as error:
logging.error("Message Error: {}".format(error), exc_info=True)
def configure_app():
# determine if application is a script file or frozen exe
if getattr(sys, 'frozen', False):
application_path = os.path.dirname(sys.executable)
exe_name = ""
for root, dirs, files in os.walk(application_path):
for file in files:
if "Configure TranslateAndTTS" in file:
exe_name = file
GUI_path = os.path.join(application_path, exe_name)
# Use subprocess.Popen to run the executable
process = subprocess.Popen(GUI_path)
# Wait for the process to complete
process.wait()
elif __file__:
application_path = os.path.dirname(__file__)
GUI_script_path = os.path.join(application_path, 'GUI_TranslateAndTTS', 'widget.py')
process = subprocess.run(["python", GUI_script_path])
def get_paths(args: vars):
if args['config'] != '' and os.path.exists(args['config']):
config_path = args['config']
audio_files_path = os.path.join(os.path.dirname(config_path), 'WAV Files')
else:
# determine if application is a script file or frozen exe
if getattr(sys, 'frozen', False):
# Get the path to the user's app data folder
home_directory = os.path.expanduser("~")
application_path = os.path.join(home_directory, 'AppData', 'Roaming', 'TranslateAndTTS')
elif __file__:
application_path = os.path.dirname(__file__)
audio_files_path = os.path.join(application_path, 'Audio Files')
config_path = os.path.join(application_path, 'settings.cfg')
# Check if the directory already exists
if not os.path.exists(audio_files_path):
# Create the "Audio Files" directory
os.makedirs(audio_files_path)
# Check if the file already exists
if not os.path.exists(config_path):
message = '\n\n Do You want to open the Configuration Setup?'
try:
result = ynbox("settings.cfg file not found." + message, 'Error')
if result:
configure_app()
else:
message = "\n\n Please Run 'Configure TranslateAndTTS executable' first."
response = msgbox("settings.cfg file not found. " + message, 'Error')
sys.exit(response)
except Exception as error:
logging.error("Configuration Error: {}".format(error), exc_info=True)
return config_path, audio_files_path
def play_audio(audio_bytes, file: bool = False):
if file:
audio_stream = audio_bytes
else:
audio_stream = io.BytesIO(audio_bytes)
pygame.mixer.music.load(audio_stream)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
continue
def save_audio(audio_bytes: bytes, text: str, engine: str, format: str = 'wav'):
timestr = time.strftime("%Y%m%d-%H%M%S.")
filename = os.path.join(audio_files_path, timestr + format)
sql = "INSERT INTO History(text, filename, engine) VALUES('{}','{}','{}')".format(text, timestr + format, engine)
with open(filename, 'wb') as out_file:
out_file.write(audio_bytes)
try:
connection = sqlite3.connect(os.path.join(audio_files_path, 'cache_history.db'))
connection.execute(sql)
connection.commit()
connection.close()
except Exception as error:
logging.error("Database Error: {}".format(error), exc_info=True)
def get_uuid():
try:
# Note: Remove uuid config every commit
# Code will raise an exception at first run due to blank uuid
identifier = uuid.UUID(config.get('App', 'uuid'))
except Exception as error:
identifier = uuid.uuid4()
config.set('App', 'uuid', str(identifier))
with open(config_path, 'w') as configfile:
config.write(configfile)
logging.error("Failed to get uuid: {}".format(error), exc_info=True)
logging.info("uuid: {}".format(identifier), exc_info=True)
return str(identifier)
def notify_posthog(id: str, event_name: str, properties: dict = {}):
try:
posthog_client = posthog.Posthog(project_api_key='phc_q37FBcmTQD1hHtNBgqvs9wid45gKjGKEJGduRkPog0t',
host='https://app.posthog.com')
# Attempt to send the event to PostHog
posthog_client.capture(distinct_id=id, event=event_name, properties=properties)
print(f"Event '{event_name}' captured successfully!")
except Exception as e:
# Handle the case when there's an issue with sending the event
print(f"Failed to capture event '{event_name}': {e}")
logging.error("Failed to capture event '{}': {}".format(event_name, e), exc_info=True)
# You can add further logic here if needed, such as logging the error or continuing the script
pass
def check_history(text: str):
try:
if args['style']:
return None
if os.path.isfile(os.path.join(audio_files_path, 'cache_history.db')):
sql = "SELECT filename FROM History WHERE text='{}'".format(text)
connection = sqlite3.connect(os.path.join(audio_files_path, 'cache_history.db'))
cursor = connection.execute(sql)
results = cursor.fetchone()
base_name = results[0] if results is not None else None
if base_name is not None:
file = os.path.join(audio_files_path, base_name)
connection.close()
return file
else:
return None
else:
create_Database()
return None
except Exception as error:
logging.error("Failed to connect to database: ".format(error), exc_info=True)
return None
def clear_history(files: list):
try:
if os.path.isfile(os.path.join(audio_files_path, 'cache_history.db')) and len(files) > 0:
connection = sqlite3.connect(os.path.join(audio_files_path, 'cache_history.db'))
for file in files:
sql = "DELETE FROM History WHERE filename='{}'".format(file)
connection.execute(sql)
connection.commit()
connection.close()
except Exception as error:
logging.error("Failed to connect to database: ".format(error), exc_info=True)
return None
def create_Database():
try:
if not os.path.isfile(os.path.join(audio_files_path, 'cache_history.db')):
sql1 = """CREATE TABLE IF NOT EXISTS "History" ("id" INTEGER NOT NULL UNIQUE,
"text" TEXT NOT NULL,
"filename" TEXT NOT NULL,
"engine" TEXT NOT NULL,
UNIQUE("id"),
PRIMARY KEY("id" AUTOINCREMENT));"""
sql2 = """CREATE UNIQUE INDEX IF NOT EXISTS "id_text" ON "History" ("text");"""
connection = sqlite3.connect(os.path.join(audio_files_path, 'cache_history.db'))
connection.execute(sql1)
connection.execute(sql2)
connection.close()
logging.info("Cache database is created.")
else:
logging.info("Cache database is found")
except Exception as error:
logging.error("Failed to create database: ".format(error), exc_info=True)
def update_Database(file):
try:
if not os.path.isfile(os.path.join(audio_files_path, 'cache_history.db')):
pass
else:
logging.info("Cache database is found: ")
except Exception as error:
logging.error("Failed to update database: ".format(error), exc_info=True)
parser = argparse.ArgumentParser(
description='Reads pasteboard. Translates it. Speaks it out. Or any variation of that')
parser.add_argument(
'-c', '--config', help='Path to a defined config file', required=False, default='')
parser.add_argument(
'-l', '--listvoices', help='List Voices to see whats available', required=False, default=False, action="store_true")
parser.add_argument(
'-p', '--preview', help='Preview Only', required=False, default=False, action="store_true")
parser.add_argument(
'-s', '--style', help='Voice style for Azure TTS', required=False, default='')
parser.add_argument(
'-sd', '--styledegree', type=float, help='Degree of style for Azure TTS', required=False, default=None)
args = vars(parser.parse_args())
logging.info(str(args))
(config_path, audio_files_path) = get_paths(args=args)
config = configparser.ConfigParser()
current_path = os.path.dirname(config_path)
# Need to set initial path if no config file was found.
if os.path.isdir(current_path):
logging.basicConfig(filename=os.path.join(current_path, 'app.log'),
filemode='a',
format="%(asctime)s — %(name)s — %(levelname)s — %(funcName)s:%(lineno)d — %(message)s",
level=logging.DEBUG,
force=True)
try:
# print(config_path)
if os.path.isfile(config_path):
config.read(config_path)
Allow_Collecting_Stats = config.getboolean('App', 'collectstats')
else:
msg = "\n\n Please Run 'Configure TranslateAndTTS executable' first."
result = msgbox("settings.cfg file not found. " + msg, 'Error')
sys.exit()
except Exception as e:
logging.error("Configuration Error {}".format(e), exc_info=True)
sys.exit()
if Allow_Collecting_Stats:
start = time.perf_counter()
distinct_id = get_uuid()
event_name = 'App Run'
event_properties = {
'uuid': distinct_id,
'source': 'helperApp',
'version': '1.1',
'fromLang': config.get('translate', 'startlang'),
'toLang': config.get('translate', 'endlang'),
'ttsengine': config.get('TTS', 'engine'),
}
notify_posthog(distinct_id, event_name, event_properties)
stop = time.perf_counter() - start
print(f"Posthog runtime is {stop:0.5f} seconds.")
logging.info(f"Posthog runtime is {stop:0.5f} seconds.")