pratikshahp commited on
Commit
ebc0ac9
·
verified ·
1 Parent(s): b2e5d57

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -4
app.py CHANGED
@@ -1,17 +1,31 @@
1
  from PIL import Image
2
  import streamlit as st
3
- import pytesseract
4
  from transformers import LayoutLMForTokenClassification, LayoutLMTokenizer
5
 
6
  # Load Hugging Face models
7
  layoutlm_model = LayoutLMForTokenClassification.from_pretrained("microsoft/layoutlm-base-uncased")
8
  layoutlm_tokenizer = LayoutLMTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")
9
 
 
10
  # Function to extract text from image
11
  def extract_text_from_image(image):
12
- # Convert image to text using Tesseract OCR
13
- text = pytesseract.image_to_string(image)
14
- return text
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  # Function to generate response
17
  def generate_response(prompt, text):
@@ -40,3 +54,4 @@ if uploaded_file is not None:
40
  else:
41
  st.warning("Please upload an image.")
42
 
 
 
1
  from PIL import Image
2
  import streamlit as st
3
+ import torch
4
  from transformers import LayoutLMForTokenClassification, LayoutLMTokenizer
5
 
6
  # Load Hugging Face models
7
  layoutlm_model = LayoutLMForTokenClassification.from_pretrained("microsoft/layoutlm-base-uncased")
8
  layoutlm_tokenizer = LayoutLMTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")
9
 
10
+
11
  # Function to extract text from image
12
  def extract_text_from_image(image):
13
+ inputs = layoutlm_tokenizer(image, return_tensors="pt", padding=True, truncation=True)
14
+ with torch.no_grad():
15
+ outputs = layoutlm_model(**inputs)
16
+
17
+ # Get the predicted labels (classifications) from the model output
18
+ predicted_labels = torch.argmax(outputs.logits, dim=2)
19
+
20
+ # Convert labels to tokens using tokenizer
21
+ tokens = layoutlm_tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
22
+
23
+ # Filter out special tokens and format the extracted text
24
+ extracted_text = ""
25
+ for token, label in zip(tokens, predicted_labels[0]):
26
+ if label != layoutlm_tokenizer.label_pad_token_id:
27
+ extracted_text += token.replace("##", "") + " " # Removing '##' subwords
28
+ return extracted_text.strip()
29
 
30
  # Function to generate response
31
  def generate_response(prompt, text):
 
54
  else:
55
  st.warning("Please upload an image.")
56
 
57
+