5m4ck3r commited on
Commit
d5f755c
1 Parent(s): c153d6e

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +24 -0
main.py CHANGED
@@ -8,6 +8,29 @@ 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
 
@@ -109,6 +132,7 @@ def valuate_qna(p: str, r: str) -> str:
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__)
 
8
  from mimetypes import guess_type
9
  import requests
10
  import time
11
+ from PIL import Image
12
+
13
+ def compress_image(input_stream: io.BytesIO, max_size_mb=4) -> io.BytesIO:
14
+ with Image.open(input_stream) as img:
15
+ img = Image.new(img.mode, img.size)
16
+ img.paste(img)
17
+ quality = 95
18
+ step = 5
19
+ output_stream = io.BytesIO()
20
+ while True:
21
+ output_stream.seek(0)
22
+ img.save(output_stream, format="JPEG", quality=quality)
23
+ output_stream_size_mb = len(output_stream.getvalue()) / (1024 * 1024)
24
+
25
+ if output_stream_size_mb <= max_size_mb:
26
+ output_stream.seek(0)
27
+ print(f"Image compressed to {output_stream_size_mb:.2f} MB")
28
+ return output_stream
29
+ quality -= step
30
+ if quality < step:
31
+ print("Cannot compress the image to the desired size.")
32
+ output_stream.seek(0)
33
+ return output_stream
34
 
35
  def read_image_from_stream(image_data, subscription_key, endpoint):
36
 
 
132
  return hug.output.get("data", [None])[0]
133
 
134
  def ocr(image: io.BytesIO) -> str:
135
+ image = compress_image(image) # Compress the image
136
  return process_image(image, os.getenv('AZKEY'), os.getenv('AZURL'))
137
 
138
  app = Flask(__name__)