1414import traceback
1515from typing import List
1616
17+ from django .utils .translation import gettext_lazy as _
1718from pypdf import PdfReader
1819from pypdf .generic import Destination
19- from django .utils .translation import gettext_lazy as _
2020
2121from common .handle .base_split_handle import BaseSplitHandle
2222from common .utils .logger import maxkb_logger
@@ -76,9 +76,7 @@ def handle(
7676 return {"name" : file .name , "content" : result }
7777
7878 # 没目录但是有链接的pdf
79- result = self .handle_links (
80- pdf_document , pattern_list , with_filter , limit
81- )
79+ result = self .handle_links (pdf_document , pattern_list , with_filter , limit )
8280 if result is not None and len (result ) > 0 :
8381 return {"name" : file .name , "content" : result }
8482
@@ -88,13 +86,9 @@ def handle(
8886 if pattern_list is not None and len (pattern_list ) > 0 :
8987 split_model = SplitModel (pattern_list , with_filter , limit )
9088 else :
91- split_model = SplitModel (
92- default_pattern_list , with_filter = with_filter , limit = limit
93- )
89+ split_model = SplitModel (default_pattern_list , with_filter = with_filter , limit = limit )
9490 except BaseException as e :
95- maxkb_logger .error (
96- f"File: { file .name } , error: { e } , { traceback .format_exc ()} "
97- )
91+ maxkb_logger .error (f"File: { file .name } , error: { e } , { traceback .format_exc ()} " )
9892 return {"name" : file .name , "content" : []}
9993 finally :
10094 # 处理完后可以删除临时文件
@@ -147,9 +141,7 @@ def handle_pdf_content(file, pdf_document):
147141 content = content .replace ("\0 " , "" )
148142
149143 elapsed_time = time .time () - start_time
150- maxkb_logger .debug (
151- f"File: { file .name } , Page: { page_num + 1 } , Time: { elapsed_time :.3f} s"
152- )
144+ maxkb_logger .debug (f"File: { file .name } , Page: { page_num + 1 } , Time: { elapsed_time :.3f} s" )
153145
154146 return content
155147
@@ -284,12 +276,16 @@ def handle_toc(doc, limit):
284276 if 0 < limit < len (chapter_text ):
285277 split_text = smart_split_paragraph (chapter_text , limit )
286278 for text in split_text :
287- chapters .append ({"title" : real_chapter_title , "content" : text })
279+ chapters .append (
280+ {"title" : real_chapter_title , "content" : text .encode ("utf-8" , "ignore" ).decode ("utf-8" )}
281+ )
288282 else :
289283 chapters .append (
290284 {
291285 "title" : real_chapter_title ,
292- "content" : chapter_text if chapter_text else real_chapter_title ,
286+ "content" : (chapter_text if chapter_text else real_chapter_title )
287+ .encode ("utf-8" , "ignore" )
288+ .decode ("utf-8" ),
293289 }
294290 )
295291 # 保存章节内容和章节标题
@@ -334,13 +330,9 @@ def handle_links(doc, pattern_list, with_filter, limit):
334330 next_link = links [num + 1 ] if num + 1 < len (links ) else None
335331 next_link_title = None
336332 if next_link is not None :
337- next_link_title = PdfSplitHandle .extract_link_title (
338- page , next_link ["from" ]
339- )
333+ next_link_title = PdfSplitHandle .extract_link_title (page , next_link ["from" ])
340334 if not next_link_title :
341- next_link_title = PdfSplitHandle .extract_first_line (
342- doc .pages [next_link ["page" ]]
343- )
335+ next_link_title = PdfSplitHandle .extract_first_line (doc .pages [next_link ["page" ]])
344336 end_page = next_link ["page" ]
345337
346338 # 提取章节内容
@@ -383,24 +375,14 @@ def handle_links(doc, pattern_list, with_filter, limit):
383375 else :
384376 pre_toc [- 1 ]["content" ] += line
385377 for i in range (len (pre_toc )):
386- pre_toc [i ]["content" ] = re .sub (
387- r"(?<!。)\n+" , "" , pre_toc [i ]["content" ]
388- )
389- pre_toc [i ]["content" ] = re .sub (
390- r"(?<!.)\n+" , "" , pre_toc [i ]["content" ]
391- )
378+ pre_toc [i ]["content" ] = re .sub (r"(?<!。)\n+" , "" , pre_toc [i ]["content" ])
379+ pre_toc [i ]["content" ] = re .sub (r"(?<!.)\n+" , "" , pre_toc [i ]["content" ])
392380 except BaseException as e :
393- maxkb_logger .error (
394- _ (
395- "This document has no preface and is treated as ordinary text: {e}"
396- ).format (e = e )
397- )
381+ maxkb_logger .error (_ ("This document has no preface and is treated as ordinary text: {e}" ).format (e = e ))
398382 if pattern_list is not None and len (pattern_list ) > 0 :
399383 split_model = SplitModel (pattern_list , with_filter , limit )
400384 else :
401- split_model = SplitModel (
402- default_pattern_list , with_filter = with_filter , limit = limit
403- )
385+ split_model = SplitModel (default_pattern_list , with_filter = with_filter , limit = limit )
404386 # 插入目录前的部分
405387 page_content = re .sub (r"(?<!。)\n+" , "" , page_content )
406388 page_content = re .sub (r"(?<!.)\n+" , "" , page_content )
@@ -419,15 +401,11 @@ def get_internal_links(doc, page):
419401 continue
420402 if annotation .get ("/Subtype" ) != "/Link" :
421403 continue
422- dest_page = PdfSplitHandle .get_annotation_destination_page_number (
423- doc , annotation
424- )
404+ dest_page = PdfSplitHandle .get_annotation_destination_page_number (doc , annotation )
425405 if dest_page is None or dest_page < 0 or dest_page >= len (doc .pages ):
426406 continue
427407 rect = annotation .get ("/Rect" )
428- links .append (
429- {"page" : dest_page , "from" : PdfSplitHandle .normalize_rect (rect )}
430- )
408+ links .append ({"page" : dest_page , "from" : PdfSplitHandle .normalize_rect (rect )})
431409 return links
432410
433411 @staticmethod
@@ -465,9 +443,7 @@ def get_destination_page_number(doc, destination):
465443 return PdfSplitHandle .get_page_number_by_reference (doc , destination [0 ])
466444
467445 if hasattr (destination , "get" ) and destination .get ("/D" ) is not None :
468- return PdfSplitHandle .get_destination_page_number (
469- doc , destination .get ("/D" )
470- )
446+ return PdfSplitHandle .get_destination_page_number (doc , destination .get ("/D" ))
471447
472448 return None
473449
@@ -511,8 +487,7 @@ def visitor_text(text, cm, tm, font_dict, font_size):
511487 text_top = y + (float (font_size ) if font_size else 0 )
512488 in_horizontal_range = left - tolerance <= x <= right + tolerance
513489 in_vertical_range = (
514- bottom - tolerance <= y <= top + tolerance
515- or bottom - tolerance <= text_top <= top + tolerance
490+ bottom - tolerance <= y <= top + tolerance or bottom - tolerance <= text_top <= top + tolerance
516491 )
517492 if in_horizontal_range and in_vertical_range :
518493 text_parts .append (text )
0 commit comments