Repository navigation
Expand file tree
/
Copy pathimage_processor.py
More file actions
85 lines (68 loc) · 2.21 KB
/
Copy pathimage_processor.py
File metadata and controls
85 lines (68 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import io
import json
import os
import imagehash
from PIL import Image
import converse
def generate_report(texts, image_dir, offset=0, limit=20):
assert offset >= 0
content = [{"text": texts[0]}]
final_response = ""
files = os.listdir(image_dir)
files.sort()
# First remove duplicates using perceptual hashing
unique_files = []
previous_hash = None
hash_threshold = 0.5
for image_file in files:
image_path = os.path.join(image_dir, image_file)
with Image.open(image_path) as img:
img_hash = imagehash.phash(img)
if previous_hash is not None and abs(img_hash - previous_hash) <= hash_threshold:
continue
previous_hash = img_hash
unique_files.append(image_file)
unique_files = unique_files[offset:]
unique_files = unique_files[limit*-1:]
for image_file in unique_files:
format = image_file.split(".")[-1]
if format == "jpg":
format = "jpeg"
image_path = os.path.join(image_dir, image_file)
with Image.open(image_path) as img:
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format=format)
img_byte_arr.seek(0)
image_bytes = img_byte_arr.getvalue()
content.append({
"image": {
"format": format,
"source": {
"bytes": image_bytes,
}
}
})
message = [{
"role": "user",
"content": content
}]
for i in range(len(texts)):
response_message = converse.converse(message, reasoning=32000)
message.append(response_message)
print(json.dumps(response_message, indent=4, default=str))
print("\n\n")
print("-" * 50)
final_response = response_message['content'][1]['text']
print(final_response)
print("-" * 50)
print("\n\n")
if i < len(texts) - 1:
message.append({
"role": "user",
"content": [
{
"text": texts[i + 1]
}
]
})
return final_response