-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathh2fb.py
1539 lines (1429 loc) · 56 KB
/
h2fb.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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python2.3
# -*- coding: ascii -*-
"""
HTML to FictionBook converter.
Usage: %prog [options] args
-i, --input-file=FILENAME: (*.html|*.htm|*.html|*.*) Input file name, defaults to stdin if omitted.
-o, --output-file=FILENAME: (*.fb2|*.*) Output file name, defaults to stdin if omitted.
-f, --encoding-from=ENCODING_NAME: Source encoding, autodetect if omitted.
-t, --encoding-to=ENCODING_NAME DEFAULT=Windows-1251: Result encoding(Windows-1251)
-r, --header-re=REGEX: Regular expression for headers detection('')
--not-convert-quotes: Not convert quotes
--not-convert-hyphen: Not convert hyphen
--skip-images: Skip images, i.e. if specified do NOT include images. Default is to include images/pictures
--not-convert-images: Do not convert images to PNG, i.e. if specified keep images as original types. By default ALL in-line images are converted to PNG format.
--skip-ext-links: Skip external links
--allow-empty-lines: Allow generate tags <empty-line/>
--not-detect-italic: Not detect italc
--not-detect-headers: Not detect sections headers
--not-detect-epigraphs: Not detect epigraphs
--not-detect-paragraphs: Not detect paragraphs
--not-detect-annot: Not detect annotation
--not-detect-verses: Not detect verses
--not-detect-notes: Not detect notes
-v,--verbose=INT: Debug
"""
####
"""
Chris TODO
* output encoding, only really works if output is the same as system
encoding. E.g. windows (command line) ascii, for most out-of-linux utf8
this is due to use of str types contructed on the fly in the encoding
specified in command line and then implict conversion from str to
Unicode (joining str to Unicode type, needs explict decode)
* uriparse lib for proper URL parsing
* images
* check support for links to images (as well as alterative text display/processing)
* handle images with url encoding, e.g. "my%20pic.jpg" versus "my pic.jpg" see url/uri above..
* add a check "if image not (png or jpeg) convert to PNG"? Most readers seem to only support png and jpeg
* check/change encoding of source to be (7 bit) ASCII, make this the default (instead if Windows-1252)
* remove getopt, use: optparse, (my modified) wxoptparse or my document optparse
* "em dash" only handles for html name tag "—",
does not handle at all —
and unicode/xml literal — is displayed as text of that!
probably due to use of SGML parser which isn't that flexible
* test multi document html input
* test href properly
* href bug if --not-convert-quotes is not issued, get ">>" in href!!
* -i bug not working properly if file does not exist (uses stdin) - Low priority as file logic removed from class, html2fb does NOT suffer from this
* -o bug not working properly if file is in use, get no error/exception displayed and instead got to stdout - Low priority as file logic removed from class, html2fb does NOT suffer from this
* TODO check python coding style/guide for open() versus file() -- http://mail.python.org/pipermail/python-dev/2004-July/045928.html
* pep8 where appropriate (note use 120 cols not 80)
* pychecker/pylint
* process() open() has except without type, should have type and not ignore everything
* convert_to_fb() out_file=file() also has except without type, should have type and not ignore everything
* convert2png has try/except with no restrictions, errors are lost.
* stuff before first header is book description: on/off
* remove SGMLParser? replace with Beautiful Soup http://www.crummy.com/software/BeautifulSoup/
* chardet suport - http://chardet.feedparser.org/
* support of non ascii chracter (e.g. Unicode) like "...", mdash, etc. open/close quotes, check HaliReader on pocketPC (suspect missing unicode font) and import my mapping code
"""
from sgmllib import SGMLParser
import sys
from types import DictType, TupleType, ListType
import re
import tempfile
import os
import base64
import time
import mimetypes
import urllib
import locale
import urllib2
from wget import Wget
import md5
try:
#raise ImportError
import optionparse
have_optparse = True
except ImportError:
have_optparse = False
version='0.1.1'
# Module wide values
_SENTENCE_FIN = u'\'".!?:\xBB\u2026' # \xBB == >>, \u2026 == ...
_HEAD_CHARS = u'0123456789VXILM*@'
_DIAL_START = u'-\u2013\u2014' # MINUS, N DASH, M DASH
_DIAL_START2 = u')-\u2013\u2014 .;'
_CH_REPL_AMP = u'\x00'
_CH_REPL_LT = u'\x01'
_CH_REPL_GT = u'\x02'
_CH_LEFT_Q = u'\\1\xab'
_CH_RIGHT_Q = u'\xbb\\1'
_CH_FLOW = u' '
_CH_DOTS = u'\u2026'
_CH_TIRE = u'\u2013'
_RE_LQUOTES = re.compile('([ (;-])"')
_RE_RQUOTES = re.compile('"([ <&.,;?!)-])')
_RE_LQUOTES2 = re.compile('^((?:<[^>]*>)*)"',re.M)
_RE_RQUOTES2 = re.compile('"((?:<[^>]*>)*)$',re.M)
_RE_TAG = re.compile('<[^>]*>')
_RE_ROMAN = re.compile('^m?m?m?(c[md]|d?c{0,3})(x[lc]|l?x{0,3})(i[xv]|v?i{0,3})$', re.I)
_RE_EL = re.compile('<empty-line/>\s*(</section>)')
# Flags
_TAG_SKIP = 0x0001
_TAG_STARTP = 0x0002
_TAG_STRONG = 0x0004
_TAG_EM = 0x0008
_TAG_NOTSKIP = 0x0010
_TAG_ENDP = 0x0020
_TAG_PRE = 0x0040
_TAG_HEADER = 0x0080
_TAG_INP = 0x0100
_TAG_ID = 0x0200
_TAGS={
'a' : _TAG_INP,
'abbr' : 0,
'article' : 0,
'acronym' : 0,
'address' : 0,
'align' : 0,
'applet' : 0,
'area' : 0,
'b' : _TAG_STRONG,
'base' : 0,
'basefont' : 0,
'bdo' : 0,
'bgsound' : 0,
'big' : 0,
'blink' : 0,
'blockquote' : 0,
'body' : 0,
'br' : _TAG_STARTP|_TAG_ENDP,
'button' : 0,
'caption' : 0,
'center' : 0,
'cite' : _TAG_EM|_TAG_ID,
'code' : 0,
'col' : 0,
'colgroup' : 0,
'comment' : 0,
'dd' : 0,
'del' : 0,
'dfn' : 0,
'dir' : 0,
'div' : 0,
'dl' : 0,
'dt' : 0,
'em' : _TAG_EM,
'embed' : 0,
'fieldset' : 0,
'font' : 0,
'form' : _TAG_SKIP,
'frame' : 0,
'frameset' : 0,
'h0' : _TAG_HEADER,
'h1' : _TAG_HEADER,
'h2' : _TAG_HEADER,
'h3' : _TAG_HEADER,
'h4' : _TAG_HEADER,
'h5' : _TAG_HEADER,
'h6' : _TAG_HEADER,
'head' : _TAG_SKIP,
'hr' : _TAG_ENDP,
'html' : 0,
'i' : _TAG_EM,
'iframe' : 0,
'ilayer' : 0,
'img' : _TAG_ENDP,
'input' : 0,
'ins' : 0,
'isindex' : 0,
'kbd' : 0,
'keygen' : 0,
'label' : 0,
'layer' : 0,
'legend' : 0,
'li' : 0,
'link' : 0,
'listing' : _TAG_PRE,
'map' : 0,
'marquee' : 0,
'menu' : 0,
'meta' : 0,
'multicol' : 0,
'nextid' : 0,
'nobr' : 0,
'noembed' : _TAG_SKIP,
'noframes' : _TAG_SKIP,
'nolayer' : 0,
'nosave' : 0,
'noscript' : _TAG_SKIP,
'object' : 0,
'ol' : 0,
'optgroup' : 0,
'option' : 0,
'p' : _TAG_STARTP|_TAG_ENDP,
'param' : 0,
'plaintext' : _TAG_PRE,
'pre' : 0,
'q' : 0,
'rb' : 0,
'rbc' : 0,
'rp' : 0,
'rt' : 0,
'rtc' : 0,
'ruby' : 0,
's' : 0,
'samp' : 0,
'script' : _TAG_SKIP,
'select' : 0,
'server' : 0,
'servlet' : 0,
'small' : 0,
'spacer' : 0,
'span' : 0,
'strike' : 0,
'strong' : _TAG_STRONG|_TAG_INP,
'style' : _TAG_SKIP,
'sub' : 0,
'sup' : 0,
'table' : 0,
'tbody' : 0,
'td' : 0,
'textarea' : 0,
'tfoot' : 0,
'th' : 0,
'thead' : 0,
'title' : _TAG_NOTSKIP,
'tr' : _TAG_STARTP,
'tt' : 0,
'u' : 0,
'ul' : 0,
'var' : _TAG_EM,
'wbr' : 0,
'xmp' : _TAG_PRE,
#fb2 tags. ignored while parsing
'emphasis' : _TAG_INP,
'section' : _TAG_ID,
'poem' : _TAG_ID,
'epigraph' : _TAG_ID,
}
try:
import wx
_IMG_LIB='wxPython'
def convert2png(filename):
if wx.GetApp() is None:
_app = wx.PySimpleApp()
retv=''
img = wx.Bitmap(filename, wx.BITMAP_TYPE_ANY)
if img.Ok():
img = wx.ImageFromBitmap(img)
of= tempfile.mktemp()
if img.SaveFile(of, wx.BITMAP_TYPE_PNG):
retv=open(of, 'rb').read()
os.unlink(of)
return retv
except ImportError:
try:
from PIL import Image
_IMG_LIB='PIL'
def convert2png(filename):
retv = ''
try:
of = tempfile.mktemp()
Image.open(filename).save(of,'PNG')
retv=open(of, 'rb').read()
os.unlink(of)
except:
pass
return retv
except ImportError:
_IMG_LIB='None'
convert2png = None
mimetypes.init()
class MyHTMLParser(SGMLParser):
"""HTML parser.
Originated from standard htmllib
"""
from htmlentitydefs import name2codepoint
entitydefs={}
for (name, codepoint) in name2codepoint.iteritems():
entitydefs[name] = unichr(codepoint)
del name, codepoint, name2codepoint
entitydefs['nbsp']=u' '
def reset(self):
SGMLParser.reset(self)
self.nofill = 1 # PRE active or not
self.oldnofill = 0 # for saving nofill flag (for section title, for example)
self.out = [] # Result
self.data = '' # Currently parsed text data
self.skip = '' # Skip all all between tags. End tag here
self.nstack = [[],[]] # Stack for nesting tags control. first el. is tags stack, second - correspond. attrs
self.save = '' # Storage for data between tags pair
self.saving = False # Saving in progress flag
self.ishtml = False # data type
self.asline = (0,0,0) # [counted lines, > 80, < 80]
self.ids = {} # links ids
self.nextid=1 # next note id
self.notes=[] # notes
self.descr={} # description
self.bins=[] # images (binary objects)
self.informer=None # informer (for out messages)
self.header_stack = [] # tags stack. For example: ['h1','h3','h4'] means: "I am in section under h1, then h3, then h4 header"
def handle_charref(self, name):
"""Handle decimal escaped character reference, does not handle hex.
E.g. “Quoted.” Fred’s car."""
# Modified version of Python 2.3 SGMLParser class
# to fix , etc. (named escape) ascii decode error
# as well as “, etc. (decimal escape) ascii decode error
try:
n = int(name)
except ValueError:
self.unknown_charref(name)
return
self.handle_data(unichr(n))
def process(self, params):
'''Main processing method. Process all data '''
self.params=params
self._TAGS = _TAGS
if 'informer' in params:
self.informer=params['informer']
if params['convert-images'] != 0 and convert2png is None:
raise(RuntimeError, 'convert to png requested but no image libraries are available')
if self.params['convert-span-to'] == 'emphasis' or self.params['convert-span-to'] == 'em':
self.params['convert-span-to'] == 'em'
elif self.params['convert-span-to'] != 'strong':
self.params['convert-span-to'] = None
if self.params['convert-span-to'] is not None:
self._TAGS['span'] = self._TAGS[self.params['convert-span-to']]
secs = time.time()
self.msg('HTML to FictionBook converter, ver. %s\n' % version)
self.msg("Reading data...\n")
data=params['data']
##
## use basename for href finding, could change regex instead?
#self.msg('process:'+unicode(params['file-name'], params['sys-encoding']))
##self.href_re = re.compile(".*?%s#(.*)" % unicode(params['file-name'], params['sys-encoding']))
self.href_re = re.compile(".*?%s#(.*)" % unicode(os.path.basename(params['file-name']), params['sys-encoding']))
self.source_directoryname = unicode(os.path.dirname(params['file-name']), params['sys-encoding'])
##
try:
self.header_re = params['header-re'].strip() and re.compile(params['header-re'])
except:
self.header_re = None
if not data:
return ''
self.msg('Preprocessing...\n')
data = self.pre_process(data)
self.msg('Parsing...\n')
self.feed(data+'</p>')
self.close()
self.msg('Formatting...\n')
self.detect_epigraphs()
self.detect_verses()
self.detect_paragraphs()
self.msg('Postprocessing...\n')
self.post_process()
self.msg('Building result document...\n')
self.out= '<?xml version="1.0" encoding="%s"?>\n' \
'<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:xlink="http://www.w3.org/1999/xlink">\n' % \
self.params['encoding-to'] + \
(self.make_description() + \
'<body>%s</body>' % self.out + \
self.make_notes()).encode(self.params['encoding-to'],'xmlcharrefreplace') + \
self.make_bins().encode(self.params['encoding-to'],'xmlcharrefreplace')+ '</FictionBook>'
self.msg("Total process time is %.2f secs\n" % (time.time() - secs))
return self.out
# --- Tag handling, need for parsing
def unknown_starttag(self, tag, attrs):
'''
Handle unknown start ttag
'''
if tag in self._TAGS or self.skip:
self.handle_starttag(tag, None, attrs)
else:
self.handle_data(self.tag_repr(tag, attrs))
def unknown_endtag(self, tag):
'''
Handle unknown end ttag
'''
if tag in self._TAGS or self.skip:
self.handle_endtag(tag, None)
else:
self.handle_data("</%s>" % tag)
def handle_data(self, data):
'''
Handle data stream
'''
data = data.replace('&',_CH_REPL_AMP).replace('<',_CH_REPL_LT).replace('>',_CH_REPL_GT)
if self.saving:
self.save += data
else:
self.data += data
def handle_starttag(self, tag, method, attrs):
'''
Handle all start tags
'''
# TODO: make this without 'singletone'
self.header_tag = tag
try:
flag = self._TAGS[tag]
except:
flag = 0
if self.skip and not flag & _TAG_NOTSKIP:
return
if flag & _TAG_SKIP:
self.skip = tag
if not method:
if flag & _TAG_EM:
method = self.start_em
if flag & _TAG_STRONG:
method = self.start_strong
if flag & _TAG_PRE:
method = self.start_pre
if flag & _TAG_STARTP:
method = self.do_p
if flag & _TAG_HEADER:
method = self.start_h1
if method:
method(attrs)
# if detected tag, but text still non-html - set text as html
if not self.ishtml and \
not flag & (_TAG_EM|_TAG_STRONG|_TAG_INP) and \
tag != 'h6':
self.end_paragraph()
self.ishtml = True
self.nofill = 0
def handle_endtag(self, tag, method):
'''
Handle all end tags
'''
# TODO: make this without 'singletone'
self.header_tag = tag
try:
flag = self._TAGS[tag]
except:
flag = 0
if self.skip and self.skip == tag:
self.skip=''
self.data=''
return
if not method:
if flag & _TAG_EM:
method=self.end_em
if flag & _TAG_STRONG:
method=self.end_strong
if flag & _TAG_PRE:
method=self.end_pre
if flag & _TAG_ENDP:
method = self.end_paragraph
if flag & _TAG_HEADER:
method = self.end_h1
if method:
method()
def start_title(self, attrs):
''' Save document title - start'''
self.start_saving()
def end_title(self):
''' End saving document title '''
self.descr['title'] = ' '.join(self.stop_saving().split()).strip()
def do_meta(self, attrs):
'''
Handle meta tags - try get document author
'''
name=''
content=''
for opt, val in attrs:
if opt=='name':
name=val
elif opt=='content':
content=val.strip()
if name=='author' and content:
self.descr['author']=content
def do_p(self, attrs):
'''Handle tag P'''
self.end_paragraph()
self.mark_start_tag('p')
def start_pre(self, attrs):
''' Handle tag PRE '''
self.nofill = self.nofill + 1
self.do_p(None)
def end_pre(self):
''' Handle tag /PRE '''
self.end_paragraph()
self.nofill = max(0, self.nofill - 1)
def start_em(self, attrs):
''' Handle tag EM '''
self.mark_start_tag('emphasis')
def end_em(self):
''' Handle tag /EM '''
self.mark_end_tag('emphasis')
def start_strong(self, attrs):
''' Handle tag STRONG '''
self.mark_start_tag('strong')
def end_strong(self):
''' Handle tag /STRONG '''
self.mark_end_tag('strong')
def start_a(self, attrs):
''' Handle tag A '''
for attrname, value in attrs:
value = value.strip()
if attrname == 'href':
res = self.href_re.match(value)
if res:
value=self.make_id(res.group(1))
try:
self.ids[value][1]+=1
except:
self.ids[value]=[0,1]
value="#"+value
if self.params['skip-ext-links'] and not res:
return
value = value.replace("&","&")
self.mark_start_tag('a', [('xlink:href',value)])
if attrname == 'name':
value = self.make_id(value)
self.data+="<id %s>" % value
try:
self.ids[value][0]+=1
except:
self.ids[value]=[1,0]
def end_a(self):
''' Handle tag /A '''
self.mark_end_tag('a')
def open_section(self):
self.end_paragraph()
self.out.extend(['<section>'])
self.mark_start_tag('p')
self.oldnofill, self.nofill = self.nofill, 0
def close_section(self):
self.end_paragraph()
self.out.append('</section>')
self.nofill = self.oldnofill
self.mark_start_tag('p')
def open_title(self):
self.end_paragraph()
self.out.extend(['<title>'])
self.mark_start_tag('p')
self.oldnofill, self.nofill = self.nofill, 0
def close_title(self):
self.end_paragraph()
self.out.append('</title>')
self.nofill = self.oldnofill
self.mark_start_tag('p')
def start_h1(self, attrs):
''' Handle tag H1-H6 '''
#self.end_paragraph()
#self.out.extend(['</section>','<section>','<title>'])
#self.mark_start_tag('p')
#self.oldnofill, self.nofill = self.nofill, 0
level = int(self.header_tag.replace("h",""))
if len(self.header_stack) == 0:
self.open_section()
self.open_title()
self.header_stack.append(level)
elif self.header_stack[-1] == level:
self.close_section()
self.open_section()
self.open_title()
elif self.header_stack[-1] < level:
self.open_section()
self.open_title()
self.header_stack.append(level)
else:
while True:
if len(self.header_stack) == 0: break
if self.header_stack[-1] < level: break
self.close_section()
self.header_stack.pop()
self.open_section()
self.open_title()
self.header_stack.append(level)
# self.close_section()
# self.open_section()
# self.open_title()
def end_h1(self):
''' Handle tag /H1-/H6 '''
#self.end_paragraph()
#self.out.append('</title>')
#self.nofill = self.oldnofill
#self.mark_start_tag('p')
self.close_title()
#self.close_section()
def do_img(self, attrs):
''' Handle images '''
if self.params['skip-images']:
return
src = None
for attrname, value in attrs:
if attrname == 'src':
src = value
sh = md5.new()
sh.update(src)
temp_image_filename=urllib.unquote(src)
src = sh.hexdigest() + ".png"
mime_type, data = self.convert_image(temp_image_filename)#src.encode(self.params['sys-encoding']))
if data:
self.end_paragraph()
src=os.path.basename(src)
self.out.append(self.tag_repr('image', [('xlink:href','#'+src)], True))
self.bins.append((mime_type, src, data))
def report_unbalanced(self, tag):
''' Handle unbalansed close tags'''
self.handle_data('</%s>\n' % tag)
def unknown_charref(self, ref):
''' Handle unknown char refs '''
# FIX: Don't know, how to handle it
self.msg('Unknown/invalid char ref %s is being ignored\n' % ref)
raise(Warning, 'Unknown char ref %s is being ignored\n' % ref)
def unknown_entityref(self, ref):
''' Handle unknown entity refs '''
# FIX: Don't know, how to handle it
self.msg('Unknown entity ref %s\n' % ref, 1)
# --- Methods for support parsing
def start_saving(self):
''' Not out data to out but save it '''
self.saving = True
self.save = ''
def stop_saving(self):
''' Stop data saving '''
self.saving = False
return self.save
def end_paragraph(self):
'''
Finalise paragraph
'''
if not self.data.strip():
try:
p = self.nstack[0].index('p')
if self.out[-1] == '<p>' or not self.out[-1]:
if self.params['skip-empty-lines']:
self.out.pop()
else:
self.out[-1] = "<empty-line/>"
self.nstack[0]=self.nstack[0][:p]
self.nstack[1]=self.nstack[1][:p]
else:
self.mark_end_tag('p')
except ValueError:
pass
else:
if 'p' not in self.nstack[0]:
self.nstack[0][0:0]='p'
self.nstack[1][0:0]=[None]
self.out.append('<p>')
self.mark_end_tag('p')
def mark_start_tag(self, tag, attrs=None):
''' Remember open tag and put it to output '''
try:
flag = self._TAGS[tag]
except:
flag = 0
if tag in self.nstack[0]:
self.mark_end_tag(tag)
self.nstack[0].append(tag)
self.nstack[1].append(attrs)
if flag & _TAG_INP:
self.data += self.tag_repr(tag, attrs)
else:
self.out.append(self.tag_repr(tag, attrs))
def mark_end_tag(self, tag):
'''
Close corresponding tags. If tag is not last tag was outed,
close all previously opened tags.
I.e. <strong><em>text</strong> -> <strong><em>text</em></strong>
'''
if tag not in self.nstack[0]:
return
while self.nstack[0]:
v = self.nstack[0].pop()
a = self.nstack[1].pop()
try:
flag = self._TAGS[v]
except:
flag = 0
if flag & _TAG_INP:
et=self.tag_repr(v,a)
if self.data.rstrip().endswith(et):
self.data=self.data.rstrip()[:-len(et)]
if v=='a':
try:
self.ids[a[0][1]][1]-=1
except:
pass
else:
self.data += "</%s>" % v
else:
self.process_data()
if self.out[-1]=="<%s>" % v:
## duplicate tag detected, often from replacing embedded <p> inside <a>...</a>
## FIXME not really sure if this is 100% appropriate, is this ONLY for missing target links?
self.msg("!!!!\n")
self.msg('DEBUG** ' + repr(v) + ' --- ' + repr(self.out[-10:]) + ' ' + repr(v), 1)
self.out.pop()
else:
self.out.append("</%s>" % v)
if tag == v:
break
def process_data(self):
'''
Handle accomulated data when close paragraph.
'''
if not self.data.strip():
return
if not self.nofill:
self.data=_CH_FLOW+self.data.strip()
self.out.append(self.data)
else:
self.data = self.process_pre(self.data)
self.data = self.detect_headers(self.data)
try:
if self.data[0]=='</p>' and self.out[-1]=='<p>':
self.out.pop()
self.data = self.data[1:]
msg("WoW! I must be impossible!!!")
except IndexError:
pass
self.out.extend(self.data)
self.data = ''
# --- Parsed data processing methods
def pre_process(self, data):
'''
Processing data before parsing.
Return data converted to unicode. If conversion is impossible, return None.
If encoding not set, try detect encoding with module recoding from pETR project.
'''
encoding = self.params['encoding-from']
if not encoding:
try:
data=unicode(data,'utf8')
encoding = None # No encoding more needed
except UnicodeError:
try:
import recoding # try import local version recoding
encoding = recoding.GetRecoder().detect(data[:2000])
except ImportError:
try:
import petr.recoding as recoding # try import pETR's modyle
encoding = recoding.GetRecoder().detect(data[:2000])
except ImportError:
encoding = None
if not encoding:
encoding = "Windows-1251"
self.msg("Recoding module not found. Use default encoding")
try:
if encoding:
data=unicode(data,encoding)
self.params['encoding-from'] = encoding
except:
data = None
self.msg("Encoding %s is not valid\n" % encoding)
if data:
data=data.replace(u'\x0e',u'<h6>').replace(u'\x0f',u'</h6>')
for i in u'\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x10\x11'\
'\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f':
data = data.replace(i,u' ')
return data
def post_process(self):
'''
Last processing method
'''
id = ''
for i in range(len(self.out)):
if not self.out[i]:
pass # skip empty lines (can apper below, where ...out[i+1]='')
elif self.out[i][0] != '<':
id, p = self.process_paragraph(self.out[i], id)
if p:
if id:
self.out[i-1] = '<%s id="%s">' % (self.out[i-1][1:-1],id)
id = ''
self.out[i] = p
else:
self.out[i-1]=self.out[i]=self.out[i+1]='' # remove empty paragraph
elif id:
try:
if self._TAGS[self.out[i][1:-1]] & _TAG_ID:
self.out[i] = '<%s id="%s">' % (self.out[i][1:-1],id)
id = ''
except KeyError:
pass
self.out='\n'.join(self.out). \
replace(_CH_REPL_AMP, '&'). \
replace(_CH_REPL_LT,'<'). \
replace(_CH_REPL_GT,'>'). \
replace('...',_CH_DOTS). \
strip()
if self.params['convert-hyphen']:
self.out=self.out.replace("- ",_CH_TIRE+" ").replace(" -"," "+_CH_TIRE)
# delete links withself.out anchors
for i in [x for x in self.ids.keys() if not self.ids[x][0] and self.ids[x][1]>=0]:
self.out=re.sub("%s(.*?)%s" % (self.tag_repr('a',[('xlink:href','#'+i)]),'</a>') ,r'\1',self.out)
sect=self.out.find('<section')
close_level=len(self.header_stack)
close_level = close_level + 1 #This is made for strange heuristics below
if 0 < sect < len(self.out)/3 and self.params['detect-annot']:
self.descr['annot'] = ' '.join(self.out[:sect].rstrip().rstrip('</section>').split())
self.out=self.out[sect:]
else:
if self.out.startswith('</section>'):
self.out=self.out[len('</section>'):]
elif self.out.startswith("<section>"):
close_level = close_level - 1
else:
self.out='<section>'+self.out
for i in range(close_level) : self.out+='</section>'
self.out=_RE_EL.sub(r'\1',self.out)
def detect_headers(self, data):
'''
Find headers in plain text.
'''
if not self.params['detect-headers']:
return [data]
res = []
pstart = i = 0
header = ['</p>',
'</section>',
'<section>',
'<title>',
'<p>',
'', # place for title (5)
'</p>',
'</title>',
'<p>']
while i < len(data)-1:
empty0 = not data[i]
try:
empty1 = not data[i+1]
empty2 = not data[i+2]
empty3 = not data[i+3]
except IndexError:
empty1 = empty2 = empty3 = False
if empty0 and empty1 and not empty2 and empty3:
res.append(data[pstart:i])
header[5]=_CH_FLOW + data[i+1].strip()
res.extend(header)
i+=2
pstart = i+2
else:
istitle = (
empty0 and
not empty1 and
empty2 and
(
empty3 or
data[i+1].startswith(' '*8) or
data[i+1].isupper() or
(
data[i+1].lstrip()[0] not in _DIAL_START and
data[i+1][-1] not in _SENTENCE_FIN
) or
data[i+1].lstrip()[0] in _HEAD_CHARS or
self.is_roman_number(data[i+1])
)
)
istitle = istitle or \
not empty1 and \
self.header_re and \
self.header_re.match(data[i+1])
if istitle:
res.append(data[pstart:i])
header[5]=_CH_FLOW + data[i+1].strip()
res.extend(header)
i+=1
while i < len(data)-1 and not data[i+1]:
i+=1
pstart = i+1
i+=1
if pstart < len(data):
res.append(data[pstart:])
return res
def detect_epigraphs(self):
'''
Detect epigraphs (in plain text)
'''
if not self.params['detect-epigraphs']:
return
sect_found = 0
i = 0
while i < len(self.out):
if type(self.out[i]) != ListType:
if self.out[i] == '<section>':
sect_found = 1
elif self.out[i] == '<title>':
sect_found = sect_found and 2 or 0
elif self.out[i] == '</title>':
sect_found = sect_found and 1 or 0
elif self.out[i][0] != '<':
sect_found = sect_found!=1 and 2 or 0
else:
if sect_found == 1:
res = []
raw = self.out[i]
lraw = len(raw)
j=0
eplines = 0
epfound = 0
while j < len(raw):
while j < lraw and not raw[j]:
j+=1 # skip empty lines
eep = -1
# search empty line
for k in range(j,j+60):
if k >= lraw or not raw[k]:
eep = k
break
if eep == j:
break
if eep >= 0:
eplines = 0
for k in range(j,eep):
rawk = raw[k].lstrip()
if ' '*10 in raw[k] or len(rawk) < 60:
eplines +=1
if len(rawk) > 60:
eplines -= 5
if rawk and (
rawk[0] in _DIAL_START or
rawk[0].isdigit() and
len(rawk)>2 and
rawk[1] in _DIAL_START2
):
eplines -= 1
if (float(eplines)/(eep-j)>0.8):
epfound += 1
author = eep-j > 1