@@ -740,7 +740,6 @@ def handle_tag(self, tag, attrs, start):
740740 """
741741 if not self .is_p_tag_with_dir :
742742 super ().handle_tag (tag , attrs , start )
743-
744743 elif tag not in HTML_TAGS_ATTRIBUTE_WHITELIST and tag != 'span' :
745744 if start :
746745 self .outtextf (f'<{ tag } ' )
@@ -773,28 +772,26 @@ def clean_html(content):
773772 (indicating right-to-left direction), this method will ensure that the 'dir' attribute is preserved
774773 or added to maintain consistency with the original content.
775774 """
776- LIST_TAGS = ['ul' , 'ol' ]
775+ if not content :
776+ return ''
777777 is_list_with_dir_attr_present = False
778-
779- cleaned = content .replace (' ' , '' ) # Keeping the removal of nbsps for historical consistency
780- # Parse the HTML using BeautifulSoup
778+ cleaned = content .replace (' ' , '' )
781779 soup = BeautifulSoup (cleaned , 'lxml' )
782-
780+ LIST_TAGS = [ 'ul' , 'ol' ]
783781 for tag in soup .find_all (LIST_TAGS , dir = "rtl" ):
784782 tag .attrs .pop ('dir' )
785783 is_list_with_dir_attr_present = True
786-
787- cleaned = str (soup )
788- # Need to clean empty <b> and <p> tags which are converted to <hr/> by html2text
789- cleaned = cleaned .replace ('<p><b></b></p>' , '' )
790784 html_converter = HTML2TextWithLangSpans (bodywidth = None )
791785 html_converter .wrap_links = False
792- cleaned = html_converter .handle (cleaned ).strip ()
793- cleaned = markdown .markdown (cleaned )
794- for tag in LIST_TAGS :
795- cleaned = cleaned .replace (f'<{ tag } >' , f'<{ tag } dir="rtl">' ) if is_list_with_dir_attr_present else cleaned
796-
797- return cleaned
786+ markdown_text = html_converter .handle (str (soup )).strip ()
787+ cleaned = markdown .markdown (markdown_text )
788+ cleaned = cleaned .replace ('<hr />' , '' )
789+ cleaned = re .sub (r'([^\s>])(<a\b)' , r'\1 \2' , cleaned )
790+ if is_list_with_dir_attr_present :
791+ for tag in LIST_TAGS :
792+ cleaned = cleaned .replace (f'<{ tag } >' , f'<{ tag } dir="rtl">' )
793+ cleaned = re .sub (r'\n\s*\n' , '\n ' , cleaned )
794+ return cleaned .strip ()
798795
799796
800797def get_file_from_drive_link (image_url ):
0 commit comments