Spaces:
Sleeping
Sleeping
File size: 7,482 Bytes
8dd0141 693b3d1 8dd0141 ea1eaf7 |
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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 |
import os
import re
import json
import time
import requests
import anthropic
import google.auth
import gradio as gr
from uuid import uuid4
from dotenv import load_dotenv
from google.auth.transport.requests import Request
# Gemini
def get_google_token():
credentials, project = google.auth.load_credentials_from_dict(
json.loads(os.environ.get('GCP_FINETUNE_KEY')),
scopes=[
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/generative-language.tuning",
],
)
request = Request()
credentials.refresh(request)
access_token = credentials.token
return access_token
def dubpro_english_to_hindi(text):
API_URL = os.environ.get("GEMINI_FINETUNED_ENG_HINDI_API")
BEARER_TOKEN = get_google_token()
headers = {
"Authorization": f"Bearer {BEARER_TOKEN}",
"Content-Type": "application/json",
}
payload = {
"contents": [
{
"parts": [{"text": f"text: {text}"}],
"role": "user",
}
],
"generationConfig": {
"maxOutputTokens": 8192,
"temperature": 0.85,
},
"safetySettings": [
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
],
}
result = requests.post(
url=API_URL,
headers=headers,
json=payload
)
response = result.json()
response_content = response['candidates'][0]['content']['parts'][0]['text'].replace("translated:", "").strip()
return response_content
def gemini_english_to_hindi(text):
API_URL = os.environ.get("GEMINI_FINETUNED_ENG_HINDI_API")
BEARER_TOKEN = get_google_token()
headers = {
"Authorization": f"Bearer {BEARER_TOKEN}",
"Content-Type": "application/json",
}
payload = {
"contents": [
{
"parts": [{"text": f"Translate the following text to Hindi: `{text}` Output: "}],
"role": "user",
}
],
"generationConfig": {
"maxOutputTokens": 8192,
"temperature": 0.85,
},
"safetySettings": [
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
],
}
result = requests.post(
url=API_URL,
headers=headers,
json=payload
)
response = result.json()
response_content = response['candidates'][0]['content']['parts'][0]['text'].replace("translated:", "").replace("`", "").strip()
return response_content
# GPT models
def clean(result):
text = result["choices"][0]['message']["content"]
text = re.sub(r"\(.*?\)|\[.*?\]","", text)
text = text.strip("'").replace('"', "")
if "\n" in text.strip("\n"):
text = text.split("\n")[-1]
return text
def openai_english_to_hindi(text, model):
prompt = f"Translate the following English text into Hindi such that the meaning in unchanged. Return only the translated text: `{text}`. Output: "
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {os.environ.get('OPENAI_API_KEY')}"
}
messages = [
{"role": "system", "content": f"You are a language translation assistant."},
{"role": "user", "content": prompt}
]
resp = None
while resp is None:
resp = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json={
"model": model,
"messages": messages
})
if resp.status_code != 200:
print(resp.text)
time.sleep(0.5)
response_json = resp.json()
result_text = clean(response_json)
return result_text
# Azure translate
def azure_english_to_hindi(text):
headers = {
"Ocp-Apim-Subscription-Key": os.environ.get("AZURE_TRANSLATE_KEY"),
"Ocp-Apim-Subscription-Region": os.environ.get("AZURE_TRANSLATE_REGION"),
"Content-type": "application/json",
"X-ClientTraceId": str(uuid4()),
}
ENDPOINT = "https://api.cognitive.microsofttranslator.com/translate"
params = {
"api-version": "3.0",
"from": "en-US",
"to": "hi-IN",
}
texts = [{"text": text}]
request = requests.post(ENDPOINT, headers=headers, params=params, json=texts)
response = request.json()
return response[0]["translations"][0]["text"]
# Anthopic Claude 3 Haiku
def claude_english_to_hindi(text):
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-3-haiku-20240307",
max_tokens=1000,
temperature=0.8,
system="You are an expert language translator.",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": f"Translate the following English text into Hindi such that the meaning in unchanged. Return only the translated text: `{text}`. Output: "
}
]
}
]
)
return message.content[0].text
def render_translations(text):
dubpro = dubpro_english_to_hindi(text)
azure = azure_english_to_hindi(text)
gemini = gemini_english_to_hindi(text)
gpt_4 = openai_english_to_hindi(text, model="gpt-4")
claude_haiku = claude_english_to_hindi(text)
return gr.update(value=gpt_4), gr.update(value=dubpro), gr.update(value=gemini), gr.update(value=claude_haiku), gr.update(value=azure)
with gr.Blocks(title="English to Hindi Translation Tools", theme="gradio/monochrome") as demo:
gr.Markdown("# English to Hindi Translation Tools")
input_textbox = gr.Textbox(label="Input Text", info="Text to translate", value="When you did it, you must have attended your classes well or you must have done your daily revision. Now you feel scared.")
submit = gr.Button(label="Submit")
with gr.Row():
gr.Label(value="Dubpro's Model", scale=1)
dubpro_model_textbox = gr.Textbox(label="Translated Text", scale=2, interactive=False)
with gr.Row():
gr.Label(value="GPT 4", scale=1)
gpt_4_textbox = gr.Textbox(label="Translated Text", scale=2, interactive=False)
with gr.Row():
gr.Label(value="Google Gemini", scale=1)
google_textbox = gr.Textbox(label="Translated Text", scale=2, interactive=False)
with gr.Row():
gr.Label(value="Anthropic Claude 3", scale=1)
claude_textbox = gr.Textbox(label="Translated Text", scale=2, interactive=False)
with gr.Row():
gr.Label(value="Azure Translate", scale=1)
azure_textbox = gr.Textbox(label="Translated Text", scale=2, interactive=False)
submit.click(render_translations, input_textbox, [gpt_4_textbox, dubpro_model_textbox, google_textbox, claude_textbox, azure_textbox])
if __name__=="__main__":
demo.launch(auth=(os.environ["USERNAME"], os.environ["PASSWORD"])) |