mirror of
https://github.com/yihong0618/bilingual_book_maker.git
synced 2025-06-05 19:15:34 +00:00
parent
85112cc0fc
commit
70d2535f84
@ -1,6 +1,7 @@
|
|||||||
import re
|
import re
|
||||||
import requests
|
import time
|
||||||
from rich import print
|
from rich import print
|
||||||
|
from anthropic import Anthropic
|
||||||
|
|
||||||
from .base_translator import Base
|
from .base_translator import Base
|
||||||
|
|
||||||
@ -16,23 +17,9 @@ class Claude(Base):
|
|||||||
**kwargs,
|
**kwargs,
|
||||||
) -> None:
|
) -> None:
|
||||||
super().__init__(key, language)
|
super().__init__(key, language)
|
||||||
self.api_url = (
|
self.api_url = f"{api_base}" if api_base else "https://api.anthropic.com"
|
||||||
f"{api_base}v1/complete"
|
self.client = Anthropic(base_url=api_base, api_key=key, timeout=20)
|
||||||
if api_base
|
|
||||||
else "https://api.anthropic.com/v1/complete"
|
|
||||||
)
|
|
||||||
self.headers = {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"x-api-key": key,
|
|
||||||
}
|
|
||||||
self.data = {
|
|
||||||
"prompt": "",
|
|
||||||
"model": "claude-v1.3",
|
|
||||||
"max_tokens_to_sample": 1024,
|
|
||||||
"temperature": temperature,
|
|
||||||
"stop_sequences": ["\n\nHuman:"],
|
|
||||||
}
|
|
||||||
self.session = requests.session()
|
|
||||||
self.language = language
|
self.language = language
|
||||||
self.prompt_template = (
|
self.prompt_template = (
|
||||||
prompt_template
|
prompt_template
|
||||||
@ -45,14 +32,19 @@ class Claude(Base):
|
|||||||
def translate(self, text):
|
def translate(self, text):
|
||||||
print(text)
|
print(text)
|
||||||
self.rotate_key()
|
self.rotate_key()
|
||||||
self.data["prompt"] = self.prompt_template.format(
|
prompt = self.prompt_template.format(
|
||||||
text=text,
|
text=text,
|
||||||
language=self.language,
|
language=self.language,
|
||||||
)
|
)
|
||||||
r = self.session.post(self.api_url, headers=self.headers, json=self.data)
|
message = [{"role": "user", "content": prompt}]
|
||||||
if not r.ok:
|
r = self.client.messages.create(
|
||||||
return text
|
max_tokens=4096,
|
||||||
t_text = r.json().get("completion").strip()
|
messages=message,
|
||||||
|
model="claude-3-haiku-20240307", # default it for now
|
||||||
|
)
|
||||||
|
t_text = r.content[0].text
|
||||||
|
# api limit rate and spider rule
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
print("[bold green]" + re.sub("\n{3,}", "\n\n", t_text) + "[/bold green]")
|
print("[bold green]" + re.sub("\n{3,}", "\n\n", t_text) + "[/bold green]")
|
||||||
return t_text
|
return t_text
|
||||||
|
Loading…
x
Reference in New Issue
Block a user