pryanshusharma commited on
Commit
1feeb09
1 Parent(s): 8b75ff9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -0
app.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import requests
3
+ import gradio as gr
4
+
5
+ def read_image_from_stream(image_path, subscription_key, endpoint):
6
+ with open(image_path, 'rb') as image_file:
7
+ image_data = image_file.read()
8
+
9
+ headers = {
10
+ 'Ocp-Apim-Subscription-Key': subscription_key,
11
+ 'Content-Type': 'application/octet-stream'
12
+ }
13
+
14
+ response = requests.post(f"{endpoint}/vision/v3.2/read/analyze", headers=headers, data=image_data)
15
+
16
+ if response.status_code == 202:
17
+ read_response_headers = response.headers
18
+ operation_location = read_response_headers["Operation-Location"]
19
+ else:
20
+ raise Exception(f"Unexpected response status: {response.status_code}")
21
+
22
+ return operation_location
23
+
24
+ def get_read_result(operation_location, subscription_key):
25
+ headers = {
26
+ 'Ocp-Apim-Subscription-Key': subscription_key
27
+ }
28
+
29
+ while True:
30
+ response = requests.get(operation_location, headers=headers)
31
+ if response.status_code == 200: # HTTP 200 indicates success
32
+ read_result = response.json()
33
+ status = read_result['status']
34
+ if status == 'succeeded':
35
+ break
36
+ elif status in ['failed', 'notStarted', 'running']:
37
+ time.sleep(1) # Wait before polling again
38
+ else:
39
+ raise Exception(f"Unexpected status: {status}")
40
+ else:
41
+ raise Exception(f"Unexpected response status: {response.status_code}")
42
+
43
+ return read_result
44
+
45
+ def process_image(image_path, subscription_key, endpoint):
46
+ operation_location = read_image_from_stream(image_path, subscription_key, endpoint)
47
+ operation_id = operation_location.split("/")[-1]
48
+ operation_location = f"{endpoint}/vision/v3.2/read/analyzeResults/{operation_id}"
49
+
50
+ read_result = get_read_result(operation_location, subscription_key)
51
+
52
+ if read_result['status'] == 'succeeded':
53
+ output = []
54
+ for text_result in read_result['analyzeResult']['readResults']:
55
+ for line in text_result['lines']:
56
+ output.append(line['text'])
57
+ return " ".join(output).replace("\n", " ") # Join lines and replace newlines with spaces
58
+ else:
59
+ return "Processing failed or did not succeed."
60
+
61
+ def main():
62
+ interface = gr.Interface(
63
+ fn=process_image,
64
+ inputs=[
65
+ gr.Image(type="filepath", label="Upload Image"),
66
+ gr.Textbox(label="Subscription Key"),
67
+ gr.Textbox(label="Endpoint URL")
68
+ ],
69
+ outputs=gr.Textbox(),
70
+ title="Azure OCR with Gradio",
71
+ description="Upload an image, provide your Azure subscription key and endpoint URL to perform OCR and get the text."
72
+ )
73
+ interface.launch()
74
+
75
+ if __name__ == "__main__":
76
+ main()