import streamlit as st import requests from bs4 import BeautifulSoup import os import…
- User
import streamlit as st import requests from bs4 import BeautifulSoup import os import docx from PIL import Image import io import pytesseract from pdf2image import convert_from_path import random import tempfile import shutil import threading from concurrent.futures import ThreadPoolExecutor, as_completed
Устанавливаем путь к исполняемому файлу Tesseract OCR
pytesseract.pytesseract.tesseract_cmd = r"/usr/bin/tesseract" # Укажите путь к tesseract в вашей системе
Настройка заголовка приложения
st.set_page_config(page_title="Система обработки учебных материалов", layout="wide") st.title("Система обработки учебных материалов")
Функция поиска учебников
def search_textbooks(keywords, year): # Используем альтернативный метод поиска, например, через API какого-либо открытого ресурса # Поскольку прямой парсинг Google запрещен, здесь мы будем использовать Open Library Search API base_url = "http://openlibrary.org/search.json" params = { 'title': keywords, 'language': 'rus', 'published_in': str(year) } response = requests.get(base_url, params=params) if response.status_code != 200: st.error("Ошибка при поиске учебников") return []
data = response.json() textbooks = [] for doc in data.get('docs', []): title = doc.get('title') authors = doc.get('author_name', []) publish_year = doc.get('first_publish_year') if title and publish_year and publish_year >= year: textbooks.append({ 'title': title, 'authors': ", ".join(authors), 'year': publish_year, 'url': f"http://openlibrary.org{doc.get('key')}" }) return textbooksОптимизированная функция для конвертации PDF в DOCX
@st.cache(allow_output_mutation=True) def convert_to_doc(file): try: with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file: tmp_file.write(file.read()) tmp_file_path = tmp_file.name
images = convert_from_path(tmp_file_path, dpi=300) def process_image(image): return pytesseract.image_to_string(image, lang='rus') with ThreadPoolExecutor(max_workers=4) as executor: future_to_image = {executor.submit(process_image, image): image for image in images} text_parts = [] for future in as_completed(future_to_image): text_parts.append(future.result()) text = "\n".join(text_parts) doc = docx.Document() doc.add_paragraph(text) output_path = "converted_file.docx" doc.save(output_path) return output_path except Exception as e: st.error(f"Ошибка при конвертации: {e}") return None finally: if 'tmp_file_path' in locals(): os.unlink(tmp_file_path)Оптимизированная функция для разделения на главы
def split_into_chapters(doc_file): try: doc = docx.Document(doc_file) chapters = [] current_chapter = [] for para in doc.paragraphs: if para.style.name.startswith('Heading'): if current_chapter: chapters.append("\n".join(current_chapter)) current_chapter = [] current_chapter.append(para.text)
- Assistant