-
Notifications
You must be signed in to change notification settings - Fork 2
/
batchXenocanto.py
870 lines (840 loc) · 28.1 KB
/
batchXenocanto.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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
# Check and update Xeno-Canto audio files
# Date: July 2013
# Author: Fae, http://j.mp/faewm
# CC-BY-SA
'''
import wikipedia, upload, sys, config, urllib2, urllib, re, string, time, catlib, pagegenerators, os.path, hashlib, pprint
import json,subprocess
from BeautifulSoup import BeautifulSoup
from sys import argv, stdout
import collections
from time import sleep
from os import remove
from colorama import Fore, Back, Style, init
init()
site = wikipedia.getSite('commons', 'commons')
subs=[['%20',' '],['%28','('],['%29',')'],['%2C',','],['%3A',':']]
def pquote(s):
s=urllib.quote(s)
for c in range(len(subs)):
s=re.sub(subs[c][0],subs[c][1],s)
return s
def gettag(tag,name):
if tag=='class':
try:
r=string.split(html,'class="'+name+'"')[1]
r=string.split(r,'>')[1]
r=string.split(r,'<')[0]
except:
return ''
return r
if tag=='td':
try:
r=string.split(html,'<tr><td>'+name+'</td><td>')[1]
r=string.split(r,'</td>')[0]
except:
return ''
return r
return ''
def p(tag, val): # Print nicely
if len(val)>1:
print Fore.CYAN+tag+" : "+Fore.YELLOW+val+Fore.WHITE
return
def pp(tag, val): # Print nicely
if len(val)>0:
print Fore.CYAN+tag+" : "+Fore.YELLOW+val+Fore.WHITE
else:
print Fore.CYAN+tag+Fore.RED+"** Missing data **"+Fore.WHITE
return
def trim(s): # Trim leading and trailing spaces
return re.sub('^[\s\r\t\f\n]*|[\s\r\t\f\n]*$','',s)
def up(filename, pagetitle, desc):
url = filename
keepFilename=True #set to True to skip double-checking/editing destination filename
verifyDescription=False #set to False to skip double-checking/editing description => change to bot-mode
targetSite = wikipedia.getSite('commons', 'commons')
bot = upload.UploadRobot(url, description=desc, useFilename=pagetitle, keepFilename=keepFilename, verifyDescription=verifyDescription, targetSite = targetSite)
bot.upload_image(debug=True)
def urltry(u):
countErr=0
x=''
while x=='':
try:
x = urllib2.urlopen(u)
time.sleep(1)
except:
x=''
countErr+=1
if countErr>20: countErr=20
print Fore.CYAN,'** ERROR',countErr,'\n ** Failed to read from '+u+'\n ** Pause for '+str(countErr*1)+' seconds and try again'+Fore.WHITE
time.sleep(1*countErr)
return x
def htmltry(x,u):
countErr=0
r=True
while r:
try:
return x.read()
except:
x=urltry(u)
countErr+=1
if countErr>200:
p=300
else:
p=countErr*2
print Fore.CYAN,'** ERROR',countErr,'\n ** Failed to read xml'
if countErr==1:
print Blue+'xml ='+str(x)
print 'url ='+u+Fore.CYAN
print ' ** Pause for '+str(p)+' seconds and try again'+Fore.WHITE
time.sleep(p)
else:
r=False
return
def xmlfind(item):
if data.find('<metadata name="'+item)>-1:
return data.split('<metadata name="'+item+'" value="')[1].split('"')[0]
else:
return ''
def gettag(h):
#<span class="link-11"><a href="/tag/thunderstorm" rel="tag" title="">Thunderstorm</a></span>
t=re.split('href="/tag/[^"]*" rel="tag" title="">',h)
for i in range(len(t)):
t[i]=t[i].split('<')[0]
t[0]=re.sub('^\s*|\s$','',t[0])
if t[0]=='': t.pop(0)
return ", ".join(t)
def getatt(t,h):
if h.find('>'+t+':</th>')==-1: return ''
r=re.split('<th scope="row"[^>]*>'+t+':</th>',h)[1].split('</td>')[0]
r=re.sub('[\n\r\t\s]',' ',r)
r=re.sub('\s+',' ',r)
return re.sub('^\s*|<[^>]*>|\s*$','',r)
def getcat(h):
# <div class="item-list"><ul><li><a href="/type/natural">Natural</a></li><li><a href="/type/characteristic">Characteristic</a></li></ul></div>
if h.find('<div class="terms">Type</div>')==-1: return '[[Category:Pdsounds.org]]'
r=h.split('<div class="terms">Type</div>')[1]
r=r.split('class="item-list"><ul>')[1]
r=r.split('</a></li></ul>')[0]
r=r.split('</a></li>')
c=''
for i in range(len(r)):
r[i]=re.sub('<[^>]*?>','',r[i])
return ", ".join(r)
def dupcheck(ff): # Using the SHA1 checksum, find if the file is already uploaded to Commons
#df=urllib2.urlopen(ff)
df=open(ff,'rb')
notread=True # Try to deal with socket.timeout
while notread:
notread=False
try:
sha1 = hashlib.sha1(df.read()).hexdigest()
except:
notread=True
print Fore.RED+"Trouble getting SHA1 for file, trying again in 2 seconds."
sleep(2)
df=urllib2.urlopen(ff)
#print Fore.CYAN+'SHA1='+sha1
u="http://commons.wikimedia.org/w/api.php?action=query&list=allimages&format=xml&ailimit=1&aiprop=sha1&aisha1="+sha1
notread=True
while notread:
notread=False
try:
x=urllib2.urlopen(u)
except:
notread=True
print Fore.RED+"Trouble reading",u
time.sleep(5)
xd=x.read()
x.close()
if xd.find("<img")>-1:
t=xd.split('title="')[1].split('"')[0]
return True,t
return False,''
# Check if a file title is already used on commons
def nameused(name):
u="http://commons.wikimedia.org/w/api.php?action=query&prop=imageinfo&format=xml&titles=File:"+urllib.quote(name)
x=urllib2.urlopen(u).read()
if x.find('<imageinfo>')>-1:
return True
return False
def trimtags(s):
return trim(re.sub('<[^>]*?>','',s))
def titlecase(s):
s=re.sub('�?39;',"'",s)
s=re.sub('&','and',s)
s=re.sub(':','-',s)
words=s.split(" ")
smallwords=['at','the','of','by','a','during','work','on','in','and']
bigwords=['UK','US','USA','U\.S\.','H\.M\.S\.','HMS', 'RAF', 'R\.A\.F\.', 'YWCA', 'YMCA']
for i in range(len(words)):
staybig=False
for j in bigwords:
if re.search('^'+j+'[,\.;\(\)\-]?',words[i]):
staybig=True
continue
if not staybig:
words[i]=words[i][0:1]+words[i][1:].lower()
else:
continue
if i==0:
continue
else:
for j in smallwords:
if words[i].lower()==j: words[i]=words[i].lower()
continue
return ' '.join(words)
def oddchars(s):
s=re.sub(':',"-",s)
s=re.sub('£',"£",s)
s=re.sub('åGBP',"£",s)
s=re.sub('\u00E4','ä',s)
s=re.sub('\u00FC','ü',s)
s=re.sub('\u00E2','â',s)
s=re.sub('\u2019',"'",s)
#s=re.sub('\xA4','€',s)
s=re.sub("\xC2\xA0",' ',s)
s=re.sub("\xC2\xA1",'¡',s)
s=re.sub("\xC2\xA2",'¢',s)
s=re.sub("\xC2\xA3",'£',s)
s=re.sub("\xC2\xA4",'¤',s)
s=re.sub("\xC2\xA5",'¥',s)
s=re.sub("\xC2\xA6",'¦',s)
s=re.sub("\xC2\xA7",'§',s)
s=re.sub("\xC2\xA8",'¨',s)
s=re.sub("\xC2\xA9",'©',s)
s=re.sub("\xC2\xAA",'ª',s)
s=re.sub("\xC2\xAB",'«',s)
s=re.sub("\xC2\xAC",'¬',s)
s=re.sub("\xC2\xAD",'­',s)
s=re.sub("\xC2\xAE",'®',s)
s=re.sub("\xC2\xAF",'¯',s)
s=re.sub("\xC2\xB0",'°',s)
s=re.sub("\xC2\xB1",'±',s)
s=re.sub("\xC2\xB2",'²',s)
s=re.sub("\xC2\xB3",'³',s)
s=re.sub("\xC2\xB4",'´',s)
s=re.sub("\xC2\xB5",'µ',s)
s=re.sub("\xC2\xB6",'¶',s)
s=re.sub("\xC2\xB7",'·',s)
s=re.sub("\xC2\xB8",'¸',s)
s=re.sub("\xC2\xB9",'¹',s)
s=re.sub("\xC2\xBA",'º',s)
s=re.sub("\xC2\xBB",'»',s)
s=re.sub("\xC2\xBC",'¼',s)
s=re.sub("\xC2\xBD",'½',s)
s=re.sub("\xC2\xBE",'¾',s)
s=re.sub("\xC2\xBF",'¿',s)
s=re.sub("\xC3\x80",'À',s)
s=re.sub("\xC3\x81",'Á',s)
s=re.sub("\xC3\x82",'Â',s)
s=re.sub("\xC3\x83",'Ã',s)
s=re.sub("\xC3\x84",'Ä',s)
s=re.sub("\xC3\x85",'Å',s)
s=re.sub("\xC3\x86",'Æ',s)
s=re.sub("\xC3\x87",'Ç',s)
s=re.sub("\xC3\x88",'È',s)
s=re.sub("\xC3\x89|\xc9",'É',s)
s=re.sub("\xC3\x8A",'Ê',s)
s=re.sub("\xC3\x8B",'Ë',s)
s=re.sub("\xC3\x8C",'Ì',s)
s=re.sub("\xC3\x8D",'Í',s)
s=re.sub("\xC3\x8E",'Î',s)
s=re.sub("\xC3\x8F",'Ï',s)
s=re.sub("\xC3\x90",'Ð',s)
s=re.sub("\xC3\x91",'Ñ',s)
s=re.sub("\xC3\x92",'Ò',s)
s=re.sub("\xC3\x93",'Ó',s)
s=re.sub("\xC3\x94",'Ô',s)
s=re.sub("\xC3\x95",'Õ',s)
s=re.sub("\xC3\x96",'Ö',s)
s=re.sub("\xC3\x97",'×',s)
s=re.sub("\xC3\x98",'Ø',s)
s=re.sub("\xC3\x99",'Ù',s)
s=re.sub("\xC3\x9A",'Ú',s)
s=re.sub("\xC3\x9B",'Û',s)
s=re.sub("\xC3\x9C",'Ü',s)
s=re.sub("\xC3\x9D",'Ý',s)
s=re.sub("\xC3\x9E",'Þ',s)
s=re.sub("\xC3\x9F",'ß',s)
s=re.sub("\xC3\xA0|\xe0",'à',s)
s=re.sub("\xC3\xA1|\xe1",'á',s)
s=re.sub("\xC3\xA2",'â',s)
s=re.sub("\xC3\xA3",'ã',s)
s=re.sub("\xC3\xA4",'ä',s)
s=re.sub("\xC3\xA5",'å',s)
s=re.sub("\xC3\xA6",'æ',s)
s=re.sub("\xC3\xA7|\xe7",'ç',s)
s=re.sub("\xC3\xA8",'è',s)
s=re.sub("\xC3\xA9",'é',s)
s=re.sub("\xC3\xAA|\xea",'ê',s)
s=re.sub("\xC3\xAB|\xeb",'ë',s)
s=re.sub("\xC3\xAC",'ì',s)
s=re.sub("\xC3\xAD|\xed",'í',s)
s=re.sub("\xC3\xAE|\xee",'î',s)
s=re.sub("\xC3\xAF|\xEF",'ï',s)
s=re.sub("\xC3\xB0",'ð',s)
s=re.sub("\xC3\xB1",'ñ',s)
s=re.sub("\xC3\xB2",'ò',s)
s=re.sub("\xC3\xB3|\xf3",'ó',s)
s=re.sub("\xC3\xB4",'ô',s)
s=re.sub("\xC3\xB5",'õ',s)
s=re.sub("\xC3\xB6|\xF6",'ö',s) # http://www.fileformat.info/info/unicode/char/f6/index.htm
s=re.sub("\xC3\xB7",'÷',s)
s=re.sub("\xC3\xB8",'ø',s)
s=re.sub("\xC3\xB9",'ù',s)
s=re.sub("\xC3\xBA|\xfa",'ú',s)
s=re.sub("\xC3\xBB",'û',s)
s=re.sub("\xC3\xBC|\xfc",'ü',s)
s=re.sub("\xC3\xBD",'ý',s)
s=re.sub("\xC3\xBE",'þ',s)
s=re.sub("\xC3\xBF",'ÿ',s)
#s=re.sub("\xc3",'',s) #debug - a rubbish fix
s=re.sub("\xf8",'ø',s) #debug - another unsure fix
# Latin Extended-A
s=re.sub("\xC5\x92",'Œ',s)
s=re.sub("\xC5\x93",'œ',s)
s=re.sub("\xC5\xA0",'Š',s)
s=re.sub("\xC5\xA1",'š',s)
s=re.sub("\xC5\xB8",'Ÿ',s)
s=re.sub("\xc5\xab",'ū',s) # u macron http://www.fileformat.info/info/unicode/char/16b/index.htm
s=re.sub("\xc5\x8c",'Ō',s) # o macron
s=re.sub("\xC5\x8d",'ō',s) # O macron
# Spacing Modifier Letters
s=re.sub("\xCB\x86",'ˆ',s)
s=re.sub("\xCB\x9C",'˜',s)
# General Punctuation
s=re.sub("\xE2\x80\x82",' ',s)
s=re.sub("\xE2\x80\x83",' ',s)
s=re.sub("\xE2\x80\x89",' ',s)
s=re.sub("\xE2\x80\x8C",'‌',s)
s=re.sub("\xE2\x80\x8D",'‍',s)
s=re.sub("\xE2\x80\x8E",'‎',s)
s=re.sub("\xE2\x80\x8F",'‏',s)
s=re.sub("\xE2\x80\x93",'–',s)
s=re.sub("\xE2\x80\x94",'—',s)
s=re.sub("\xE2\x80\x98",'‘',s)
s=re.sub("\xE2\x80\x99",'’',s)
s=re.sub("\xE2\x80\x9A",'‚',s)
s=re.sub("\xE2\x80\x9C",'“',s)
s=re.sub("\xE2\x80\x9D",'”',s)
s=re.sub("\xE2\x80\x9E",'„',s)
s=re.sub("\xE2\x80\xA0",'†',s)
s=re.sub("\xE2\x80\xA1",'‡',s)
s=re.sub("\xE2\x80\xB0",'‰',s)
s=re.sub("\xE2\x80\xB9",'‹',s)
s=re.sub("\xE2\x80\xBA",'›',s)
s=re.sub("\xE2\x82\xAC",'€',s)
# Latin Extended-B
s=re.sub("\xC6\x92",'ƒ',s)
# Greek
s=re.sub("\xCE\x91",'Α',s)
s=re.sub("\xCE\x92",'Β',s)
s=re.sub("\xCE\x93",'Γ',s)
s=re.sub("\xCE\x94",'Δ',s)
s=re.sub("\xCE\x95",'Ε',s)
s=re.sub("\xCE\x96",'Ζ',s)
s=re.sub("\xCE\x97",'Η',s)
s=re.sub("\xCE\x98",'Θ',s)
s=re.sub("\xCE\x99",'Ι',s)
s=re.sub("\xCE\x9A",'Κ',s)
s=re.sub("\xCE\x9B",'Λ',s)
s=re.sub("\xCE\x9C",'Μ',s)
s=re.sub("\xCE\x9D",'Ν',s)
s=re.sub("\xCE\x9E",'Ξ',s)
s=re.sub("\xCE\x9F",'Ο',s)
s=re.sub("\xCE\xA0",'Π',s)
s=re.sub("\xCE\xA1",'Ρ',s)
s=re.sub("\xCE\xA3",'Σ',s)
s=re.sub("\xCE\xA4",'Τ',s)
s=re.sub("\xCE\xA5",'Υ',s)
s=re.sub("\xCE\xA6",'Φ',s)
s=re.sub("\xCE\xA7",'Χ',s)
s=re.sub("\xCE\xA8",'Ψ',s)
s=re.sub("\xCE\xA9",'Ω',s)
s=re.sub("\xCE\xB1",'α',s)
s=re.sub("\xCE\xB2",'β',s)
s=re.sub("\xCE\xB3",'γ',s)
s=re.sub("\xCE\xB4",'δ',s)
s=re.sub("\xCE\xB5",'ε',s)
s=re.sub("\xCE\xB6",'ζ',s)
s=re.sub("\xCE\xB7",'η',s)
s=re.sub("\xCE\xB8",'θ',s)
s=re.sub("\xCE\xB9",'ι',s)
s=re.sub("\xCE\xBA",'κ',s)
s=re.sub("\xCE\xBB",'λ',s)
s=re.sub("\xCE\xBC",'μ',s)
s=re.sub("\xCE\xBD",'ν',s)
s=re.sub("\xCE\xBE",'ξ',s)
s=re.sub("\xCE\xBF|\U014D",'o',s)#&omacron;
s=re.sub("\xCF\x80",'π',s)
s=re.sub("\xCF\x81",'ρ',s)
s=re.sub("\xCF\x82",'ς',s)
s=re.sub("\xCF\x83",'σ',s)
s=re.sub("\xCF\x84",'τ',s)
s=re.sub("\xCF\x85",'υ',s)
s=re.sub("\xCF\x86",'φ',s)
s=re.sub("\xCF\x87",'χ',s)
s=re.sub("\xCF\x88",'ψ',s)
s=re.sub("\xCF\x89",'ω',s)
s=re.sub("\xCF\x91",'ϑ',s)
s=re.sub("\xCF\x92",'ϒ',s)
s=re.sub("\xCF\x96",'ϖ',s)
# General Punctuation
s=re.sub("\xE2\x80\xA2",'•',s)
s=re.sub("\xE2\x80\xA6",'…',s)
s=re.sub("\xE2\x80\xB2",'′',s)
s=re.sub("\xE2\x80\xB3",'″',s)
s=re.sub("\xE2\x80\xBE",'‾',s)
s=re.sub("\xE2\x81\x84",'⁄',s)
# Letterlike Symbols
s=re.sub("\xE2\x84\x98",'℘',s)
s=re.sub("\xE2\x84\x91",'ℑ',s)
s=re.sub("\xE2\x84\x9C",'ℜ',s)
s=re.sub("\xE2\x84\xA2",'™',s)
s=re.sub("\xE2\x84\xB5",'ℵ',s)
# Arrows
s=re.sub("\xE2\x86\x90",'←',s)
s=re.sub("\xE2\x86\x91",'↑',s)
s=re.sub("\xE2\x86\x92",'→',s)
s=re.sub("\xE2\x86\x93",'↓',s)
s=re.sub("\xE2\x86\x94",'↔',s)
s=re.sub("\xE2\x86\xB5",'↵',s)
s=re.sub("\xE2\x87\x90",'⇐',s)
s=re.sub("\xE2\x87\x91",'⇑',s)
s=re.sub("\xE2\x87\x92",'⇒',s)
s=re.sub("\xE2\x87\x93",'⇓',s)
s=re.sub("\xE2\x87\x94",'⇔',s)
# Mathematical Operators
s=re.sub("\xE2\x88\x80",'∀',s)
s=re.sub("\xE2\x88\x82",'∂',s)
s=re.sub("\xE2\x88\x83",'∃',s)
s=re.sub("\xE2\x88\x85",'∅',s)
s=re.sub("\xE2\x88\x87",'∇',s)
s=re.sub("\xE2\x88\x88",'∈',s)
s=re.sub("\xE2\x88\x89",'∉',s)
s=re.sub("\xE2\x88\x8B",'∋',s)
s=re.sub("\xE2\x88\x8F",'∏',s)
s=re.sub("\xE2\x88\x91",'∑',s)
s=re.sub("\xE2\x88\x92",'−',s)
s=re.sub("\xE2\x88\x97",'∗',s)
s=re.sub("\xE2\x88\x9A",'√',s)
s=re.sub("\xE2\x88\x9D",'∝',s)
s=re.sub("\xE2\x88\x9E",'∞',s)
s=re.sub("\xE2\x88\xA0",'∠',s)
s=re.sub("\xE2\x88\xA7",'∧',s)
s=re.sub("\xE2\x88\xA8",'∨',s)
s=re.sub("\xE2\x88\xA9",'∩',s)
s=re.sub("\xE2\x88\xAA",'∪',s)
s=re.sub("\xE2\x88\xAB",'∫',s)
s=re.sub("\xE2\x88\xB4",'∴',s)
s=re.sub("\xE2\x88\xBC",'∼',s)
s=re.sub("\xE2\x89\x85",'≅',s)
s=re.sub("\xE2\x89\x88",'≈',s)
s=re.sub("\xE2\x89\xA0",'≠',s)
s=re.sub("\xE2\x89\xA1",'≡',s)
s=re.sub("\xE2\x89\xA4",'≤',s)
s=re.sub("\xE2\x89\xA5",'≥',s)
s=re.sub("\xE2\x8A\x82",'⊂',s)
s=re.sub("\xE2\x8A\x83",'⊃',s)
s=re.sub("\xE2\x8A\x84",'⊄',s)
s=re.sub("\xE2\x8A\x86",'⊆',s)
s=re.sub("\xE2\x8A\x87",'⊇',s)
s=re.sub("\xE2\x8A\x95",'⊕',s)
s=re.sub("\xE2\x8A\x97",'⊗',s)
s=re.sub("\xE2\x8A\xA5",'⊥',s)
s=re.sub("\xE2\x8B\x85",'⋅',s)
# Miscellaneous Technical
s=re.sub("\xE2\x8C\x88",'⌈',s)
s=re.sub("\xE2\x8C\x89",'⌉',s)
s=re.sub("\xE2\x8C\x8A",'⌊',s)
s=re.sub("\xE2\x8C\x8B",'⌋',s)
s=re.sub("\xE2\x8C\xA9",'⟨',s)
s=re.sub("\xE2\x8C\xAA",'⟩',s)
# Geometric Shapes
s=re.sub("\xE2\x97\x8A",'◊',s)
# Miscellaneous Symbols
s=re.sub("\xE2\x99\xA0",'♠',s)
s=re.sub("\xE2\x99\xA3",'♣',s)
s=re.sub("\xE2\x99\xA5",'♥',s)
s=re.sub("\xE2\x99\xA6",'♦',s)
s=re.sub("\xE8",'è',s)
s=re.sub("\xE9",'é',s)
return s
def asciichars(s):
s=re.sub(r'&([A-Za-z])(uml|circ|grave|acute|macron|cedil|tilde|ring|slash);',r'\1',s)
# -a-
s=re.sub('å','A',s)
s=re.sub(u'\xC3',"A",s)
s=re.sub("Á",'A',s) # ç
s=re.sub("À",'A',s) # A grave
s=re.sub("Æ",'Ae',s) # AE ligature
s=re.sub(u'\u00E4','a',s)
s=re.sub(u'\u00E2','a',s)
s=re.sub("Ä",'a',s) #
s=re.sub("Å",'a',s) #
s=re.sub("â",'a',s) # a circ
s=re.sub(u"\xe2",'a',s) # a circ
s=re.sub("ä",'a',s) #
s=re.sub("å",'a',s) #
s=re.sub("æ",'ae',s) # ¾
s=re.sub("á",'a',s) #
s=re.sub("à",'a',s) # a grave
s=re.sub("ä",'a',s) #
# -c-
s=re.sub("ç",'c',s) # c cedila
s=re.sub("Ç",'C',s) # c cedila
s=re.sub(u'\xE7',"c",s) # c cedila
# -d-
s=re.sub("ð",'d',s) # edd / eth
# -e-
s=re.sub(u'\xA4',"E",s)
s=re.sub("Ê",'E',s) # E circ
s=re.sub("É|É",'E',s) # E acute
s=re.sub("è",'e',s) #
s=re.sub("é|é",'e',s) # e acute
s=re.sub("ê",'e',s) # e circ
s=re.sub("ë",'e',s) # e diaresis
s=re.sub("è",'e',s) # e
# -i-
s=re.sub("í",'i',s) #
s=re.sub("î",'i',s) # i circumflex
s=re.sub(u"\xee",'i',s) # icirc
s=re.sub("ý",'y',s) # y acute
s=re.sub("Þ",'Th',s) # thorn upper
s=re.sub("Í",'I',s) # upper I acute
s=re.sub("–",'-',s) # long dash
s=re.sub("”",'"',s) # rquo
s=re.sub("ï",'i',s)
# -n-
s=re.sub("ñ",'n',s) # ntilde
s=re.sub(u'\xf1','n',s)
# -o-
s=re.sub("Ó",'O',s) # î
s=re.sub("Ō",'O',s) # O macron
s=re.sub(u'\u014c','O',s) # O macron
s=re.sub(u'\u014D','o',s)
s=re.sub("Ö",'o',s) #
s=re.sub("ó",'o',s) #
s=re.sub("ø",'o',s) # o slash
s=re.sub("ò|\xf2",'o',s) # o grave
s=re.sub(u'\u014d','o',s) # o grave
s=re.sub("Ø",'Oe',s) # ¯
s=re.sub("Œ",'oe',s) # oe ligature
s=re.sub("ø",'oe',s) # ¿
s=re.sub("ö",'o',s) #
s=re.sub("ō",'o',s) # o grave
s=re.sub("ô",'o',s) # o circ
# -s-
s=re.sub("š",'s',s) # s with caron
s=re.sub("Š",'S',s) # S with caron
s=re.sub("þ",'th',s) # thorn lower
s=re.sub("\s¿",'.',s)
s=re.sub("¿",'.',s) # upside down question mark
# -u-
s=re.sub(u'\u00FC','u',s)
s=re.sub("ù",'u',s) # ugrave
s=re.sub("û",'u',s) # ucirc
s=re.sub("ü",'u',s) #
s=re.sub("ū",'u',s) # u bar
s=re.sub("ú",'u',s) # u acute
s=re.sub(u'\u016b','u',s) # u macron
s=re.sub("ü",'u',s)
# -y-
s=re.sub('ÿ','y',s) # ydiaresis
# non-letters
s=re.sub(u'\u2019',"'",s)
s=re.sub(u"\u2013",'-',s) # endash
s=re.sub(u'\ufffd','?',s) # diamond questionmark symbol
s=re.sub("‘","'",s)
s=re.sub("’","'",s)
s=re.sub(''',"'",s)
s=re.sub('"',"'",s)
s=re.sub(u'\u016b',"'",s)
s=re.sub('Õ',"'",s)
s=re.sub('£',"GBP",s)
return s
# *** Grab description ***
def flatten(l):
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
for sub in flatten(el):
yield sub
else:
yield el
def getdesc(html):
soup=BeautifulSoup(html)
try:
image=soup.findAll("img")[-1]
except:
return ''
attrib=html.split("If you are going to publish, redistribute this image on the Internet place this link:")[1].split("</td>")[0]
title=attrib.split("title="")[1].split(""")[0]
site=attrib.split("href="")[1].split(""")[0]
try:
author=re.sub("\n","",urllib.quote(attrib.split("> by ")[1].split("</em")[0], " ,").encode('ascii','ignore'))
except:
author="Public Domain Images"
return '{{information\n| description = {{en|1=<br/>\n:''Image title: '+image['title']+'\n:Image from Public domain images website, '+site+"}}\n| source = "+image['src']+"\n| author = "+author+'\n| date = Not given\n*Transferred by [[User:{{subst:User:Fae/Fae}}|]] on {{subst:today}}\n| permission = This file is in public domain, not copyrighted, no rights reserved, free for any use. You can use this picture for any use including commercial purposes without the prior written permission and without fee or obligation.\n}}\n=={{int:license}}==\n{{PD-author|1='+author+'}}\n[[Category:Images uploaded by {{subst:User:Fae/Fae}}]]\n[[Category:Public-domain-image.com]]'+allcat, re.sub("\s{2,}"," ",image['title'].encode('ascii','ignore'))+'.jpg', image['src']
def uptry(source,filename,desc):
countErr=0
r=True
while r:
try:
up(source,filename,desc)
return
except:
countErr+=1
if countErr>200:
p=300
else:
p=countErr*5
print Fore.CYAN,'** ERROR Upload failed'
print ' ** Pause for '+str(p)+' seconds and try again'+Fore.WHITE
sleep(p)
return
plist=[]
def numberSearch(v):
vcount=0
countErr=0
loop=True
while loop:
try:
vgen = pagegenerators.SearchPageGenerator(v, namespaces = "6")
for vPage in vgen:
plist.append(vPage.title())
vcount+=1
loop=False
except:
loop=True
countErr+=1
print Fore.RED+"Problem running search, sleeping for",countErr,"seconds"
time.sleep(countErr)
if countErr>30:
loop=False
vcount=-1
return vcount
def catexists(cat): # Does this Commons category exist?
urlpath="http://commons.wikimedia.org/w/api.php?action=query&prop=info&format=xml&titles=Category:"+urllib.quote(cat)
url=urltry(urlpath)
xml=htmltry(url,urlpath)
if re.search('missing=""',xml):
return False
else:
return True
def createcat(cat,txt,action):
wikipedia.setAction(action)
p=wikipedia.Page(site,"Category:"+cat)
ptxt="Creating category "+cat
print Fore.GREEN+"-"*len(ptxt)
print ptxt
print "-"*len(ptxt),Fore.WHITE
sleep(30)
p.put(txt)
return
def sleepcounter(period):
for i in range(period):
stdout.write("\r%d " % (period-i))
stdout.flush()
sleep(1)
stdout.write("\r ")
stdout.flush()
stdout.write("\r")
def ns(s):
s=re.sub("\s{2,}"," ",s)
s=asciichars(oddchars(s))
s=trim(s)
return re.sub(" ","_",s)
# *********
# Main loop
# *********
baseurl="http://www.xeno-canto.org/api/recordings.php?query=lic:by-sa&page="
page=1
uri=baseurl+str(page)
print "Getting",uri
url=urltry(uri)
html=json.load(url)
print str(html)[0:100]
# error was a key, not sure what happened to it
'''
if html['error']==0:
print Fore.GREEN,"Loaded without errors",Fore.WHITE
else:
print Fore.RED,"Error",html['errorMessage'],Fore.WHITE
'''
results=html
recordings=results['recordings'] #[i for i in html['results']['recordings']]
numRecordings=results['numRecordings']
numPages=results['numPages']
print Fore.YELLOW,"numRecordings",numRecordings,"\n numPages",numPages,Fore.WHITE
for p in range(int(float(numPages))):
if p==0: continue
uri=baseurl+str(p+1)
print "Getting",uri
url=urltry(uri)
html2=json.load(url)
#print hArr
'''if html2['error']==0:
print Fore.GREEN,"Loaded without errors",Fore.WHITE
else:
print Fore.RED,"Error",html2['errorMessage'],Fore.WHITE'''
#for i in html2['results']['recordings']:
recordings=html2['recordings']#.append(i)
print Fore.CYAN+"Number of recordings identified:",len(recordings),"of",numRecordings
count=0
results=[]
for r in recordings:
count+=1
#pprint.PrettyPrinter(indent=2).pprint(r)
# Quick check of uniqueness of id on Commons, for virin read filename
plist=[]
ref="XC"+r['id']
title=r['en']
numbermatch='"xeno-canto"+"'+r['gen']+'"+"'+r['sp']+'"+"'+ref+'"'
vc=numberSearch(numbermatch)
print Fore.YELLOW+str(count), Fore.CYAN+"http://commons.wikimedia.org/w/index.php?search="+urllib.quote(numbermatch), Fore.WHITE
if vc==-1:
print Fore.YELLOW+"Error generating search matches for '"+title+" "+ref+"', probably timeout error, skipping file without completing this test",Fore.WHITE
continue
if vc>0: # May be a need to ignore known false positives
#print Fore.RED+"-"*75
print Fore.RED+"Image appears to be in use already for",asciichars(oddchars(title))+" "+ref+" ("+str(vc)+" matches)."+Fore.WHITE
#print Fore.RED+"-"*75,Fore.WHITE
continue
else:
results.append(r)
workingdir="F:/XC/"
count=0
uploadcount=0
for r in results:
count+=1
ref=re.sub("\D*","",r['id'])
species=r['sp']
genus=r['gen']
common=r['en']
title=genus+" "+species+" - "+common+" XC"+ref
filename=asciichars(oddchars(title))+".ogg" # upload filename
# Quick check of filename in use - these should be unique
if nameused(filename):
print Fore.RED+'Filename found',Fore.YELLOW+"http://commons.wikimedia.org/wiki/File:"+re.sub("%20","_",urllib.quote(filename)),Fore.WHITE
continue
localfile=workingdir+ref+".mp3" # source mp3 file
localenc=workingdir+ref
print Fore.GREEN+filename+Fore.WHITE
source=r['file']
artist=r['rec']
gallery=r['url']
url=urltry(gallery)
html=htmltry(url,gallery)
soup=BeautifulSoup(html)
rd=str(soup.find('section',{'id':'recording-data'}).find('tbody'))
date=rd.split(">Date<")[1].split('<td>')[1].split('<')[0]
dtime=""
if re.search(">Time<",rd):
dtime=rd.split(">Time<")[1].split('<td>')[1].split('<')[0]
if len(dtime)>2:
date+=" "+dtime
elevation=''
if re.search('>Elevation<',rd):
elevation=rd.split(">Elevation<")[1].split('<td>')[1].split('<')[0]
background=''
if re.search('>Background<',rd):
background=rd.split(">Background")[1].split('<td')[1].split('>')[1].split('<')[0]
if background=="none":
background=''
remarks=''
if re.search('<h2>Remarks from',html):
remarks=html.split('<h2>Remarks')[1].split('h2>')[1]
if re.search('<.section',remarks):
remarks=remarks.split('</section')[0]
remarks=re.sub("<.?p>","\n",remarks)
remarks=re.sub("<.?span[^>]*?>","\n",remarks)
remarks=re.sub("\n*\s*<$","",remarks)
remarks=re.sub("\n+","\n:",re.sub("\s*\n\s*","\n",remarks))
remarks=re.sub("<a [^>]*>","",re.sub("<\/a>","",remarks))
d="=={{int:filedesc}}==\n{{information"
d+="\n|description={{en|"
if remarks!='':
d+=remarks
if len(r['en'])>2:
d+="\n:'''Common name:''' "+r['en']
if len(r['type'])>2:
d+="\n:'''Type:''' "+r['type']
if len(r['gen'])>2:
d+="\n:'''Genus:''' "+r['gen']
if len(r['sp'])>2:
d+="\n:'''Species:''' "+r['sp']
if len(r['loc'])>2:
d+="\n:'''Location:''' "+r['loc']
if len(r['cnt'])>2:
d+="\n:'''Country:''' "+r['cnt']
if elevation!='':
d+="\n:'''Elevation:''' "+elevation
if background!='':
d+="\n:Background:''' "+background
d+="}}"
d+="\n|date="+date
d+="\n|author="+artist
d+="\n|source=\n*'''Metadata:''' "+gallery+"\n*'''Audio file:''' "+source
d+="\n}}"
if len(r['lat'])>2:
d+="{{object location dec|"+r['lat']+"|"+r['lng']+"}}"
d+="{{User:{{subst:User:Fae/Fae}}/Projects/Xeno-canto/credit}}"
d+="\n\n=={{int:license-header}}==\n{{cc-by-sa-3.0}}"
d+="\n[[Category:Xeno-canto]]\n[[Category:Sound files uploaded by {{subst:User:Fae/Fae}}]]"
cat=r['gen']+" "+r['sp']
if catexists(cat):
d+="\n[[Category:"+cat+"]]"
d=re.sub("ocolono",":",oddchars(re.sub(":","ocolono",d)))
print Fore.CYAN+d,Fore.WHITE
urllib.urlretrieve(source, localfile)
print Fore.YELLOW+str(count)+"/"+str(len(results)),Fore.GREEN,"Encoding",localfile
print "ffmpeg -i",localfile,localenc+".wav",Fore.WHITE
subprocess.call(["ffmpeg","-i",localfile,localenc+".wav"])
subprocess.call(["oggenc2",localenc+".wav",
"-q 10", #quality
"-a "+ns(artist), #artist
"-l "+ns(gallery), #album
"-t "+ns(title), #title
#"-d "+re.sub("\D*","",date.split(" ")[0]), #date
"-N "+ref, #track num
"-G "+ns(r['type']), #genre
"-c country="+ns(r['cnt']),
"-c location="+ns(r['loc']),
"-c genus="+ns(r['gen']),
"-c species="+ns(r['sp']),
"-c latitude="+ns(r['lat']),
"-c longitude="+ns(r['lng']),
"-c license="+ns(r['lic']),
"-c URL="+ns(r['url']),
"-c date="+date.split(" ")[0],
"-c time="+dtime,
"-o",localenc+".ogg"])
remove(localenc+".wav")
remove(localenc+".mp3")
# Check if image is a duplicate on Commons
media=localenc+".ogg"
try:
duplicate,duptitle = dupcheck(media)
except:
print Fore.RED+"Problem when running the duplicate check for",media,Fore.WHITE
time.sleep(10)
try:
duplicate,duptitle = dupcheck(media)
except:
print Fore.RED+"Failed on second try, giving up and skipping"
remove(media)
continue
if duplicate:
print Fore.RED+'File is already on Commons as',duptitle,Fore.WHITE
time.sleep(2)
continue
# Upload
uptry(media,filename,d) # Intermittently getting [Errno 54] Connection reset by peer
remove(media)
uploadcount+=1
print Fore.GREEN+"Total uploads =",uploadcount,Fore.WHITE
sleepcounter(10)