rajsinghparihar commited on
Commit
93762d1
1 Parent(s): 862ba62

first commit: doc-info-ext v0.0.1

Browse files
.gitignore ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
161
+
162
+ *.zip
163
+ *.xlsx
164
+ *.png
165
+ *.ipynb
166
+ *.DS_Store
167
+ *.db
168
+ *.tar
README.md CHANGED
@@ -1,12 +1,12 @@
1
  ---
2
- title: Document Information Extraction
3
  emoji: 🔥
4
- colorFrom: gray
5
- colorTo: blue
6
- sdk: streamlit
7
- sdk_version: 1.35.0
8
  app_file: app.py
9
- pinned: false
10
  license: apache-2.0
11
  ---
12
 
 
1
  ---
2
+ title: Document Information Extractor
3
  emoji: 🔥
4
+ colorFrom: purple
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 3.3.1
8
  app_file: app.py
9
+ pinned: true
10
  license: apache-2.0
11
  ---
12
 
app.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from rag import RAG, ServiceContextModule
3
+ from llama_index.core import set_global_service_context
4
+ from dotenv import load_dotenv
5
+ import json
6
+ from prompts import general_prompt
7
+ from gradio_pdf import PDF
8
+ import requests
9
+
10
+ service_context_module = None
11
+ current_model = None
12
+
13
+
14
+ def initialize(api_key, model_name):
15
+ global service_context_module, current_model
16
+ gr.Info("Initializing app")
17
+ load_dotenv(override=True)
18
+ url = "https://api.groq.com/openai/v1/models"
19
+ headers = {
20
+ "Authorization": f"Bearer {api_key}",
21
+ "Content-Type": "application/json",
22
+ }
23
+ try:
24
+ response = requests.get(url, headers=headers)
25
+ data = response.json()
26
+ models = [model["id"] for model in data["data"]]
27
+
28
+ except Exception:
29
+ gr.Error("Invalid API KEY")
30
+ return gr.update(choices=[])
31
+
32
+ if not service_context_module or current_model != model_name:
33
+ service_context_module = ServiceContextModule(api_key, model_name)
34
+ current_model = model_name
35
+ gr.Info("App started")
36
+ set_global_service_context(
37
+ service_context=service_context_module.service_context
38
+ )
39
+ else:
40
+ gr.Info("App is already running")
41
+
42
+ return gr.update(choices=models)
43
+
44
+
45
+ def process_document(file, query):
46
+ if file.endswith(".pdf"):
47
+ return process_pdf(file, query=query)
48
+ else:
49
+ return "Unsupported file format"
50
+
51
+
52
+ def postprocess_json_string(json_string: str) -> dict:
53
+ json_string = json_string.replace("'", '"')
54
+ json_string = json_string[json_string.rfind("{") : json_string.rfind("}") + 1]
55
+ try:
56
+ json_data = json.loads(json_string)
57
+ except Exception as e:
58
+ print("Error parsing output, invalid json format", e)
59
+ return json_data
60
+
61
+
62
+ def process_pdf(file, query):
63
+ rag_module = RAG(filepaths=[file])
64
+ fields = [field for field in query.split(",")]
65
+ formatted_prompt = general_prompt(fields=fields)
66
+ response = rag_module.run_query_engine(prompt=formatted_prompt)
67
+ extracted_json = postprocess_json_string(json_string=response)
68
+ return extracted_json
69
+
70
+
71
+ with gr.Blocks(title="Document Information Extractor.") as app:
72
+ gr.Markdown(
73
+ value="""
74
+ # Welcome to Document Information Extractor.
75
+ Created by [@rajsinghparihar](https://huggingface.co/rajsinghparihar) for extracting useful information from pdf documents like invoices, salary slips, etc.
76
+ ## Usage:
77
+ - In the Init Section, Enter your `GROQ_API_KEY` in the corresponding labeled textbox.
78
+ - choose the model from the list of available models.
79
+ - click `Initialize` to start the app.
80
+
81
+ - In the app section, you can upload a document (pdf files: currently works for readable pdfs only, will add ocr functionality later)
82
+ - Enter the entities you wanna extract as a comma seperated string. (check the examples for more info)
83
+ - Click Submit to see the extracted entities as a JSON object.
84
+ """
85
+ )
86
+ with gr.Tab(label="Init Section") as init_tab:
87
+ with gr.Row():
88
+ api_key = gr.Text(label="Enter your Groq API KEY", type="password")
89
+ available_models = gr.Dropdown(
90
+ label="Choose your LLM",
91
+ choices=[
92
+ "gemma-7b-it",
93
+ "llama3-70b-8192",
94
+ "llama3-8b-8192",
95
+ "mixtral-8x7b-32768",
96
+ "whisper-large-v3",
97
+ ],
98
+ )
99
+ init_btn = gr.Button(value="Initialize")
100
+ init_btn.click(
101
+ fn=initialize,
102
+ inputs=[api_key, available_models],
103
+ outputs=available_models,
104
+ )
105
+ with gr.Tab(label="App Section") as app_tab:
106
+ iface = gr.Interface(
107
+ fn=process_document,
108
+ inputs=[
109
+ PDF(label="Document"),
110
+ gr.Text(
111
+ label="Entities you wanna extract in comma separated string format"
112
+ ),
113
+ ],
114
+ outputs=gr.JSON(label="Extracted Entities"),
115
+ description="Upload a PDF document and extract specified entities from it.",
116
+ examples=[
117
+ [
118
+ "examples/Commerce Bank Statement Sample.pdf",
119
+ "Customer Name, Account Number, Statement Date, Ending Balance, Total Deposits, Checks Paid",
120
+ ],
121
+ [
122
+ "examples/Salary-Slip-pdf.pdf",
123
+ "Employee Name, Bank Name, Location, Total Salary, Total Deductions",
124
+ ],
125
+ ],
126
+ )
127
+ gr.Markdown("""
128
+ ## Pros of LLMs as information extractors over current extraction solutions:
129
+ - LLMs are able to understand the scope of the problem from the context and are more robust to typos or extraction failure
130
+
131
+ ## Cons
132
+ - Higher Inference Cost
133
+ - Can't use free APIs for Sensitive documents.
134
+ """)
135
+
136
+ app.launch(server_name="0.0.0.0", server_port=7860)
examples/Commerce Bank Statement Sample.pdf ADDED
Binary file (55.1 kB). View file
 
examples/Salary-Slip-pdf.pdf ADDED
Binary file (38.3 kB). View file
 
prompts.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import outlines
2
+
3
+
4
+ @outlines.prompt
5
+ def general_prompt(fields):
6
+ """
7
+ You are an entity extractor.
8
+ Using the information in the provided documents, use your deep understanding of documents and complete the following tasks.
9
+ 1. Answer the question, What are the values of the following, {{ fields }}?
10
+ 2. Print the answers against each field in a step by step approach.
11
+ 3. After you have all the answers ready, Please format the response in JSON format, with these fields as keys and their answers as values.
12
+
13
+ Make sure to follow the Instructions below.
14
+ 1. In the records, make sure to only include the values of the descriptors without any descriptor names.
15
+ 2. Do NOT Create a Nested JSON response. If response is Nested, format it to a simpler JSON format.
16
+ 2. Avoid keywords like <<SYS>> or [SYS] or [INST] in the final response.
17
+ """
rag.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from llama_index.core import (
2
+ VectorStoreIndex,
3
+ SimpleDirectoryReader,
4
+ get_response_synthesizer,
5
+ ServiceContext,
6
+ )
7
+ from llama_index.embeddings.huggingface import HuggingFaceEmbedding
8
+ from llama_index.core.postprocessor import SentenceTransformerRerank
9
+ from typing import Optional, List
10
+ from llama_index.llms.groq import Groq
11
+
12
+
13
+ class RAG:
14
+ def __init__(
15
+ self, filepaths: List[str], rerank: Optional[SentenceTransformerRerank] = None
16
+ ) -> None:
17
+ documents = SimpleDirectoryReader(input_files=filepaths).load_data()
18
+ response_synthesizer = get_response_synthesizer(
19
+ response_mode="tree_summarize",
20
+ use_async=True,
21
+ )
22
+ self.index = VectorStoreIndex.from_documents(
23
+ documents=documents,
24
+ response_synthesizer=response_synthesizer,
25
+ )
26
+ if not rerank:
27
+ self.query_engine = self.index.as_query_engine(
28
+ response_mode="tree_summarize",
29
+ use_async=True,
30
+ streaming=True,
31
+ similarity_top_k=10,
32
+ )
33
+ else:
34
+ self.query_engine = self.index.as_query_engine(
35
+ response_mode="tree_summarize",
36
+ use_async=True,
37
+ streaming=True,
38
+ similarity_top_k=10,
39
+ node_postprocessors=[rerank],
40
+ )
41
+
42
+ def run_query_engine(self, prompt):
43
+ response = self.query_engine.query(prompt)
44
+ response.print_response_stream()
45
+ return str(response)
46
+
47
+
48
+ class ServiceContextModule:
49
+ def __init__(self, api_key, model_name) -> None:
50
+ self._llm = Groq(model=model_name, api_key=api_key)
51
+ self._embedding_model = HuggingFaceEmbedding(
52
+ "Snowflake/snowflake-arctic-embed-m-long", trust_remote_code=True
53
+ )
54
+ self.service_context = ServiceContext.from_defaults(
55
+ llm=self._llm,
56
+ embed_model=self._embedding_model,
57
+ )
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio
2
+ llama-index
3
+ llama-index-llms-groq
4
+ llama-index-embeddings-huggingface
5
+ einops
6
+ outlines
7
+ gradio_pdf