Multi-Turn Chain of Thought Reasoning with Final Synthesis
Enter your Groq API Key and a question or problem to see multiple turns of reasoning, followed by a final synthesized answer.
Enter your Groq API Key
Enter your question or problem
Chain of Thought Reasoning
Original Query
import streamlit as st import os import re import tempfile from io import BytesIO import fitz # PyMuPDF import zipfile
Настройка страницы приложения Streamlit
st.set_page_config(page_title="Автоматическое разделение PDF на главы", layout="wide")
Функция для очистки имени файла от недопустимых символов
def sanitize_filename(name): """ Заменяет запрещенные символы в имени файла на подчеркивание. Удаляет лишние пробелы. """ name = re.sub(r'[/*?:"<>|]', "_", name) name = re.sub(r'\s+', ' ', name).strip() return name
Функция для извлечения потенциальных заголовков из страницы
def extract_headings_from_page(page): """ Извлекает потенциальные заголовки из страницы, основываясь на размере шрифта и положении текста. """ headings = [] blocks = page.get_text("dict")["blocks"] for block in blocks: if "lines" in block: for line in block["lines"]: for span in line["spans"]: text = span["text"].strip() font_size = span["size"] y_position = span["bbox"][1] # Проверяем, находится ли текст в верхней трети страницы и имеет ли крупный размер шрифта if y_position < page.rect.height * 0.3 and font_size >= 14: # Добавляем текст в потенциальные заголовки headings.append((text, font_size, y_position)) return headings
Функция для определения границ глав
def detect_chapter_boundaries(doc): """ Определяет границы глав на основе обнаруженных заголовков на каждой странице. Возвращает список кортежей (номер страницы, название главы). """ chapter_starts = [] for page_num in range(len(doc)): page = doc[page_num] headings = extract_headings_from_page(page) if headings: # Выбираем самый крупный заголовок на странице headings.sort(key=lambda x: (-x[1], x[2])) # Сортировка по размеру шрифта и положению main_heading = headings[0][0] chapter_starts.append((page_num, main_heading)) return chapter_starts
Функция для разделения PDF на главы
def split_pdf_by_chapters(pdf_path): chapters = [] try: doc = fitz.open(pdf_path) chapter_starts = detect_chapter_boundaries(doc) if not chapter_starts: st.error("Не удалось обнаружить главы в документе.") return []
# Добавляем конец документа в качестве последней границы
chapter_starts.append((len(doc), "Конец документа"))
for i in range(len(chapter_starts) - 1):
start_page = chapter_starts[i][0]
end_page = chapter_starts[i+1][0]
chapter_title = sanitize_filename(chapter_starts[i][1])[:100]
chapter_doc = fitz.open()
chapter_doc.insert_pdf(doc, from_page=start_page, to_page=end_page - 1)
output_bytes = chapter_doc.write()
chapters.append({
'title': f"{chapter_title}.pdf",
'start_page': start_page,
'end_page': end_page - 1,
'file': output_bytes
})
chapter_doc.close()
doc.close()
Assistant
except Exception as e:
st.write(f"Ошибка при разделении PDF: {e}")
return chapters
Главная функция приложения
def main(): st.title("Автоматическое разделение PDF на главы")
---- Загрузка PDF файла ----
uploaded_file = st.file_uploader("Выберите PDF файл", type=["pdf"])
if uploaded_file is not None:
st.write("Файл успешно загружен. Обрабатываем...")
try:
# Сохраняем загруженный файл во временное хранилище
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
tmp_file.write(uploaded_file.getvalue())
tmp_file_path = tmp_file.name
# Разделяем PDF на главы
chapters = split_pdf_by_chapters(tmp_file_path)
if chapters:
st.success(f"Документ успешно разделен на главы.")
# Отображаем информацию о главах
for chapter in chapters:
st.write(f"{chapter['title']}: страницы {chapter['start_page']+1}-{chapter['end_page']+1}")
# Предлагаем скачать все главы в виде ZIP архива
zip_buffer = BytesIO()
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
for chapter in chapters:
filename = chapter['title']
zip_file.writestr(filename, chapter['file'])
zip_buffer.seek(0)
st.download_button(
label="Скачать все главы в формате ZIP",
data=zip_buffer,
file_name="Разделенные_главы.zip",
mime="application/zip"
)
else:
st.error("Не удалось разделить документ на главы.")
os.unlink(tmp_file_path)
except Exception as e:
st.error(f"Произошла ошибка при обработке файла: {e}")
if name == "main": main()
Turn 1
Reasoning
Analysis of the Given Python Script Explanation: The provided Python script is a Streamlit application that allows users to upload a PDF file and automatically split it into chapters based on detected headings. The script uses the PyMuPDF library to work with PDF files and the zipfile library to create a ZIP archive of the split chapters.
Understanding the Chapter Detection Algorithm Explanation: The script uses a simple algorithm to detect chapter headings. It checks each page of the PDF for text with a large font size (>= 14) that is located in the top third of the page. The text with the largest font size is considered the main heading for that page.
Identifying Potential Issues and Improvements Explanation: There are several potential issues and improvements that can be identified in the script:
The chapter detection algorithm is simple and may not work well for all types of PDF documents. More advanced algorithms, such as machine learning-based approaches, could be explored.
The script does not handle cases where a chapter spans multiple pages without a clear heading on each page. This could be addressed by introducing a mechanism to merge pages into a single chapter based on context.
The script does not provide any feedback to the user about the progress of the chapter detection and splitting process. This could be addressed by adding status updates or progress bars to the Streamlit interface.
The script does not handle cases where the uploaded PDF file is corrupted or invalid. This could be addressed by adding error checking and handling code to the script.
Potential Changes and Refactoring Explanation: Based on the analysis above, several changes and refactoring could be made to the script to improve its functionality and robustness:
Introduce a more advanced chapter detection algorithm, such as a machine learning-based approach.
Add a mechanism to merge pages into a single chapter based on context.
Add status updates or progress bars to the Streamlit interface to provide feedback to the user about the progress of the chapter detection and splitting process.
Add error checking and handling code to the script to handle cases where the uploaded PDF file is corrupted or invalid.
Answer
The provided Python script is a basic implementation of a PDF chapter splitter that uses a simple algorithm to detect chapter headings. While the script works for simple cases, there are several potential issues and improvements that can be identified, including the need for a more advanced chapter detection algorithm, mechanisms to handle cases where a chapter spans multiple pages, and error checking and handling code. To address these issues, changes and refactoring can be made to the script, such as introducing a more advanced chapter detection algorithm, adding a mechanism to merge pages into a single chapter, and adding status updates or progress bars to the Streamlit interface.
Turn 2
Critique
The previous reasoning provides a thorough analysis of the provided Python script and identifies several potential issues and improvements. However, the critique could be more detailed, and the suggestions for improvement could be more specific. Additionally, the previous reasoning does not provide a clear plan for implementing the suggested changes.
New Reasoning
Refactoring the Script to Improve Readability and Maintainability Explanation: The script can be refactored to improve readability and maintainability by breaking it down into smaller functions, each with a specific responsibility. For example, the chapter detection algorithm can be separated into its own function, and the PDF splitting logic can be separated into its own function. This will make the script easier to understand and modify.
Implementing a More Advanced Chapter Detection Algorithm Explanation: A more advanced chapter detection algorithm can be implemented using machine learning techniques. For example, a supervised learning approach can be used to train a model on a labeled dataset of PDF documents with chapter headings. The model can then be used to predict chapter headings in new PDF documents. This will improve the accuracy of chapter detection.
Adding a Mechanism to Merge Pages into a Single Chapter Explanation: A mechanism can be added to merge pages into a single chapter based on context. For example, if a chapter spans multiple pages without a clear heading on each page, the script can use natural language processing techniques to identify the context and merge the pages into a single chapter. This will improve the accuracy of chapter splitting.
Adding Status Updates or Progress Bars to the Streamlit Interface Explanation: Status updates or progress bars can be added to the Streamlit interface to provide feedback to the user about the progress of the chapter detection and splitting process. This will improve the user experience and make the script more interactive.
Adding Error Checking and Handling Code to the Script Explanation: Error checking and handling code can be added to the script to handle cases where the uploaded PDF file is corrupted or invalid. This will improve the robustness of the script and prevent crashes.
Updated Answer
The provided Python script can be improved by refactoring it to improve readability and maintainability, implementing a more advanced chapter detection algorithm using machine learning techniques, adding a mechanism to merge pages into a single chapter based on context, adding status updates or progress bars to the Streamlit interface, and adding error checking and handling code to the script. These changes will improve the accuracy and robustness of the script and make it more user-friendly.
Here is some sample code to demonstrate the suggested changes:
import fitz # PyMuPDF
import zipfile
import streamlit as st
from io import BytesIO
import re
import tempfile
import os
Refactored function to detect chapter headings
def detect_chapter_headings(page):
headings = []
blocks = page.get_text("dict")["blocks"]
for block in blocks:
if "lines" in block:
for line in block["lines"]:
for span in line["spans"]:
text = span["text"].strip()
font_size = span["size"]
y_position = span["bbox"][1]
if y_position < page.rect.height * 0.3 and font_size >= 14:
headings.append((text, font_size, y_position))
return headings
def sanitize_filename(name):
name = re.sub(r'[\/*?:"<>|]', "_", name)
name = re.sub(r'\s+', ' ', name).strip()
return name
Main function
def main():
st.title("Автоматическое разделение PDF на главы")
uploaded_file = st.file_uploader("Выберите PDF файл", type=["pdf"])
if uploaded_file is not None:
st.write("Файл успешно загружен. Обрабатываем...")
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
tmp_file.write(uploaded_file.getvalue())
tmp_file_path = tmp_file.name
doc = fitz.open(tmp_file_path)
chapters = split_pdf_into_chapters(doc)
if chapters:
st.success(f"Документ успешно разделен на главы.")
for chapter in chapters:
st.write(f"{chapter['title']}: страницы {chapter['start_page']+1}-{chapter['end_page']+1}")
zip_buffer = BytesIO()
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
for chapter in chapters:
filename = chapter['title']
zip_file.writestr(filename, chapter['file'])
zip_buffer.seek(0)
st.download_button(
label="Скачать все главы в формате ZIP",
data=zip_buffer,
file_name="Разделенные_главы.zip",
mime="application/zip"
)
else:
st.error("Не удалось разделить документ на главы.")
os.unlink(tmp_file_path)
except Exception as e:
st.error(f"Произошла ошибка при обработке файла: {e}")
if name == "main":
main()
Note that this is just a sample code to demonstrate the suggested changes, and you may need to modify it to fit your specific requirements.
Turn 3
Critique
The previous reasoning provides a good analysis of the provided Python script and identifies several potential issues and improvements. However, the critique could be more detailed, and the suggestions for improvement could be more specific. Additionally, the previous reasoning does not provide a clear plan for implementing the suggested changes, and the sample code provided is not well-structured and lacks error handling.
New Reasoning
Implementing a More Advanced Chapter Detection Algorithm Using Machine Learning Techniques Explanation: A more advanced chapter detection algorithm can be implemented using machine learning techniques. For example, a supervised learning approach can be used to train a model on a labeled dataset of PDF documents with chapter headings. The model can then be used to predict chapter headings in new PDF documents. This will improve the accuracy of chapter detection.
Adding a Mechanism to Merge Pages into a Single Chapter Based on Context Explanation: A mechanism can be added to merge pages into a single chapter based on context. For example, if a chapter spans multiple pages without a clear heading on each page, the script can use natural language processing techniques to identify the context and merge the pages into a single chapter. This will improve the accuracy of chapter splitting.
Improving the Structure and Organization of the Code Explanation: The code can be improved by breaking it down into smaller functions, each with a specific responsibility. For example, the chapter detection algorithm can be separated into its own function, and the PDF splitting logic can be separated into its own function. This will make the code easier to understand and modify.
Adding Error Handling and Logging to the Code Explanation: Error handling and logging can be added to the code to handle cases where the uploaded PDF file is corrupted or invalid. This will improve the robustness of the script and prevent crashes.
Improving the User Experience by Adding Status Updates or Progress Bars to the Streamlit Interface Explanation: Status updates or progress bars can be added to the Streamlit interface to provide feedback to the user about the progress of the chapter detection and splitting process. This will improve the user experience and make the script more interactive.
Updated Answer
The provided Python script can be improved by implementing a more advanced chapter detection algorithm using machine learning techniques, adding a mechanism to merge pages into a single chapter based on context, improving the structure and organization of the code, adding error handling and logging to the code, and improving the user experience by adding status updates or progress bars to the Streamlit interface.
Here is some sample code to demonstrate the suggested changes:
import fitz # PyMuPDF
import zipfile
import streamlit as st
from io import BytesIO
import re
import tempfile
import os
import logging
def detect_chapter_headings(page):
try:
headings = []
blocks = page.get_text("dict")["blocks"]
for block in blocks:
if "lines" in block:
for line in block["lines"]:
for span in line["spans"]:
text = span["text"].strip()
font_size = span["size"]
y_position = span["bbox"][1]
if y_position < page.rect.height * 0.3 and font_size >= 14:
headings.append((text, font_size, y_position))
return headings
except Exception as e:
logger.error(f"Error detecting chapter headings: {e}")
return []
Function to split PDF into chapters
def split_pdf_into_chapters(doc):
try:
chapters = []
chapter_starts = []
for page_num in range(len(doc)):
page = doc[page_num]
headings = detect_chapter_headings(page)
if headings:
main_heading = headings[0][0]
chapter_starts.append((page_num, main_heading))
chapter_starts.append((len(doc), "Конец документа"))
for i in range(len(chapter_starts) - 1):
start_page = chapter_starts[i][0]
end_page = chapter_starts[i+1][0]
chapter_title = sanitize_filename(chapter_starts[i][1])[:100]
chapter_doc = fitz.open()
chapter_doc.insert_pdf(doc, from_page=start_page, to_page=end_page - 1)
output_bytes = chapter_doc.write()
chapters.append({
'title': f"{chapter_title}.pdf",
'start_page': start_page,
'end_page': end_page - 1,
'file': output_bytes
})
chapter_doc.close()
return chapters
except Exception as e:
logger.error(f"Error splitting PDF into chapters: {e}")
return []
Function to sanitize filename
def sanitize_filename(name):
name = re.sub(r'[\/*?:"<>|]', "_", name)
name = re.sub(r'\s+', ' ', name).strip()
return name
Main function
def main():
st.title("Автоматическое разделение PDF на главы")
uploaded_file = st.file_uploader("Выберите PDF файл", type=["pdf"])
if uploaded_file is not None:
st.write("Файл успешно загружен. Обрабатываем...")
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
tmp_file.write(uploaded_file.getvalue())
tmp_file_path = tmp_file.name
doc = fitz.open(tmp_file_path)
chapters = split_pdf_into_chapters(doc)
if chapters:
st.success(f"Документ успешно разделен на главы.")
for chapter in chapters:
st.write(f"{chapter['title']}: страницы {chapter['start_page']+1}-{chapter['end_page']+1}")
zip_buffer = BytesIO()
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
for chapter in chapters:
filename = chapter['title']
zip_file.writestr(filename, chapter['file'])
zip_buffer.seek(0)
st.download_button(
label="Скачать все главы в формате ZIP",
data=zip_buffer,
file_name="Разделенные_главы.zip",
mime="application/zip"
)
else:
st.error("Не удалось разделить документ на главы.")
os.unlink(tmp_file_path)
except Exception as e:
logger.error(f"Error processing file: {e}")
st.error(f"Произошла ошибка при обработке файла: {e}")
if name == "main":
main()
Note that this is just a sample code to demonstrate the suggested changes, and you may need to modify it to fit your specific requirements.
Synthesis
Analysis of Turns
Turn 1 provides a thorough analysis of the given Python script and identifies several potential issues and improvements. The critique is well-structured, and the suggestions for improvement are clear and specific. However, the critique could be more detailed, and the suggestions for improvement could be more specific.
Turn 2 provides a good analysis of the provided Python script and identifies several potential issues and improvements. The critique is well-structured, and the suggestions for improvement are clear and specific. However, the critique could be more detailed, and the suggestions for improvement could be more specific.
Turn 3 provides a detailed analysis of the provided Python script and identifies several potential issues and improvements. The critique is well-structured, and the suggestions for improvement are clear and specific. The critique is more detailed than the previous turns, and the suggestions for improvement are more specific.
Comparison
All three turns provide a good analysis of the provided Python script and identify several potential issues and improvements. However, Turn 3 provides a more detailed analysis and more specific suggestions for improvement.
Final Reasoning
Based on the analysis of the three turns, it is clear that the provided Python script can be improved in several ways. The most important improvements are:
Implementing a more advanced chapter detection algorithm using machine learning techniques.
Adding a mechanism to merge pages into a single chapter based on context.
Improving the structure and organization of the code.
Adding error handling and logging to the code.
Improving the user experience by adding status updates or progress bars to the Streamlit interface.
Comprehensive Final Answer
The provided Python script can be improved by implementing a more advanced chapter detection algorithm using machine learning techniques, adding a mechanism to merge pages into a single chapter based on context, improving the structure and organization of the code, adding error handling and logging to the code, and improving the user experience by adding status updates or progress bars to the Streamlit interface. These improvements will make the script more accurate, robust, and user-friendly.
Concise Answer
The Python script can be improved by implementing a more advanced chapter detection algorithm, adding a mechanism to merge pages into a single chapter, improving the code structure, adding error handling and logging, and improving the user experience. These improvements will make the script more accurate, robust, and user-friendly.
Timing Information
возьми и реализуй улучшения напечатай полный код
Конечно! Я реализую предложенные улучшения и предоставлю полный обновленный код. В данном обновленном коде реализованы следующие улучшения:
Улучшенный алгоритм определения глав: Используется метод на основе анализа содержания страниц с помощью TF-IDF и косинусного сходства для определения вероятных заголовков и объединения страниц, относящихся к одной главе.
Структуризация кода: Код разделен на отдельные функции с четко определенными обязанностями для улучшения читаемости и поддерживаемости.
Обработка ошибок и логирование: Добавлено подробное логирование и обработка исключений для повышения надежности приложения.
Улучшение пользовательского интерфейса: Добавлены индикаторы прогресса и сообщения о статусе для повышения интерактивности приложения.
Ниже представлен полный обновленный код:
import streamlit as st
import os
import re
import tempfile
from io import BytesIO
import fitz # PyMuPDF
import zipfile
import logging
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from tqdm import tqdm
# Настройка логирования
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Настройка страницы приложения Streamlit
st.set_page_config(page_title="Автоматическое разделение PDF на главы", layout="wide")
# Функция для очистки имени файла от недопустимых символов
def sanitize_filename(name):
"""
Заменяет запрещенные символы в имени файла на подчеркивание.
Удаляет лишние пробелы.
"""
name = re.sub(r'[\\/*?:"<>|]', "_", name)
name = re.sub(r'\s+', ' ', name).strip()
return name
# Функция для извлечения текста из страницы
def extract_text_from_page(page):
try:
text = page.get_text()
return text.strip()
except Exception as e:
logger.error(f"Ошибка при извлечении текста из страницы: {e}")
return ""
# Функция для определения границ глав с использованием TF-IDF и косинусного сходства
def detect_chapter_boundaries(doc):
"""
Определяет границы глав на основе анализа содержания страниц.
Возвращает список кортежей (номер страницы начала главы, название главы).
"""
try:
page_texts = [extract_text_from_page(doc[page_num]) for page_num in range(len(doc))]
vectorizer = TfidfVectorizer().fit_transform(page_texts)
vectors = vectorizer.toarray()
chapter_starts = []
threshold = 0.1 # Порог для определения новой главы (можно настроить)
for i in range(len(vectors) - 1):
cos_sim = cosine_similarity([vectors[i]], [vectors[i+1]])[0][0]
if cos_sim < threshold:
# Предполагаем, что начинается новая глава
page = doc[i+1]
headings = extract_headings_from_page(page)
if headings:
main_heading = max(headings, key=lambda x: x[1])[0]
else:
main_heading = f"Глава_{i+1}"
chapter_starts.append((i+1, main_heading))
# Добавляем начало первой главы
first_page_headings = extract_headings_from_page(doc[0])
if first_page_headings:
first_heading = max(first_page_headings, key=lambda x: x[1])[0]
else:
first_heading = "Глава_0"
chapter_starts.insert(0, (0, first_heading))
return chapter_starts
except Exception as e:
logger.error(f"Ошибка при определении границ глав: {e}")
return []
# Функция для извлечения потенциальных заголовков из страницы
def extract_headings_from_page(page):
"""
Извлекает потенциальные заголовки из страницы,
основываясь на размере шрифта и положении текста.
"""
headings = []
try:
blocks = page.get_text("dict")["blocks"]
for block in blocks:
if "lines" in block:
for line in block["lines"]:
for span in line["spans"]:
text = span["text"].strip()
font_size = span["size"]
y_position = span["bbox"][1]
# Проверяем, находится ли текст в верхней трети страницы и имеет ли крупный размер шрифта
if y_position < page.rect.height * 0.3 and font_size >= 14:
# Добавляем текст в потенциальные заголовки
headings.append((text, font_size, y_position))
except Exception as e:
logger.error(f"Ошибка при извлечении заголовков из страницы: {e}")
return headings
# Функция для разделения PDF на главы
def split_pdf_by_chapters(pdf_path):
chapters = []
try:
with fitz.open(pdf_path) as doc:
with st.spinner("Определение границ глав..."):
chapter_starts = detect_chapter_boundaries(doc)
if not chapter_starts:
st.error("Не удалось обнаружить главы в документе.")
return []
# Добавляем конец документа в качестве последней границы
chapter_starts.append((len(doc), "Конец документа"))
st.write("Разделение документа на главы...")
progress_bar = st.progress(0)
total_chapters = len(chapter_starts) - 1
for idx in range(total_chapters):
start_page = chapter_starts[idx][0]
end_page = chapter_starts[idx+1][0] - 1
chapter_title = sanitize_filename(chapter_starts[idx][1])[:100]
chapter_doc = fitz.open()
chapter_doc.insert_pdf(doc, from_page=start_page, to_page=end_page)
output_bytes = chapter_doc.write()
chapters.append({
'title': f"{chapter_title}.pdf",
'start_page': start_page,
'end_page': end_page,
'file': output_bytes
})
chapter_doc.close()
progress_bar.progress((idx + 1) / total_chapters)
st.success("Документ успешно разделен на главы.")
except Exception as e:
logger.error(f"Ошибка при разделении PDF: {e}")
st.error(f"Ошибка при разделении PDF: {e}")
return chapters
# Главная функция приложения
def main():
st.title("Автоматическое разделение PDF на главы")
# ---- Загрузка PDF файла ----
uploaded_file = st.file_uploader("Выберите PDF файл", type=["pdf"])
if uploaded_file is not None:
st.write("Файл успешно загружен. Обрабатываем...")
try:
# Сохраняем загруженный файл во временное хранилище
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
tmp_file.write(uploaded_file.getvalue())
tmp_file_path = tmp_file.name
# Разделяем PDF на главы
chapters = split_pdf_by_chapters(tmp_file_path)
if chapters:
# Отображаем информацию о главах
for chapter in chapters:
st.write(f"{chapter['title']}: страницы {chapter['start_page']+1}-{chapter['end_page']+1}")
# Предлагаем скачать все главы в виде ZIP архива
zip_buffer = BytesIO()
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
for chapter in chapters:
filename = chapter['title']
zip_file.writestr(filename, chapter['file'])
zip_buffer.seek(0)
st.download_button(
label="Скачать все главы в формате ZIP",
data=zip_buffer,
file_name="Разделенные_главы.zip",
mime="application/zip"
)
else:
st.error("Не удалось разделить документ на главы.")
os.unlink(tmp_file_path)
except Exception as e:
logger.error(f"Произошла ошибка при обработке файла: {e}")
st.error(f"Произошла ошибка при обработке файла: {e}")
if __name__ == "__main__":
main()
Пояснения к обновленному коду:
Улучшенный алгоритм определения глав:
TF-IDF и косинусное сходство: Для каждой страницы извлекается текст, после чего вычисляются TF-IDF векторы. Косинусное сходство между последовательными страницами используется для определения момента, когда содержание значительно меняется, что может означать начало новой главы.
Пороговое значение: Используется пороговое значение сходства (по умолчанию 0.1), ниже которого считается, что начинается новая глава. Это значение можно настроить в зависимости от структуры конкретного документа.
Извлечение заголовков: При обнаружении возможного начала новой главы, из страницы пытаемся извлечь заголовок, основываясь на размере шрифта и положении текста. Если заголовок не найден, ему присваивается имя по умолчанию ("Глава_{номер}").
Структуризация кода: Код разделен на отдельные функции:
sanitize_filename: Очистка имени файла.
extract_text_from_page: Извлечение текста из страницы.
extract_headings_from_page: Извлечение потенциальных заголовков из страницы.
detect_chapter_boundaries: Определение границ глав.
split_pdf_by_chapters: Разделение PDF на главы.
main: Главная функция приложения.
Обработка ошибок и логирование: Добавлены блоки try-except для обработки возможных исключений с соответствующими сообщениями в логах и отображением ошибок пользователю.
Улучшение интерфейса:
Индикатор прогресса: При разделении документа на главы отображается индикатор прогресса (st.progress), показывающий ход выполнения операции.
Сообщения о статусе: Используются функции st.spinner и st.write для отображения текущего статуса обработки.
Необходимые зависимости:
PyMuPDF: Библиотека для работы с PDF (pip install PyMuPDF).
scikit-learn: Для TF-IDF и косинусного сходства (pip install scikit-learn).
tqdm: Для прогресс-бара в терминале (если необходимо) (pip install tqdm).
Примечания:
Пороговое значение для косинусного сходства может потребовать настройки в зависимости от специфики ваших документов. Рекомендуется экспериментировать с этим значением для достижения наилучших результатов.
Алгоритм, основанный на TF-IDF и косинусном сходстве, предполагает, что значительные изменения в содержании текста между страницами могут указывать на начало новой главы. Это не идеальное решение, но оно может работать лучше, чем простое сравнение размеров шрифтов и позиций текста.
Для более продвинутого разделения можно рассмотреть использование предварительно обученных моделей обработки естественного языка (NLP), таких как BERT, для более точного определения границ глав.
Надеюсь, этот обновленный код поможет вам в достижении ваших целей. Если у вас возникнут вопросы или потребуется дополнительная помощь, пожалуйста, дайте мне знать!