Skip to content

Commit

Permalink
fix: image generation response structure
Browse files Browse the repository at this point in the history
ref #34
  • Loading branch information
HanaokaYuzu committed Sep 7, 2024
1 parent 9a06a0e commit 303df62
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 14 deletions.
31 changes: 18 additions & 13 deletions src/gemini_webapi/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,12 +345,14 @@ async def generate_content(
)
else:
try:
response_json = json.loads(response.text.split("\n")[2])

# Plain request
body = json.loads(json.loads(response.text.split("\n")[2])[0][2])
body = json.loads(response_json[0][2])

if not body[4]:
# Request with Gemini extensions enabled
body = json.loads(json.loads(response.text.split("\n")[2])[4][2])
body = json.loads(response_json[4][2])

if not body[4]:
raise Exception
Expand All @@ -363,9 +365,11 @@ async def generate_content(

try:
candidates = []
for candidate in body[4]:
for i, candidate in enumerate(body[4]):
text = candidate[1][0]
if re.match(r"^http://googleusercontent.com/card_content/\d+$", text):
if re.match(
r"^http://googleusercontent.com/card_content/\d+$", text
):
text = candidate[22] and candidate[22][0] or text

web_images = (
Expand All @@ -383,11 +387,11 @@ async def generate_content(
or []
)

generated_images = (
candidate[12]
and candidate[12][7]
and candidate[12][7][0]
and [
generated_images = []
if candidate[12] and candidate[12][7] and candidate[12][7][0]:
image_generation_body = json.loads(response_json[1][2])
image_generation_candidate = image_generation_body[4][i]
generated_images = [
GeneratedImage(
url=image[0][3][3],
title=f"[Generated Image {image[3][6]}]",
Expand All @@ -397,10 +401,10 @@ async def generate_content(
proxies=self.proxies,
cookies=self.cookies,
)
for i, image in enumerate(candidate[12][7][0])
]
or []
)
for i, image in enumerate(
image_generation_candidate[12][7][0]
)
] or []

candidates.append(
Candidate(
Expand All @@ -417,6 +421,7 @@ async def generate_content(

output = ModelOutput(metadata=body[1], candidates=candidates)
except (TypeError, IndexError):
logger.debug(f"Invalid response: {response.text}")
raise APIError(
"Failed to parse response body. Data structure is invalid."
)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_save_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ async def asyncSetUp(self):

async def test_save_web_image(self):
response = await self.geminiclient.generate_content(
"Send me 10 pictures of random subjects"
"Show me some pictures of random subjects"
)
self.assertTrue(response.images)
for i, image in enumerate(response.images):
Expand Down

0 comments on commit 303df62

Please sign in to comment.