forked from unconv/gpt4v-browsing
-
Notifications
You must be signed in to change notification settings - Fork 123
/
vison_scraper.py
85 lines (69 loc) · 2.22 KB
/
vison_scraper.py
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
from openai import OpenAI
import subprocess
import base64
import os
from dotenv import load_dotenv
load_dotenv()
model = OpenAI()
model.timeout = 30
def image_b64(image):
with open(image, "rb") as f:
return base64.b64encode(f.read()).decode()
def url2screenshot(url):
print(f"Crawling {url}")
if os.path.exists("screenshot.jpg"):
os.remove("screenshot.jpg")
result = subprocess.run(
["node", "screenshot.js", url],
capture_output=True,
text=True
)
exitcode = result.returncode
output = result.stdout
if not os.path.exists("screenshot.jpg"):
print("ERROR")
return "Failed to scrape the website"
b64_image = image_b64("screenshot.jpg")
return b64_image
def visionExtract(b64_image, prompt):
response = model.chat.completions.create(
model="gpt-4-vision-preview",
messages=[
{
"role": "system",
"content": "You a web scraper, your job is to extract information based on a screenshot of a website & user's instruction",
}
] + [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{b64_image}",
},
{
"type": "text",
"text": prompt,
}
]
}
],
max_tokens=1024,
)
message = response.choices[0].message
message_text = message.content
if "ANSWER_NOT_FOUND" in message_text:
print("ERROR: Answer not found")
return "I was unable to find the answer on that website. Please pick another one"
else:
print(f"GPT: {message_text}")
return message_text
def visionCrawl(url, prompt):
b64_image = url2screenshot(url)
print("Image captured")
if b64_image == "Failed to scrape the website":
return "I was unable to crawl that site. Please pick a different one."
else:
return visionExtract(b64_image, prompt)
response = visionCrawl("https://relevanceai.com/pricing", "Extract the pricing info")
print(response)