-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.py
executable file
·715 lines (639 loc) · 22.8 KB
/
main.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tesserocr import PyTessBaseAPI, RIL
import pyautogui
import json
import base64
import os
import bs4
import eyed3
import pytesseract
from moviepy.editor import VideoFileClip
import billboard
import time
import random
import difflib
import csv
import subprocess
import re
from PyLyrics import *
#import Image, ImageChops, ImageDraw, ImageFont, ImageFilter
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
import glob
import threading
import sys
import itertools
reload(sys)
sys.setdefaultencoding('utf8')
counter = {"lev": 500, "item": ""}
lock = threading.Lock()
APIKEY = open('apiKey.txt','r').read()
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def PrintWarning(warningtext):
print '\n' + bcolors.WARNING + warningtext + bcolors.ENDC
def PrintFail(failtext):
print '\n' + bcolors.FAIL + failtext + bcolors.ENDC
def PrintGood(goodtext):
print '\n' + bcolors.OKGREEN + goodtext + bcolors.ENDC
###############################################################################3
## Utilities
def stripExtension(filename):
return filename[:filename.rfind('.')]
def stripPath(filename):
return filename[filename.rfind('/') + 1:]
def findPath(filename):
return filename[:filename.rfind('/') + 1]
def convertBase(image):
return base64.b64encode(open(image, "rb").read())
def genReqJson(image):
a = open("Request.json", "r").read()
a = a.replace('BASE', convertBase(image))
return str(json.dumps(a))
def genCurl(basefile):
a = 'curl -v -s -H "Content-Type: application/json" https://vision.googleapis.com/v1/images:annotate?key={} --data-binary @{}'.format(APIKEY, basefile)
return a
def ocrImage(image):
inpu = open('Request.json', 'r')
out = open('Request.tmp', 'w')
out.write(inpu.read().replace('BASE', convertBase(image)))
out.close()
a = genCurl("Request.tmp")
os.system("{} > tmp.json".format(a))
with open('tmp.json') as json_data:
d = json.load(json_data)
return d['responses'][0]['textAnnotations'][0]['description']
def ReturnFileName(file):
return str(file).partition('.')[0]
def ReturnFileExtension(file):
return str(file).partition('.')[2]
def process_item(lent=None, item=None, lenorig=0):
global counter
lock.acquire()
if lent != None:
print(str(lent), str(item))
if lent < counter["lev"]:
counter["lev"] = lent
counter["item"] = str(item)
lock.release()
else:
f = counter["item"]
counter = {"lev": 500, "item": ""}
lock.release()
return f
def LevList(listone, listtwo):
#a = len(set(listtwo) - set(listone))
a = 0
'''for i, words in enumerate(listone):
try:
#print(words)
a = a + levenshtein(words, listtwo[i])
except:
pass'''
try:
if list(''.join(listtwo))[0] == list(''.join(listone))[0] or list(''.join(listtwo))[1] == list(''.join(listone))[1]:
if list(''.join(listtwo))[-1] == list(''.join(listone))[-1] or list(''.join(listtwo))[-2] == list(''.join(listone))[-2]:
print(list(''.join(listtwo))[0])
print(list(''.join(listone))[0])
a = len(set(listtwo) - set(listone))
process_item(a, str(' '.join(listtwo)), len(listone))
except:
pass
def LowestSetOfNumbers(wordslist, lyrics):
threads = []
for i in range(len(lyrics)):
listone = wordslist
listtwo = lyrics[i:i+len(wordslist)]
if abs(len(listone) - len(listtwo)) < 5:
t = threading.Thread(target=LevList, args=(listone,listtwo))
threads.append(t)
t.start()
for t in threads:
t.join()
return process_item()
def PromptList(text, inputted):
PrintWarning('Initiated the list function\n')
if inputted != None:
return [inputted]
List = []
while True:
New = raw_input(text)
if New != '':
List.append(New)
else:
if len(List) == 0:
PrintFail('You need to input something here')
else:
if 'Y' in str(raw_input("Are you sure you don't want to input anymore? Y/N ")).upper():
return List
def levenshtein(s1, s2):
if len(s1) < len(s2):
return levenshtein(s2, s1)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
def nextInList(smalist, biglist):
##Fix this function
try:
smalist = [item.encode('utf-8') for item in smalist]
biglist = [item.encode('utf-8') for item in biglist]
print(smalist)
print('Biglist: {}'.format(biglist))
words = str(smalist).partition("'',")
try:
beforeword = words[0].split(',')[-2].replace('"', '').replace("'", "").replace(' ', '')
except:
return ''
print(beforeword)
afterword = words[2].split(',')[0].replace('"', '').replace("'", "").replace(' ', '')
print(afterword)
d = str((re.findall("{}.,(.*){}".format(beforeword, afterword), str(biglist))))
print(d)
d = d.split(',')[0]
guess = ''.join(re.findall('\w', d))
print(guess)
#raw_input("Before {}\nMiddle {}\nAfter {}".format(beforeword, guess, afterword))
return guess
'''raw_input("cnf")
for idx, wor in enumerate(biglist):
wor = ''.join(filter(str.isalpha, str(wor).lower()))
beforeword = ''.join(filter(str.isalpha, str(beforeword).lower()))
print(wor)
print(beforeword)
if wor == beforeword:
print('found word')
if ''.join(filter(str.isalpha, str(wor[(idx + 2) % len(wor)]).lower())) == ''.join(filter(str.isalpha, str(afterword).lower())):
print('word found: {}'.format(str(wor[(idx + 1) % len(wor)]).lower()))
raw_input('test')
return str(wor[(idx + 1) % len(wor)]).lower()'''
except Exception as exp:
raw_input(exp)
return ''
'''x = x.replace("'", "")
x = x.replace('\\n', '')
x = x.replace('\\t', '')
x = x.replace(' ', '')'''
def ReturnAll(folder, fileextension='mp3'):
return glob.glob("{}/*.{}".format(folder, fileextension))
def findSong(artist, song):
return genYoutube('{} {} lyrics'.format(artist, song))
def genYoutube(string):
string = string.replace(' ', '+')
URL = 'https://www.youtube.com/results?search_query={}'.format(string)
res = requests.get(URL, headers=LoadHeader())
page = bs4.BeautifulSoup(res.text, "lxml")
Result = page.select('.item-section > li .clearfix')
Results = []
for number in Result:
if 'Duration' in str(number):
Results.append(number)
VideoID = str(Results[0].select('.overflow-menu-choice')[0]).partition('data-video-ids="')[2].partition('" onclick="')[0]
URL = 'https://www.youtube.com/watch?v={}'.format(VideoID)
return URL
def GetDuration(clip):
if '.mp4' in str(clip):
return VideoFileClip(clip).duration
elif '.mp3' in str(clip):
return eyed3.load('{}'.format(clip)).info.time_secs
def LoadHeader():
UserAgentCSV = open('UserAgent.csv', 'r')
UserAgentList = csv.reader(UserAgentCSV)
UserAgentList = [row for row in UserAgentList]
UserAgentList = [l[0] for l in UserAgentList]
random.shuffle(UserAgentList)
return {'User-Agent': random.choice(UserAgentList)}
def CombineVidandAudio(audio, video):
audio = str(audio).replace('.mp3', '')
video = str(video).replace('.mp4', '')
video = str(video).replace('.avi', '')
print video
filename = str(video).replace('.mp4', '')
os.system('ffmpeg -i {}.mp3 -i {}.mp4 -y -strict -2 {}z.mp4'.format(audio, video, filename))
#os.system('ffmpeg -i {} -i {} -c:v copy -c:a aac -strict experimental -map 0:v:0 -map 1:a:0 {}z.mp4'.format(video, audio, filename))
os.remove('{}.mp4'.format(filename))
os.system('mv {}z.mp4 {}.mp4'.format(filename, filename))
#those weird lines above need to be done because FFMPEG doesn't correctly overwrite files
return '{}.mp4'.format(filename)
def CombineAudioandImage(audio, image=None, output=None):
if image == None:
image = GenerateBackground()
if output == None:
output = str(audio)
output = str(output).replace('.wav', '')
output = str(output).replace('.mp3', '')
os.system("ffmpeg -loop 1 -i {} -i {} -y -c:v libx264 -tune stillimage -c:a aac -b:a 192k -pix_fmt yuv420p -shortest -strict -2 {}.mp4".format(image, audio, output))
##############################################################################################
## Generate
def GenerateNewMusic():
return billboard.ChartData('hot-100')
def GenerateBackground():
return random.choice(glob.glob("src/backgrounds/*.jpg"))
def ReturnAll(folder, extension='mp3'):
return glob.glob("{}/*.{}".format(folder, extension))
def GetDuration(clip):
if '.mp4' in str(clip): return VideoFileClip(clip).duration
elif '.mp3' in str(clip): return eyed3.load('{}'.format(clip)).info.time_secs
def GrabSongLyrics(artist, song):
return str(PyLyrics.getLyrics(artist, song)).replace('\n', ' ').replace('\t', '').split(' ')
##########################################################################
## Video
def ExtractFrames(video, folder=None):
f = 0
threads = []
def doCommand(videourl, folder, i):
print('Frame {} Completed'.format(i))
os.system("ffmpeg -loglevel panic -ss {} -i {}.mp4 -y {}/{}.jpg".format(i, videourl, folder, i))
if folder == None:
folder = str(random.randint(1, 10000))
os.system('mkdir {}'.format(folder))
videourl = video.replace('.mp4', '')
for i in range(1, int(GetDuration('{}.mp4'.format(videourl)))):
t = threading.Thread(target=doCommand, args=(videourl, folder, i))
threads.append(t)
t.start()
f = f + 1
if f % 10 == 0:
time.sleep(2)
for t in threads:
t.join()
def CompareOCR(video, folder=None):
ExtractFrames(video, folder)
findLyrics(ReturnAll(folder, 'jpg'), listofwords=[''])
def DownloadVideo(url, saveas='Vid.mp4'):
os.system("youtube-dl -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4' --output {} {} 2> /dev/null".format(saveas, url))
return saveas
def YoutubeToFrames(url=None):
PrintGood('This function convert youtube video into frames in a randomly created folder')
PrintWarning("This fails a bunch of times, but it still runs - IDK why")
if isinstance(url, list) == False:
url = PromptList('Which image/images to convert from frames: ', url)
for url in url:
video = DownloadVideo(url, saveas='Vid.mp4')
ExtractFrames(video)
def SpeedUpVideo(vidfile, percent=1.25):
print "Starting speed up video"
setpts = 1.0 / float(percent)
extension = ''.join(vidfile.partition('.')[1:])
saveas = vidfile.partition('.')[0] + 'z' + extension
os.system('ffmpeg -i {} -filter:v "setpts={}*PTS" {}'.format(vidfile, setpts, saveas))
os.system('rm {}'.format(vidfile))
os.system('mv {} {}'.format(saveas, vidfile))
return vidfile
######################################################################################
## OCR
def RetrOCR(image=None, listofwords=[]):
if len(listofwords) == 0:
PrintFail('You need to input a list of words')
if 'y' in str(raw_input("Do you want to search for lyrics now? ")).lower():
artist = raw_input("Artist: ")
song = raw_input("Song: ")
listofwords = GrabSongLyrics(artist, song)
print(listofwords)
else:
return
if isinstance(image, list) == False:
image = PromptList('Which image/images to Scan: ', image)
for image in image:
WordsInImage = []
#spaces = Spaces(image)
lines = genLines(image)
print(lines)
for e in range(len(lines)):
for wordlyric in lines[e]:
try:
a = difflib.get_close_matches(wordlyric, listofwords)[0]
wordlyric = a
WordsInImage.append(wordlyric)
except Exception as exp:
print exp
WordsToSet = ' '.join(WordsInImage)
imagelocation = image[:image.rfind('/') + 1]
WriteToImage(image, WordsToSet, size=45, input=image)
os.system("mkdir OCR &> /dev/null/")
for result in glob.glob("{}/*.png".format(imagelocation)):
resultz = result.partition('/')[2]
os.system("mv {} OCR/{}".format(result, resultz))
def genLines(image=None):
PrintGood('This is going to return OCR on either a list of images or full images')
if isinstance(image, list) == False:
image = PromptList('Which image/images to OCR: ', image)
Found = []
for image in image:
image = Image.open(image)
with PyTessBaseAPI() as api:
api.SetImage(image)
boxes = api.GetComponentImages(RIL.TEXTLINE, True)
print 'Found {} textline image components.'.format(len(boxes))
for i, (im, box, _, _) in enumerate(boxes):
# im is a PIL image object
# box is a dict with x, y, w and h keys
api.SetRectangle(box['x'], box['y'], box['w'], box['h'])
ocrResult = api.GetUTF8Text().split(' ')
conf = api.MeanTextConf()
ocrResult = [word.strip() for word in ocrResult]
Found.append(ocrResult)
print (u"Box[{0}]: x={x}, y={y}, w={w}, h={h}, "
"confidence: {1}, text: {2}").format(i, conf, ocrResult, **box)
return Found
def genCords(image=None, listofwords=[]):
AllWords = []
PrintGood('This is going to return individual images for every undefined word found')
if len(listofwords) == 0:
PrintWarning("This is going to save all words, to define words to look for input a list containing words for tesseract to find.\n")
if 'y' in str(raw_input("Do you want to search for lyrics now? ")).lower():
artist = raw_input("Artist: ")
song = raw_input("Song: ")
listofwords = GrabSongLyrics(artist, song)
listofwords = [x.upper() for x in listofwords]
listofwords = [i.replace('\n','') for i in listofwords]
listofwords = [i.replace('\t','') for i in listofwords]
print(listofwords)
else:
return
if isinstance(image, list) == False:
image = PromptList('Which image/images to OCR: ', image)
for image in image:
im = Image.open(image)
os.system("tesseract {} stdout -c tessedit_create_hocr=1 -c tessedit_pageseg_mode=1 -l eng -psm 3 > index.html".format(image))
page = bs4.BeautifulSoup(open("index.html")).select('#page_1')
for x in page[0].select('.ocrx_word'):
text = x.getText().encode('ascii', 'ignore').decode('ascii')
coordinates = str(re.findall("bbox\s(.*);", str(x))[0]).split(' ')
coordinates = tuple([float(i) for i in coordinates])
if str(text).upper() not in listofwords:
try:
f = im.crop(coordinates)
with PyTessBaseAPI() as api:
api.SetImage(f)
ocrResult = api.GetUTF8Text()
conf = api.MeanTextConf()
print("confidence: {}".format(conf))
f.save('{}.jpg'.format(text))
except Exception as exp:
print(exp)
PrintWarning("Error, the following text was ignored: \"{}\"\nThe program will continue running\n".format(text))
else:
AllWords.append(text)
return AllWords
def Spaces(image=None):
PrintGood('This returns the number of spaces in a specific image or images')
if isinstance(image, list) == False:
image = PromptList('Which image/images to Scan: ', image)
for image in image:
image = Image.open(image)
with PyTessBaseAPI() as api:
api.SetImage(image)
boxes = api.GetComponentImages(RIL.TEXTLINE, True)
Spaces = 0
for i, (im, box, _, _) in enumerate(boxes):
im.save('saving{}.jpg'.format(i))
api.SetRectangle(box['x'], box['y'], box['w'], box['h'])
ocrResult = api.GetUTF8Text()
conf = api.MeanTextConf()
text = str(ocrResult).replace('\n', '').split(' ')
Spaces = len(text) + Spaces
return int(Spaces)
def findLyrics(image=None, listofwords=[]):
PrintGood('This is going to successfully OCR lyric screenshots')
if len(listofwords) == 0:
PrintFail('You need to input a list of words')
if 'y' in str(raw_input("Do you want to search for lyrics now? ")).lower():
artist = raw_input("Artist: ")
song = raw_input("Song: ")
listofwords = GrabSongLyrics(artist, song)
print(listofwords)
else:
return
if isinstance(image, list) == False:
image = PromptList('Which image/images to Scan: ', image)
for image in image:
WordsInImage = []
spaces = Spaces(image)
lines = genLines(image)
print(lines)
for e in range(len(lines)):
for wordlyric in lines[e]:
if wordlyric not in listofwords:
print('not in list of words: {}'.format(wordlyric))
for words in listofwords:
A = False
if levenshtein(wordlyric, words) < 1:
A = True
WordsInImage.append(words)
break
if A == False:
WordsInImage.append(["", wordlyric])
else:
print('appended: {}'.format(wordlyric))
WordsInImage.append(wordlyric)
for w in WordsInImage:
if len(w[1]) > 1:
w = nextInList(WordsInImage, listofwords)
print(w)
def writeLyrics(image=None, listofwords=[]):
imagez = GenerateBackground()
if len(listofwords) == 0:
PrintFail('You need to input a list of words')
if 'y' in str(raw_input("Do you want to search for lyrics now? ")).lower():
artist = raw_input("Artist: ")
song = raw_input("Song: ")
listofwords = GrabSongLyrics(artist, song)
print(listofwords)
else:
return
if isinstance(image, list) == False:
image = PromptList('Which image/images to Scan: ', image)
for image in image:
WordsInImage = []
#spaces = Spaces(image)
lines = genLines(image)
print(lines)
for e in range(len(lines)):
for wordlyric in lines[e]:
if wordlyric not in listofwords:
print('not in list of words: {}'.format(wordlyric))
for words in listofwords:
A = False
if levenshtein(wordlyric, words) < 1:
A = True
WordsInImage.append(words)
break
if A == False:
WordsInImage.append("")
else:
print('appended: {}'.format(wordlyric))
WordsInImage.append(wordlyric)
e = []
WordsToSet = LowestSetOfNumbers(WordsInImage, listofwords)
if len(WordsToSet) == 0:
WordsToSet = ' '.join(WordsInImage)
imagelocation = image[:image.rfind('/') + 1]
WriteToImage(image, WordsToSet, size=45, input=imagez)
os.system("mkdir OCR &> /dev/null/")
for result in glob.glob("{}/*.png".format(imagelocation)):
resultz = result.partition('/')[2]
os.system("mv {} OCR/{}".format(result, resultz))
def imageToOCR(image, listofwords):
WordsInImage = []
lines = genLines(image)
for e in range(len(lines)):
for wordlyric in lines[e]:
if wordlyric not in listofwords:
print('not in list of words: {}'.format(wordlyric))
for words in listofwords:
A = False
if levenshtein(wordlyric, words) < 1:
A = True
WordsInImage.append(words)
break
if A == False:
WordsInImage.append("")
else:
print('appended: {}'.format(wordlyric))
WordsInImage.append(wordlyric)
e = []
WordsToSet = LowestSetOfNumbers(WordsInImage, listofwords)
if len(WordsToSet) == 0:
WordsToSet = ' '.join(WordsInImage)
return WordsToSet
def ocrToDict(image=None, listofwords=[]):
#image can be a list of files
Words = {}
if len(listofwords) == 0:
PrintFail('You need to input a list of words')
if 'y' in str(raw_input("Do you want to search for lyrics now? ")).lower():
artist = raw_input("Artist: ")
song = raw_input("Song: ")
listofwords = GrabSongLyrics(artist, song)
print(listofwords)
else:
return
if isinstance(image, list) == False:
image = PromptList('Which image/images to Scan: ', image)
for i, image in enumerate(image):
Words['Clean'][i] = imageToOCR(image, listofwords)
with open('{}Transcript.json'.format(Words[1]), 'w') as f:
json.dump(Words, f)
def genNC(image=None, listofwords=[], artist=None, song=None):
Words = {}
Information = {}
for i, image in enumerate(image):
i = i + 1
Words[i] = pytesseract.image_to_string(Image.open(image))
Information['GuessedWords'] = Words
Information["Real_Lyrics"] = listofwords
with open('{}Transcript.json'.format(Words[1]), 'w') as f:
json.dump(Information, f)
def readOCR(jsonfile):
with open(jsonfile) as data_file:
data = json.load(data_file)
for i in range(1, len(data)):
print('{}-{}'.format(i, data[str(i)]))
############################################################################################3
## Audio
def ExtractAudio(filename):
#This receives a .mp4 file but it removes .mp4 because the alternative seemed confusing af
#filename = str(filename).replace('.mp4', '')
#os.system('ffmpeg -i {}.mp4 -y {}.mp3'.format(filename, filename))
video = VideoFileClip(filename.replace(".mp4", "") + ".mp4")
video.audio.write_audiofile(filename + ".mp3")
return '{}.mp3'.format(filename)
def genCIL(file, v=2, speed=1.25, pitch=38, silence=1):
saveas = ReturnFileName(file)
os.system('sox -v {}.0 {} finished.mp3 speed {} pitch +{}'.format(v, file, speed, pitch, silence))
os.system('mv finished.mp3 {}.mp3'.format(saveas))
def clickFile():
pyautogui.click(pyautogui.locateCenterOnScreen('src/images/audacity_fileButton.png'))
def clickApplyChain():
pyautogui.click(pyautogui.locateCenterOnScreen('src/images/audacity_applyChain.png'))
def clickApplyToFile():
pyautogui.click(pyautogui.locateCenterOnScreen('src/images/audacity_applyToCurrentFile.png'))
def maxWindow():
try:
pyautogui.click(pyautogui.locateCenterOnScreen('src/images/discard.png'))
time.sleep(1)
pyautogui.click(pyautogui.locateCenterOnScreen('src/images/yes.png'))
except:
pass
time.sleep(1)
if len(list(pyautogui.locateAllOnScreen('src/images/audacity_fileButton.png'))) > 1:
pyautogui.keyDown('alt')
pyautogui.press('f10')
pyautogui.keyUp('alt')
def applyChain(file):
p = subprocess.Popen(["audacity", "./{}".format(file)])
raw_input("Apply chain: ")
'''time.sleep(7)
maxWindow()
print("Clicked max window")
time.sleep(1)
clickFile()
print("Clicked file")
time.sleep(2)
clickApplyChain()
print("Clicked apply chain")
time.sleep(2)
clickApplyToFile()
print("Clicked apply to file")
time.sleep(10)
p.terminate()
print("Terminate p")
print('Done')'''
######################################################################################################
## Image
def genVidFromFolder(folder, saveas="output.mp4"):
os.system("ffmpeg -framerate 1 -y -i {}/%d.png {}".format(folder, saveas))
return "{}/{}".format(folder, saveas)
def draw_text_with_halo(img, position, text, font, col, halo_col):
halo = Image.new('RGBA', img.size, (0, 0, 0, 0))
ImageDraw.Draw(halo).text(position, text, font = font, fill = halo_col)
blurred_halo = halo.filter(ImageFilter.BLUR)
ImageDraw.Draw(blurred_halo).text(position, text, font = font, fill = col)
return Image.composite(img, blurred_halo, ImageChops.invert(blurred_halo))
def WriteToImage(output, txt, size=45, input='background.jpg'):
output = str(output).replace('.png', '').replace('.jpg', '')
i = Image.open(input)
font = ImageFont.load_default()
txt = txt.split(' ')
r = []
for part in txt:
r.append(str(part).replace(' ', ''))
txt = r
a = ''
while len(txt) > 0:
try:
for e in range(7):
item = txt[0]
txt.remove(item)
a = a + ' ' + str(item)
a = a + '\n'
except:
break
text_col = (255, 255, 255) # bright green
halo_col = (0, 0, 0) # black
i2 = draw_text_with_halo(i, (20, 40), a, font, text_col, halo_col)
i2.save('{}.png'.format(output))
if __name__ == "__main__":
print('started')
#main.findLyrics(image=main.ReturnAll('beware_of_darkness_all_who_remain', 'jpg'), listofwords=[])
#main.RetrOCR(image=main.ReturnAll('beware_of_darkness_all_who_remain', 'jpg'), listofwords=[])
#main.writeLyrics(image=main.ReturnAll('beware_of_darkness_all_who_remain', 'jpg'), listofwords=[])
#main.genNC(image=main.ReturnAll('beware_of_darkness_all_who_remain', 'jpg'), listofwords=[])