138 lines
7.2 KiB
Python
138 lines
7.2 KiB
Python
"""Protocol regressions without loading models or accelerator runtimes."""
|
|
import ast
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
import tempfile
|
|
from types import ModuleType
|
|
import unittest
|
|
from unittest.mock import Mock, patch
|
|
import zipfile
|
|
from io import BytesIO
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
sys.path.insert(0, str(ROOT))
|
|
|
|
|
|
class HeadingTests(unittest.TestCase):
|
|
def test_markdown_and_content_lists_keep_levels_five_and_six(self):
|
|
from mineru.utils.enum_class import BlockType, ContentType, MakeMode
|
|
for backend, render in (
|
|
('pipeline', 'make_blocks_to_markdown'), ('vlm', 'mk_blocks_to_markdown'),
|
|
):
|
|
path = ROOT / f'mineru/backend/{backend}/{backend}_middle_json_mkcontent.py'
|
|
source = ast.parse(path.read_text(encoding='utf-8'))
|
|
names = {'get_title_level', render, 'make_blocks_to_content_list'}
|
|
functions = ast.Module(body=[node for node in source.body if isinstance(node, ast.FunctionDef)
|
|
and node.name in names], type_ignores=[])
|
|
scope = {'BlockType': BlockType, 'ContentType': ContentType, 'MakeMode': MakeMode,
|
|
'merge_para_with_text': lambda block: block['text']}
|
|
exec(compile(functions, str(path), 'exec'), scope)
|
|
for level in (1, 4, 5, 6, 9):
|
|
with self.subTest(backend=backend, level=level):
|
|
block = {'type': BlockType.TITLE, 'level': level, 'text': 'Heading', 'bbox': [0, 0, 10, 10]}
|
|
args = ([block], MakeMode.MM_MD)
|
|
if backend == 'vlm':
|
|
args += (True, True)
|
|
self.assertEqual(scope[render](*args), ['#' * min(level, 6) + ' Heading'])
|
|
content = scope['make_blocks_to_content_list'](block, '', 0, [100, 100])
|
|
self.assertEqual(content['text_level'], min(level, 6))
|
|
|
|
|
|
class ProtocolTests(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
common = ModuleType('mineru.cli.common')
|
|
common.aio_do_parse = Mock()
|
|
common.read_fn = lambda path: Path(path).read_bytes()
|
|
common.pdf_suffixes, common.image_suffixes, common.word_suffixes = ['pdf'], ['png'], ['docx', 'doc']
|
|
config = ModuleType('mineru.utils.config_reader')
|
|
config.get_device = lambda: 'cpu'
|
|
models = ModuleType('mineru.utils.model_utils')
|
|
models.clean_memory = Mock()
|
|
suffixes = ModuleType('mineru.utils.guess_suffix_or_lang')
|
|
suffixes.guess_suffix_by_path = lambda path: Path(path).suffix.lstrip('.')
|
|
cls.stubs = patch.dict(sys.modules, {module.__name__: module for module in (common, config, models, suffixes)})
|
|
cls.stubs.start()
|
|
spec = importlib.util.spec_from_file_location('parser276_api_test', ROOT / 'mineru/cli/fast_api.py')
|
|
cls.api = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(cls.api)
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
cls.stubs.stop()
|
|
|
|
def setUp(self):
|
|
from fastapi.testclient import TestClient
|
|
self.temp = tempfile.TemporaryDirectory(dir=ROOT / 'tests')
|
|
self.addCleanup(self.temp.cleanup)
|
|
self.directory = Path(self.temp.name)
|
|
temp_patch = patch.object(tempfile, 'tempdir', self.temp.name)
|
|
temp_patch.start()
|
|
self.addCleanup(temp_patch.stop)
|
|
self.api._task_progress_dir = self.directory / 'progress'
|
|
self.api._task_progress.clear()
|
|
self.api.app = self.api.create_app()
|
|
self.client = TestClient(self.api.app)
|
|
self.addCleanup(self.client.close)
|
|
|
|
async def fake_parse(**kwargs):
|
|
self.engine_options = kwargs
|
|
for name in kwargs['pdf_file_names']:
|
|
backend = kwargs['backend']
|
|
subdir = kwargs['parse_method'] if backend == 'pipeline' else (
|
|
'vlm' if backend.startswith('vlm') else 'hybrid_' + kwargs['parse_method'])
|
|
folder = Path(kwargs['output_dir']) / name / subdir
|
|
(folder / 'images').mkdir(parents=True)
|
|
(folder / f'{name}.md').write_text('# Chapter\n##### Detail\n###### Leaf\n')
|
|
for suffix, data in (('_middle.json', {'pdf_info': [{'level': 6}]}),
|
|
('_model.json', [{'level': 6}]), ('_content_list.json', [{'text_level': 6}])):
|
|
(folder / (name + suffix)).write_text(json.dumps(data))
|
|
(folder / 'images/a.jpg').write_bytes(b'test-image')
|
|
self.parse_patch = patch.object(self.api, 'aio_do_parse', fake_parse)
|
|
self.parse_patch.start()
|
|
self.addCleanup(self.parse_patch.stop)
|
|
|
|
def request(self, route='/file_parse', **options):
|
|
fields = {'backend': 'pipeline', 'output_dir': str(self.directory / 'output'),
|
|
'return_md': 'true', 'return_middle_json': 'true', 'return_images': 'true',
|
|
'return_model_output': 'true', 'return_content_list': 'true', **options}
|
|
return self.client.post(route, files={'files': ('test276.pdf', b'%PDF-test', 'application/pdf')}, data=fields)
|
|
|
|
def test_maxkb_and_application_routes_return_complete_results_and_clean_outputs(self):
|
|
for route in ('/file_parse', '/api/file_parse'):
|
|
with self.subTest(route=route):
|
|
response = self.request(route)
|
|
self.assertEqual(response.status_code, 200, response.text)
|
|
self.assertEqual(response.json()['version'], '2.7.6')
|
|
data = response.json()['results']['test276']
|
|
self.assertIn('###### Leaf', data['md_content'])
|
|
self.assertEqual(json.loads(data['middle_json'])['pdf_info'][0]['level'], 6)
|
|
self.assertEqual(json.loads(data['content_list'])[0]['text_level'], 6)
|
|
self.assertTrue(data['images']['a.jpg'].startswith('data:image/jpeg;base64,'))
|
|
self.assertEqual(list((self.directory / 'output').iterdir()), [])
|
|
|
|
def test_zip_contains_requested_json_and_images(self):
|
|
response = self.request(response_format_zip='true')
|
|
self.assertEqual(response.status_code, 200, response.text)
|
|
with zipfile.ZipFile(BytesIO(response.content)) as archive:
|
|
self.assertEqual(set(archive.namelist()), {
|
|
'test276/test276.md', 'test276/test276_middle.json', 'test276/test276_model.json',
|
|
'test276/test276_content_list.json', 'test276/images/a.jpg'})
|
|
|
|
def test_gpu_option_reaches_the_served_app_and_invalid_value_fails(self):
|
|
from click.testing import CliRunner
|
|
with patch.object(self.api.uvicorn, 'run') as serve, patch.dict(os.environ, {'MINERU_GPU_MEMORY_UTILIZATION': '0.4'}):
|
|
result = CliRunner().invoke(self.api.main, ['--host', '127.0.0.1'])
|
|
self.assertEqual(result.exit_code, 0, result.output)
|
|
self.assertIs(serve.call_args.args[0], self.api.app)
|
|
self.assertEqual(self.api.app.state.config['gpu_memory_utilization'], 0.4)
|
|
with patch.dict(os.environ, {'MINERU_GPU_MEMORY_UTILIZATION': '1.1'}):
|
|
self.assertNotEqual(CliRunner().invoke(self.api.main, []).exit_code, 0)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|