5m4ck3r commited on
Commit
10f6029
·
verified ·
1 Parent(s): f42329d

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +57 -26
main.py CHANGED
@@ -6,6 +6,60 @@ import io
6
  import random
7
  import string
8
  from mimetypes import guess_type
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  def get_answer(image: io.BytesIO, question: str):
11
  filename = image.name
@@ -55,30 +109,7 @@ def valuate_qna(p: str, r: str) -> str:
55
  return hug.output.get("data", [None])[0]
56
 
57
  def ocr(image: io.BytesIO) -> str:
58
- spid3 = os.getenv('SPID3')
59
- hug = hugging(spid3)
60
- filelink = hug.upload(image)
61
- image.seek(0, 2)
62
- file_size = image.tell()
63
- image.seek(0)
64
- image_mime_type, _ = guess_type(image.name)
65
- data = [
66
- {
67
- "meta": {
68
- "_type": "gradio.FileData"
69
- },
70
- "mime_type": image_mime_type,
71
- "orig_name": image.name,
72
- "path": filelink.split("=", 1)[1],
73
- "size": file_size,
74
- "url": filelink
75
- },
76
- os.getenv('AZKEY'),
77
- os.getenv('AZURL')
78
- ]
79
- eventid = hug.filnal_setup(data, 0, 13)
80
- hug.start()
81
- return data, hug.output #.get("data", [None])[0]
82
 
83
  app = Flask(__name__)
84
 
@@ -132,8 +163,8 @@ def task_ocr():
132
  headers = dict(request.headers)
133
  if not headers.get("KEY") != os.getenv("KEY"):
134
  return jsonify({"status" : False, "msg" : "Invalid API Key"}), 404
135
- eventid, answer = ocr(file_content)
136
- return jsonify({"status" : True, "data" : answer, "other" : eventid})
137
 
138
  @app.route('/check', methods=['POST', 'GET'])
139
  def check_f():
 
6
  import random
7
  import string
8
  from mimetypes import guess_type
9
+ import requests
10
+ import time
11
+
12
+ def read_image_from_stream(image_data, subscription_key, endpoint):
13
+
14
+ headers = {
15
+ 'Ocp-Apim-Subscription-Key': subscription_key,
16
+ 'Content-Type': 'application/octet-stream'
17
+ }
18
+
19
+ response = requests.post(f"{endpoint}/vision/v3.2/read/analyze", headers=headers, data=image_data)
20
+
21
+ if response.status_code == 202:
22
+ read_response_headers = response.headers
23
+ operation_location = read_response_headers["Operation-Location"]
24
+ else:
25
+ raise Exception(f"Unexpected response status: {response.status_code}")
26
+
27
+ return operation_location
28
+
29
+ def get_read_result(operation_location, subscription_key):
30
+ headers = {
31
+ 'Ocp-Apim-Subscription-Key': subscription_key
32
+ }
33
+
34
+ while True:
35
+ response = requests.get(operation_location, headers=headers)
36
+ if response.status_code == 200: # HTTP 200 indicates success
37
+ read_result = response.json()
38
+ status = read_result['status']
39
+ if status == 'succeeded':
40
+ break
41
+ elif status in ['failed', 'notStarted', 'running']:
42
+ time.sleep(1) # Wait before polling again
43
+ else:
44
+ raise Exception(f"Unexpected status: {status}")
45
+ else:
46
+ raise Exception(f"Unexpected response status: {response.status_code}")
47
+
48
+ return read_result
49
+
50
+ def process_image(image_path, subscription_key, endpoint):
51
+ operation_location = read_image_from_stream(image_path, subscription_key, endpoint)
52
+ operation_id = operation_location.split("/")[-1]
53
+ operation_location = f"{endpoint}/vision/v3.2/read/analyzeResults/{operation_id}"
54
+ read_result = get_read_result(operation_location, subscription_key)
55
+ if read_result['status'] == 'succeeded':
56
+ output = []
57
+ for text_result in read_result['analyzeResult']['readResults']:
58
+ for line in text_result['lines']:
59
+ output.append(line['text'])
60
+ return " ".join(output).replace("\n", " ") # Join lines and replace newlines with spaces
61
+ else:
62
+ return "Processing failed or did not succeed."
63
 
64
  def get_answer(image: io.BytesIO, question: str):
65
  filename = image.name
 
109
  return hug.output.get("data", [None])[0]
110
 
111
  def ocr(image: io.BytesIO) -> str:
112
+ return process_image(image, os.getenv('AZKEY'), os.getenv('AZURL'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
  app = Flask(__name__)
115
 
 
163
  headers = dict(request.headers)
164
  if not headers.get("KEY") != os.getenv("KEY"):
165
  return jsonify({"status" : False, "msg" : "Invalid API Key"}), 404
166
+ answer = ocr(file_content)
167
+ return jsonify({"status" : True, "data" : answer})
168
 
169
  @app.route('/check', methods=['POST', 'GET'])
170
  def check_f():