pratikshahp commited on
Commit
95a0fec
·
verified ·
1 Parent(s): 78ff6b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -36
app.py CHANGED
@@ -1,46 +1,53 @@
 
 
 
 
1
  import streamlit as st
2
  from PIL import Image
3
- import torch
4
- from transformers import LayoutLMv2Processor, LayoutLMv2ForQuestionAnswering
5
 
6
- @st.cache(allow_output_mutation=True)
7
- def load_model():
8
- processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased")
9
- model = LayoutLMv2ForQuestionAnswering.from_pretrained("microsoft/layoutlmv2-base-uncased")
10
- return processor, model
 
 
11
 
12
- # Function to process the image and return the extracted information
13
- def process_image(image, question, processor, model):
14
- # Prepare the image for the model
15
- encoding = processor(image, question, return_tensors="pt", truncation=True, padding="max_length", max_length=512)
16
- # Make sure we have the pixel values (image), input IDs, attention mask, and token type IDs
17
- inputs = {k: v.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu')) for k, v in encoding.items()}
18
- # Move model to the appropriate device
19
- model.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu'))
20
- # Perform the forward pass
21
- outputs = model(**inputs)
22
- start_logits = outputs.start_logits
23
- end_logits = outputs.end_logits
24
- # Get the most likely beginning and end of answer with the argmax of the logits
25
- all_tokens = processor.tokenizer.convert_ids_to_tokens(inputs['input_ids'].squeeze().tolist())
26
- answer = ' '.join(all_tokens[torch.argmax(start_logits):torch.argmax(end_logits)+1])
27
- return answer
28
 
 
29
  st.set_page_config(page_title="Invoice Extractor")
30
- st.header("Invoice Extractor using LayoutLMv2")
31
-
32
- question = st.text_input("Enter your question about the invoice:")
33
- uploaded_file = st.file_uploader("Choose an invoice image...", type=["jpg", "jpeg", "png"])
34
- image = None
35
  if uploaded_file is not None:
36
  image = Image.open(uploaded_file)
37
- st.image(image, caption="Uploaded Image.", use_column_width=True)
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- submit = st.button("Get Answer")
40
 
41
- if submit and image is not None and question:
42
- st.write("Processing...")
43
- processor, model = load_model()
44
- answer = process_image(image, question, processor, model)
45
- st.subheader("The response is:")
46
- st.write(answer)
 
1
+
2
+
3
+ #Invoice Extractor
4
+ import os
5
  import streamlit as st
6
  from PIL import Image
7
+ from transformers import AutoProcessor, AutoModelForTokenClassification
 
8
 
9
+ #function to load gemini pro vision model and get response
10
+ def get_model_response(input,image,prompt): #input: how LLM model behave like, #image: To extract info, prompt: ask something
11
+ #load a model
12
+ processor = AutoProcessor.from_pretrained("monuirctc/invoice-extraction")
13
+ model = AutoModelForTokenClassification.from_pretrained("monuirctc/invoice-extraction")
14
+ response=model.generate_content([input,image[0],prompt]) #get response from model
15
+ return response.text
16
 
17
+ #function to provide image
18
+ def input_image_setup(uploaded_file):
19
+ if uploaded_file is not None:
20
+ #read te file into byte
21
+ bytes_data = uploaded_file.getvalue()
22
+ image_parts=[
23
+ {
24
+ "mime_type": uploaded_file.type,
25
+ "data": bytes_data
26
+ }
27
+ ]
28
+ return image_parts
29
+ else:
30
+ raise FileNotFoundError("No file uploaded")
 
 
31
 
32
+ #Streamlit App
33
  st.set_page_config(page_title="Invoice Extractor")
34
+ st.header("Gemini Application")
35
+ input=st.text_input("Input Prompt: ",key="input")
36
+ uploaded_file = st.file_uploader("choose an image...", type=["jpg","jpeg","png"])
37
+ image=""
 
38
  if uploaded_file is not None:
39
  image = Image.open(uploaded_file)
40
+ st.image(image, caption="Uploaded Image.", use_column_width=True)
41
+ submit = st.button("Tell me about the invoice")
42
+ input_prompt="""
43
+ You are an expert in understanding invoices. you will receive input images as invoices and
44
+ you will have to answer questions based on the input image.
45
+ """
46
+ #if submit button is clicked,
47
+ if submit:
48
+ image_data=input_image_setup(uploaded_file)
49
+ response=get_model_response(input_prompt,image_data,input)
50
+ st.subheader("The response is..")
51
+ st.write(response)
52
 
 
53