1-
21import fitz
32from docx import Document
43from ..base_check import BaseReportCriterion , answer
1110
1211#С данными значениями погрешность 4-5 процентов
1312
14-
1513class TablePercentage (BaseReportCriterion ):
1614 label = "Проверка процентного соотношения таблиц в документе"
1715 description = "Проверяет, что таблицы занимают не более установленного процента площади документа"
1816 id = 'table_percentage'
1917
2018
21- def __init__ (self , file_info , max_percentage = 30 ):
19+ def __init__ (self , file_info , hasApplication = True , max_percentage = 30 ):
2220 super ().__init__ (file_info )
2321 self ._max_percentage = max_percentage
22+ self ._hasApplication = hasApplication
2423
2524 def get_font_size (self , run , paragraph ) -> float :
2625 """Функция получения размера шрифта"""
@@ -96,13 +95,45 @@ def getPercentOfTables(self) -> float:
9695
9796 tables_height = 0
9897
99- for table in doc_docx .tables :
100- table_height = self .heightTable (table )
101- tables_height += table_height
98+ end_index = len (doc_docx .tables )
99+
100+ if self ._hasApplication :
101+ end_index = self .find_table_index_after_text ('ПРИЛОЖЕНИЕ' )
102+ end_index = end_index if end_index is not None else len (doc_docx .tables )
103+
104+ for table_index , table in enumerate (doc_docx .tables ):
105+ if table_index < end_index :
106+ table_height = self .heightTable (table )
107+ tables_height += table_height
102108
103109 percentage = (tables_height / total_height ) * 100
104110 return percentage
105111
112+
113+ def find_table_index_after_text (self , target_text : str ) -> int | None :
114+ """Функция находит первый индекс таблицы после target_text, если не найден, то вернет None"""
115+ doc_docx = self .file .file
116+ for i , paragraph in enumerate (doc_docx .paragraphs ):
117+ if target_text in paragraph .text :
118+
119+ para_elem = paragraph ._element
120+ following_tables = para_elem .xpath ('./following-sibling::w:tbl' )
121+
122+ for table_elem in following_tables :
123+
124+ for index , table in enumerate (doc_docx .tables ):
125+ if table ._element == table_elem :
126+ return index
127+
128+ return None
129+
130+ def find_tables_indexs_between_text (self ,start_text : str , end_text : str | None = None ):
131+ """Функция нахождения индексов начала и конца таблиц между двумя текстами"""
132+ start_index = self .find_table_index_after_text (start_text )
133+ end_index = self .find_table_index_after_text (end_text )
134+
135+ return (start_index , end_index )
136+
106137 def check (self ):
107138 try :
108139 if self .file .page_counter () < 4 :
@@ -118,9 +149,15 @@ def check(self):
118149 else :
119150 return answer (
120151 False ,
121- f"Таблицы занимают { percent_tables :.1f} % документа, "
122- f"что превышает допустимые { self ._max_percentage } %. "
123- f"Рекомендуется сократить количество или размер таблиц."
152+ f'''
153+ Таблицы занимают { percent_tables :.1f} % документа, что превышает допустимые { self ._max_percentage } %.
154+ Рекомендации:
155+ <ul>
156+ <li>Уменьшите количество таблиц в основном тексте документа;</li>
157+ <li>Перенесите вспомогательные таблицы в приложения;</li>
158+ <li>Сократите объем данных в таблицах, оставив только самую важную информацию.</li>
159+ </ul>
160+ '''
124161 )
125162 except Exception as e :
126163 return answer (False , f"Ошибка при проверке процентного соотношения таблиц: { str (e )} " )
0 commit comments