Skip to content
This repository has been archived by the owner on Apr 24, 2024. It is now read-only.

Commit

Permalink
refactor: style black
Browse files Browse the repository at this point in the history
  • Loading branch information
dsdanielpark committed Sep 28, 2023
1 parent 104905d commit c325adc
Show file tree
Hide file tree
Showing 14 changed files with 11,274 additions and 111 deletions.
2 changes: 1 addition & 1 deletion bardapi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
SEPARATOR_LINE,
USER_PROMPT,
IMG_UPLOAD_HEADERS,
Tool
Tool,
)
from bardapi.utils import (
extract_links,
Expand Down
116 changes: 69 additions & 47 deletions bardapi/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@
SESSION_HEADERS,
REPLIT_SUPPORT_PROGRAM_LANGUAGES,
TEXT_GENERATION_WEB_SERVER_PARAM,
Tool
Tool,
)
from bardapi.utils import (
build_input_replit_data_struct,
build_export_data_structure,
build_bard_answer,
upload_image,
extract_bard_cookie,
build_input_text_struct
build_input_text_struct,
)


Expand All @@ -38,16 +38,16 @@ class Bard:
"""

def __init__(
self,
token: Optional[str] = None,
timeout: int = 20,
proxies: Optional[dict] = None,
session: Optional[requests.Session] = None,
conversation_id: Optional[str] = None,
google_translator_api_key: Optional[str] = None,
language: Optional[str] = None,
run_code: bool = False,
token_from_browser: bool = False,
self,
token: Optional[str] = None,
timeout: int = 20,
proxies: Optional[dict] = None,
session: Optional[requests.Session] = None,
conversation_id: Optional[str] = None,
google_translator_api_key: Optional[str] = None,
language: Optional[str] = None,
run_code: bool = False,
token_from_browser: bool = False,
):
"""
Initialize the Bard instance.
Expand Down Expand Up @@ -152,9 +152,13 @@ def _get_snim0e(self) -> str:
)
return snim0e.group(1)

def ask(self, text: str,
image: Optional[bytes] = None, image_name: Optional[str] = None,
tool: Optional[Tool] = None) -> BardResult:
def ask(
self,
text: str,
image: Optional[bytes] = None,
image_name: Optional[str] = None,
tool: Optional[Tool] = None,
) -> BardResult:

if image is not None:
image_url = upload_image(image)
Expand All @@ -163,9 +167,13 @@ def ask(self, text: str,

# Make post data structure and insert prompt
input_text_struct = build_input_text_struct(
text, self.conversation_id, self.response_id, self.choice_id,
image_url, image_name,
tools=[tool.value] if tool is not None else None
text,
self.conversation_id,
self.response_id,
self.choice_id,
image_url,
image_name,
tools=[tool.value] if tool is not None else None,
)

# Get response
Expand All @@ -185,18 +193,22 @@ def ask(self, text: str,
)

if resp.status_code != 200:
raise Exception(f"Response status code is not 200. Response Status is {resp.status_code}")
raise Exception(
f"Response status code is not 200. Response Status is {resp.status_code}"
)

lines = [line for line in resp.content.splitlines() if line.startswith(b'[["wrb.fr')]
lines = [
line for line in resp.content.splitlines() if line.startswith(b'[["wrb.fr')
]
jsons = [json.loads(json.loads(line)[0][2]) for line in lines]
# Post-processing of response
resp_json = jsons[-1]

if not resp_json:
raise {
"content": f"Response Error: {resp.content}. "
f"\nUnable to get response."
f"\nPlease double-check the cookie values and verify your network environment or google account."
f"\nUnable to get response."
f"\nPlease double-check the cookie values and verify your network environment or google account."
}

res = BardResult(resp_json)
Expand All @@ -207,15 +219,19 @@ def ask(self, text: str,
self.conversation_id, self.response_id, self.choice_id = (
res.conversation_id,
res.response_id,
res.drafts[0].id
res.drafts[0].id,
)
self._reqid += 100000

return res

def get_answer(self, input_text: str,
image: Optional[bytes] = None, image_name: Optional[str] = None,
tool: Optional[Tool] = None) -> dict:
def get_answer(
self,
input_text: str,
image: Optional[bytes] = None,
image_name: Optional[str] = None,
tool: Optional[Tool] = None,
) -> dict:
"""
Get an answer from the Bard API for the given input text.
Expand Down Expand Up @@ -264,16 +280,16 @@ def get_answer(self, input_text: str,

# [Optional] Language translation
if (
self.language is not None
and self.language not in ALLOWED_LANGUAGES
and self.google_translator_api_key is None
self.language is not None
and self.language not in ALLOWED_LANGUAGES
and self.google_translator_api_key is None
):
translator_to_eng = GoogleTranslator(source="auto", target="en")
input_text = translator_to_eng.translate(input_text)
elif (
self.language is not None
and self.language not in ALLOWED_LANGUAGES
and self.google_translator_api_key is not None
self.language is not None
and self.language not in ALLOWED_LANGUAGES
and self.google_translator_api_key is not None
):
input_text = google_official_translator.translate(
input_text, target_language="en"
Expand All @@ -286,9 +302,13 @@ def get_answer(self, input_text: str,

# Make post data structure and insert prompt
input_text_struct = build_input_text_struct(
input_text, self.conversation_id, self.response_id, self.choice_id,
image_url, image_name,
tools=[tool.value] if tool is not None else None
input_text,
self.conversation_id,
self.response_id,
self.choice_id,
image_url,
image_name,
tools=[tool.value] if tool is not None else None,
)

data = {
Expand All @@ -311,8 +331,8 @@ def get_answer(self, input_text: str,
if not resp_dict:
return {
"content": f"Response Error: {resp.content}. "
f"\nUnable to get response."
f"\nPlease double-check the cookie values and verify your network environment or google account."
f"\nUnable to get response."
f"\nPlease double-check the cookie values and verify your network environment or google account."
}
resp_json = json.loads(resp_dict)
if resp_json[4] is None:
Expand Down Expand Up @@ -356,12 +376,14 @@ def translator_func(text):
program_lang = (
parsed_answer[4][0][1][0].split("```")[1].split("\n")[0].strip()
)
code = parsed_answer[4][0][1][0].split("```")[1][len(program_lang):]
code = parsed_answer[4][0][1][0].split("```")[1][len(program_lang) :]
except Exception:
program_lang, code = None, None

# Returns dictionary object
bard_answer = build_bard_answer(parsed_answer, images, program_lang, code, resp.status_code)
bard_answer = build_bard_answer(
parsed_answer, images, program_lang, code, resp.status_code
)

# Update params
self.conversation_id, self.response_id, self.choice_id = (
Expand Down Expand Up @@ -432,8 +454,8 @@ def speech(self, input_text: str, lang: str = "en-US") -> dict:
if not resp_dict:
return {
"content": f"Response Error: {resp.content}. "
f"\nUnable to get response."
f"\nPlease double-check the cookie values and verify your network environment or google account."
f"\nUnable to get response."
f"\nPlease double-check the cookie values and verify your network environment or google account."
}
resp_json = json.loads(resp_dict)
audio_b64 = resp_json[0]
Expand Down Expand Up @@ -498,7 +520,7 @@ def export_conversation(self, bard_answer, title: str = "") -> dict:
return {"url": url, "status_code": resp.status_code}

def ask_about_image(
self, input_text: str, image: bytes, image_name: str, lang: Optional[str] = None
self, input_text: str, image: bytes, image_name: str, lang: Optional[str] = None
) -> dict:
"""
Send Bard image along with question and get answer
Expand Down Expand Up @@ -534,11 +556,11 @@ def ask_about_image(
return self.get_answer(input_text, image, image_name)

def export_replit(
self,
code: str,
program_lang: Optional[str] = None,
filename: Optional[str] = None,
**kwargs,
self,
code: str,
program_lang: Optional[str] = None,
filename: Optional[str] = None,
**kwargs,
) -> dict:
"""
Get export URL to repl.it from code
Expand Down
3 changes: 1 addition & 2 deletions bardapi/core_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
build_bard_answer,
upload_image,
extract_bard_cookie,
build_input_text_struct
build_input_text_struct,
)


Expand Down Expand Up @@ -84,7 +84,6 @@ def __init__(
from deep_translator import GoogleTranslator
from google.cloud import translate_v2 as translate


def _get_token(self, token_from_browser: bool) -> dict:
"""
Get the Bard API token either from the provided token or from the browser cookie.
Expand Down
52 changes: 43 additions & 9 deletions bardapi/models/draft.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,20 @@ def text(self) -> str:
@property
def citations(self) -> list[DraftCitation]:
text = self.text
return [DraftCitation(c, text) for c in self._input_list[2][0]] if self._input_list[2] else []
return (
[DraftCitation(c, text) for c in self._input_list[2][0]]
if self._input_list[2]
else []
)

@property
def images(self) -> list[BardImageContent]:
# also in self._attachments[1]
return [BardImageContent(img) for img in self._input_list[4]] if self._input_list[4] else []
return (
[BardImageContent(img) for img in self._input_list[4]]
if self._input_list[4]
else []
)

@property
def language(self) -> str:
Expand All @@ -44,19 +52,31 @@ def _attachments(self) -> Optional[list]:
def map_content(self) -> list[BardMapContent]:
if not self._attachments:
return []
return [BardMapContent(a) for a in self._attachments[3]] if self._attachments[3] else []
return (
[BardMapContent(a) for a in self._attachments[3]]
if self._attachments[3]
else []
)

@property
def gdocs(self) -> list[BardGDocsContent]:
if not self._attachments:
return []
return [BardGDocsContent(a) for a in self._attachments[12][0][2]] if self._attachments[12] else []
return (
[BardGDocsContent(a) for a in self._attachments[12][0][2]]
if self._attachments[12]
else []
)

@property
def youtube(self) -> list[BardYoutubeContent]:
if not self._attachments:
return []
return [BardYoutubeContent(a) for a in self._attachments[4]] if self._attachments[4] else []
return (
[BardYoutubeContent(a) for a in self._attachments[4]]
if self._attachments[4]
else []
)

@property
def python_code(self) -> list[CodeContent]:
Expand All @@ -67,26 +87,40 @@ def python_code(self) -> list[CodeContent]:
# The code snippet is the same for all drafts!
if not self._attachments:
return []
return [CodeContent(a) for a in self._attachments[5]] if self._attachments[5] and self._attachments[5][0][3] else []
return (
[CodeContent(a) for a in self._attachments[5]]
if self._attachments[5] and self._attachments[5][0][3]
else []
)

@property
def links(self) -> list[BardLink]:
if not self._attachments:
return []
return [BardLink(a) for a in self._attachments[8]] if self._attachments[8] else []
return (
[BardLink(a) for a in self._attachments[8]] if self._attachments[8] else []
)

@property
def flights(self) -> list[BardFlightContent]:
if not self._attachments:
return []
return [BardFlightContent(a) for a in self._attachments[16]] if self._attachments[16] else []
return (
[BardFlightContent(a) for a in self._attachments[16]]
if self._attachments[16]
else []
)

@property
def tool_disclaimers(self) -> list[BardToolDeclaimer]:
if not self._attachments or len(self._attachments) < 23:
return []

return [BardToolDeclaimer(a) for a in self._attachments[22]] if self._attachments[22] else []
return (
[BardToolDeclaimer(a) for a in self._attachments[22]]
if self._attachments[22]
else []
)

@property
def user_content(self) -> dict[str, UserContent]:
Expand Down
10 changes: 8 additions & 2 deletions bardapi/models/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ def factuality_queries(self) -> Optional[list]:

@property
def drafts(self) -> list[BardDraft]:
return [BardDraft(c) for c in self._input_list[4]] if self._input_list[4] else []
return (
[BardDraft(c) for c in self._input_list[4]] if self._input_list[4] else []
)

@property
def location(self) -> BardUserLocation:
Expand All @@ -68,4 +70,8 @@ def topic(self) -> Optional[str]:
def tools_applied(self) -> list[BardTool]:
if len(self._input_list) < 12:
return []
return [BardTool(tool) for tool in self._input_list[11]] if self._input_list[11] else []
return (
[BardTool(tool) for tool in self._input_list[11]]
if self._input_list[11]
else []
)
Loading

0 comments on commit c325adc

Please sign in to comment.