Skip to content

Commit d72abf3

Browse files
authored
Merge pull request #148 from harmonydata/experiment_ai_pdf_extraction
Experiment ai pdf extraction
2 parents 1404342 + 0e2edb4 commit d72abf3

9 files changed

Lines changed: 294 additions & 9 deletions

File tree

‎.github/workflows/test.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ jobs:
1818
runs-on: ubuntu-latest
1919
strategy:
2020
matrix:
21-
python: [3.10.11]
21+
python: [3.15.2]
2222

2323
steps:
2424
- uses: actions/checkout@v4

‎requirements.txt‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,6 @@ sklearn-crfsuite>=0.5.0
1212
scikit-learn>=1.6.1
1313
scipy>=1.13.1
1414
huggingface-hub>=0.30.2
15-
sklearn-crfsuite==0.5.0
16-
scipy==1.14.1
1715
torch==2.2.2
1816
transformers==4.50.3
1917
fpdf2~=2.8.2

‎src/harmony/parsing/pdf_parser.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
from tqdm import tqdm
3535
from transformers import AutoModelForTokenClassification, AutoTokenizer
3636
from typing import List
37+
from harmony.schemas.enums.parsing_methods import ParsingMethod
3738

3839
import harmony
3940

@@ -188,5 +189,5 @@ def convert_pdf_to_instruments(file: RawFile) -> List[Instrument]:
188189

189190
instrument = harmony.create_instrument_from_list(question_texts_entire_document, answer_texts_entire_document,
190191
instrument_name=file.file_name,
191-
file_name=file.file_name)
192+
file_name=file.file_name, parsing_method=ParsingMethod.harmony_custom_pdf_model)
192193
return [instrument]

‎src/harmony/parsing/wrapper_all_parsers.py‎

Lines changed: 101 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,19 +27,117 @@
2727
from harmony.parsing.html_parser import convert_html_to_instruments
2828
from harmony.parsing.google_forms_parser import convert_google_forms_to_instruments
2929
from harmony.schemas.enums.file_types import FileType
30-
from harmony.schemas.requests.text import RawFile, Instrument
30+
from harmony.schemas.enums.parsing_methods import ParsingMethod
31+
from harmony.schemas.requests.text import RawFile, Instrument, Question
32+
import os
33+
import base64
34+
import io
35+
import logging
36+
import uuid
37+
38+
logger = logging.getLogger(__name__)
39+
40+
# PDFs and images are sent to OpenAI when OPENAI_API_KEY is set and the base64 content is under this length,
41+
# which is OpenAI's 50 MB per-file limit once base64 has added its third.
42+
# Anything else, or any failure in the OpenAI call, goes to the standard parsers below.
43+
OPENAI_MAX_CONTENT_LENGTH = 50 * 1024 * 1024 * 4 // 3
44+
OPENAI_FILE_TYPES = (FileType.pdf, FileType.png, FileType.jpg, FileType.jpeg)
45+
46+
47+
def _convert_with_openai(file: RawFile) -> List[Instrument]:
48+
"""
49+
Extract the questions from a PDF or an image with OpenAI.
50+
openai is imported here, so harmony still works without it installed.
51+
"""
52+
from typing import Optional
53+
from openai import OpenAI
54+
from pydantic import BaseModel, Field
55+
56+
class ExtractedQuestion(BaseModel):
57+
question_no: Optional[str] = Field(None, description="Number of the question")
58+
question_intro: Optional[str] = Field(None, description="Introductory text applying to the question")
59+
question_text: str = Field(description="Text of the question", min_length=1)
60+
response_options: List[str] = Field([], description="The possible answer options")
61+
62+
class QuestionList(BaseModel):
63+
questions: List[ExtractedQuestion]
64+
65+
client = OpenAI()
66+
67+
if file.file_type == FileType.pdf:
68+
# Upload the PDF file using the Files API
69+
content_type, content_string = file.content.split(",")
70+
file_in_bytes = base64.b64decode(content_string)
71+
72+
uploaded_file = client.files.create(
73+
file=("document.pdf", io.BytesIO(file_in_bytes), "application/pdf"),
74+
purpose="user_data",
75+
expires_after={
76+
"anchor": "created_at",
77+
"seconds": 3600
78+
}
79+
)
80+
document_name = "PDF"
81+
document_input = {
82+
"type": "input_file",
83+
"file_id": uploaded_file.id,
84+
}
85+
parsing_method = ParsingMethod.gen_ai_pdf
86+
else:
87+
# Images: we can process directly in a single call
88+
document_name = "image"
89+
document_input = {
90+
"type": "input_image",
91+
"image_url": file.content,
92+
}
93+
parsing_method = ParsingMethod.gen_ai_image
94+
95+
response = client.responses.parse(
96+
model="gpt-5.4-mini",
97+
input=[
98+
{
99+
"role": "user",
100+
"content": [
101+
{
102+
"type": "input_text",
103+
"text": f"Extract all questions, including any introductions and response options, from this {document_name}.",
104+
},
105+
document_input,
106+
],
107+
}
108+
],
109+
text_format=QuestionList
110+
)
111+
112+
questions = []
113+
for question in response.output_parsed.questions:
114+
questions.append(
115+
Question(question_no=question.question_no, question_intro=question.question_intro,
116+
question_text=question.question_text, options=question.response_options))
117+
118+
# Named the same way as the PDF parser names its instrument
119+
return [Instrument(questions=questions, instrument_name=file.file_name, instrument_id=uuid.uuid4().hex,
120+
file_name=file.file_name, file_id=uuid.uuid4().hex, parsing_method=parsing_method)]
31121

32122

33123
def _get_instruments_from_file(file):
34124
"""
35125
Route files to appropriate parsers based on file type.
36-
126+
37127
Args:
38128
file: RawFile object containing file content and metadata
39-
129+
40130
Returns:
41131
List[Instrument]: Parsed instruments from the file
42132
"""
133+
134+
if file.file_type in OPENAI_FILE_TYPES and len(file.content) < OPENAI_MAX_CONTENT_LENGTH \
135+
and os.environ.get("OPENAI_API_KEY"):
136+
try:
137+
return _convert_with_openai(file)
138+
except Exception:
139+
logger.exception("OpenAI extraction failed for %s, using the standard parser instead", file.file_name)
140+
43141
if file.file_type == FileType.pdf or file.file_type == FileType.docx:
44142
instruments_from_this_file = convert_pdf_to_instruments(file)
45143
elif file.file_type == FileType.txt or file.file_type == FileType.csv:

‎src/harmony/schemas/enums/file_types.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,7 @@ class FileType(str, Enum):
3232
docx: str = 'docx'
3333
html: str = 'html'
3434
htm: str = 'htm'
35+
png: str = 'png'
36+
jpg: str = 'jpg'
37+
jpeg: str = 'jpeg'
3538
google_forms: str = 'google_forms'
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
'''
2+
MIT License
3+
4+
Copyright (c) 2023 Ulster University (https://www.ulster.ac.uk).
5+
Project: Harmony (https://harmonydata.ac.uk)
6+
Maintainer: Thomas Wood (https://fastdatascience.com)
7+
8+
Permission is hereby granted, free of charge, to any person obtaining a copy
9+
of this software and associated documentation files (the "Software"), to deal
10+
in the Software without restriction, including without limitation the rights
11+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12+
copies of the Software, and to permit persons to whom the Software is
13+
furnished to do so, subject to the following conditions:
14+
15+
The above copyright notice and this permission notice shall be included in all
16+
copies or substantial portions of the Software.
17+
18+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24+
SOFTWARE.
25+
26+
'''
27+
28+
from enum import Enum
29+
30+
31+
class ParsingMethod(str, Enum):
32+
gen_ai_pdf: str = 'gen_ai_pdf'
33+
gen_ai_image: str = 'gen_ai_image'
34+
harmony_custom_pdf_model: str = 'harmony_custom_pdf_model'

‎src/harmony/schemas/requests/text.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
from pydantic import ConfigDict, BaseModel, Field
3131
from harmony.schemas.enums.file_types import FileType
3232
from harmony.schemas.enums.languages import Language
33+
from harmony.schemas.enums.parsing_methods import ParsingMethod
3334

3435
DEFAULT_FRAMEWORK = "huggingface"
3536
DEFAULT_MODEL = 'sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2'
@@ -93,6 +94,7 @@ class Instrument(BaseModel):
9394
language: Language = Field(Language.English,
9495
description="The ISO 639-2 (alpha-2) encoding of the instrument language")
9596
questions: List[Question] = Field(description="The items inside the instrument")
97+
parsing_method: Optional[ParsingMethod] = Field(None, description="The method that was used to parse the instrument from the original document, e.g. PDF, generative AI, etc")
9698
model_config = ConfigDict(
9799
json_schema_extra={
98100
"example": {

‎src/harmony/util/instrument_helper.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,14 @@
2929
import json
3030
import uuid
3131

32+
from harmony.schemas.enums.parsing_methods import ParsingMethod
3233
from harmony.schemas.requests.text import Instrument, Question
3334

3435

3536
def create_instrument_from_list(question_texts: list[str], answer_texts: list[list] = None,
3637
question_numbers: list = None,
3738
instrument_name: str = "My instrument",
38-
file_name="My file") -> Instrument:
39+
file_name="My file", parsing_method: ParsingMethod = None) -> Instrument:
3940
"""
4041
Read a list of strings and create an Instrument object.
4142
@@ -48,6 +49,7 @@ def create_instrument_from_list(question_texts: list[str], answer_texts: list[li
4849
This list should be the same length as `question_texts`. Question numbers can be strings.
4950
:param instrument_name: Optional metadata containing name of the instrument.
5051
:param file_name: Optional metadata containing name of the file.
52+
:param parsing_method: Optional metadata around which method was used to extract the data from the original file e.g. PDF, generative AI, etc.
5153
:return: Single Instrument.
5254
"""
5355
questions = []
@@ -63,7 +65,7 @@ def create_instrument_from_list(question_texts: list[str], answer_texts: list[li
6365
Question(question_text=question_text, question_no=question_no, options=answer_texts_this_question))
6466

6567
return Instrument(questions=questions, instrument_name=instrument_name, instrument_id=uuid.uuid4().hex,
66-
file_name=file_name, file_id=uuid.uuid4().hex)
68+
file_name=file_name, file_id=uuid.uuid4().hex, parsing_method=parsing_method)
6769

6870

6971
def import_instrument_into_harmony_web(instrument: Instrument, harmony_fe_base_url="https://harmonydata.ac.uk") -> str:

‎tests/test_openai_extraction.py‎

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
'''
2+
MIT License
3+
4+
Copyright (c) 2023 Ulster University (https://www.ulster.ac.uk).
5+
Project: Harmony (https://harmonydata.ac.uk)
6+
Maintainer: Thomas Wood (https://fastdatascience.com)
7+
8+
Permission is hereby granted, free of charge, to any person obtaining a copy
9+
of this software and associated documentation files (the "Software"), to deal
10+
in the Software without restriction, including without limitation the rights
11+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12+
copies of the Software, and to permit persons to whom the Software is
13+
furnished to do so, subject to the following conditions:
14+
15+
The above copyright notice and this permission notice shall be included in all
16+
copies or substantial portions of the Software.
17+
18+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24+
SOFTWARE.
25+
26+
'''
27+
28+
import os
29+
import sys
30+
import types
31+
import unittest
32+
from types import SimpleNamespace
33+
from unittest import mock
34+
35+
sys.path.append("../src")
36+
37+
from harmony.parsing import wrapper_all_parsers
38+
from harmony.parsing.wrapper_all_parsers import convert_files_to_instruments
39+
from harmony.schemas.requests.text import RawFile, Instrument
40+
41+
pdf_file = RawFile.model_validate({
42+
"file_name": "GAD-7.pdf",
43+
"file_type": "pdf",
44+
"content": "data:application/pdf;base64,JVBERi0xLjQK"
45+
})
46+
47+
png_file = RawFile.model_validate({
48+
"file_name": "GAD-7.png",
49+
"file_type": "png",
50+
"content": "data:image/png;base64,iVBORw0KGgo="
51+
})
52+
53+
csv_file = RawFile.model_validate({
54+
"file_name": "GAD-7.csv",
55+
"file_type": "csv",
56+
"content": "I feel nervous\nI feel afraid"
57+
})
58+
59+
pdf_parser_result = [Instrument(instrument_name="from the PDF parser", questions=[])]
60+
61+
62+
def fake_openai_module(client):
63+
module = types.ModuleType("openai")
64+
module.OpenAI = mock.Mock(return_value=client)
65+
return module
66+
67+
68+
def fake_openai_client():
69+
client = mock.Mock()
70+
client.files.create.return_value = SimpleNamespace(id="file-abc")
71+
client.responses.parse.return_value = SimpleNamespace(output_parsed=SimpleNamespace(questions=[
72+
SimpleNamespace(question_no="1", question_intro="Over the last two weeks",
73+
question_text="Feeling nervous", response_options=["Not at all", "Several days"]),
74+
]))
75+
return client
76+
77+
78+
class TestOpenAIExtraction(unittest.TestCase):
79+
80+
def test_csv_parses_without_key_or_openai_installed(self):
81+
with mock.patch.dict(os.environ, {}, clear=True), mock.patch.dict(sys.modules, {"openai": None}):
82+
instruments = convert_files_to_instruments([csv_file])
83+
self.assertEqual(2, len(instruments[0].questions))
84+
85+
@mock.patch.object(wrapper_all_parsers, "convert_pdf_to_instruments", return_value=pdf_parser_result)
86+
def test_pdf_without_key_uses_pdf_parser(self, convert_pdf):
87+
with mock.patch.dict(os.environ, {}, clear=True):
88+
instruments = convert_files_to_instruments([pdf_file])
89+
self.assertEqual("from the PDF parser", instruments[0].instrument_name)
90+
91+
@mock.patch.object(wrapper_all_parsers, "convert_pdf_to_instruments", return_value=pdf_parser_result)
92+
def test_pdf_with_key_uses_openai(self, convert_pdf):
93+
client = fake_openai_client()
94+
with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "test"}), \
95+
mock.patch.dict(sys.modules, {"openai": fake_openai_module(client)}):
96+
instruments = convert_files_to_instruments([pdf_file])
97+
convert_pdf.assert_not_called()
98+
client.files.create.assert_called_once()
99+
self.assertEqual("GAD-7.pdf", instruments[0].instrument_name)
100+
self.assertEqual("GAD-7.pdf", instruments[0].file_name)
101+
self.assertEqual("Feeling nervous", instruments[0].questions[0].question_text)
102+
self.assertEqual("Over the last two weeks", instruments[0].questions[0].question_intro)
103+
self.assertEqual(["Not at all", "Several days"], instruments[0].questions[0].options)
104+
self.assertEqual(instruments[0].instrument_id, instruments[0].questions[0].instrument_id)
105+
106+
def test_image_with_key_uses_openai(self):
107+
client = fake_openai_client()
108+
with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "test"}), \
109+
mock.patch.dict(sys.modules, {"openai": fake_openai_module(client)}):
110+
instruments = convert_files_to_instruments([png_file])
111+
client.files.create.assert_not_called()
112+
self.assertEqual("GAD-7.png", instruments[0].instrument_name)
113+
self.assertEqual(1, len(instruments[0].questions))
114+
115+
@mock.patch.object(wrapper_all_parsers, "convert_pdf_to_instruments", return_value=pdf_parser_result)
116+
def test_pdf_falls_back_when_openai_fails(self, convert_pdf):
117+
client = fake_openai_client()
118+
client.responses.parse.side_effect = RuntimeError("rate limited")
119+
with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "test"}), \
120+
mock.patch.dict(sys.modules, {"openai": fake_openai_module(client)}):
121+
instruments = convert_files_to_instruments([pdf_file])
122+
self.assertEqual("from the PDF parser", instruments[0].instrument_name)
123+
124+
@mock.patch.object(wrapper_all_parsers, "OPENAI_MAX_CONTENT_LENGTH", 100)
125+
@mock.patch.object(wrapper_all_parsers, "convert_pdf_to_instruments", return_value=pdf_parser_result)
126+
def test_large_pdf_uses_pdf_parser(self, convert_pdf):
127+
large_pdf_file = pdf_file.model_copy(update={"content": "data:application/pdf;base64," + "A" * 100})
128+
client = fake_openai_client()
129+
with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "test"}), \
130+
mock.patch.dict(sys.modules, {"openai": fake_openai_module(client)}):
131+
instruments = convert_files_to_instruments([large_pdf_file])
132+
client.responses.parse.assert_not_called()
133+
self.assertEqual("from the PDF parser", instruments[0].instrument_name)
134+
135+
@mock.patch.object(wrapper_all_parsers, "convert_pdf_to_instruments", return_value=pdf_parser_result)
136+
def test_docx_with_key_uses_pdf_parser(self, convert_pdf):
137+
docx_file = pdf_file.model_copy(update={"file_name": "GAD-7.docx", "file_type": "docx"})
138+
client = fake_openai_client()
139+
with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "test"}), \
140+
mock.patch.dict(sys.modules, {"openai": fake_openai_module(client)}):
141+
instruments = convert_files_to_instruments([docx_file])
142+
client.responses.parse.assert_not_called()
143+
self.assertEqual("from the PDF parser", instruments[0].instrument_name)
144+
145+
146+
if __name__ == '__main__':
147+
unittest.main()

0 commit comments

Comments
 (0)