Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Translate functionality #2

Open
wants to merge 2 commits into
base: f24
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions .github/workflows/f24_translator-syntax-squad.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy
# More GitHub Actions for Azure: https://github.com/Azure/actions
# More info on Python, GitHub Actions, and Azure App Service: https://aka.ms/python-webapps-actions

name: Build and deploy Python app to Azure Web App - translator-syntax-squad

on:
push:
branches:
- f24
workflow_dispatch:

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4

- name: Set up Python version
uses: actions/setup-python@v1
with:
python-version: '3.10'

- name: Create and start virtual environment
run: |
python -m venv venv
source venv/bin/activate

- name: Install dependencies
run: pip install -r requirements.txt

# Optional: Add step to run tests here (PyTest, Django test suites, etc.)
- name: Zip artifact for deployment
run: zip release.zip ./* -r

- name: Upload artifact for deployment jobs
uses: actions/upload-artifact@v3
with:
name: python-app
path: |
release.zip
!venv/

deploy:
runs-on: ubuntu-latest
needs: build
environment:
name: 'Production'
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}

steps:
- name: Download artifact from build job
uses: actions/download-artifact@v3
with:
name: python-app

- name: Unzip artifact for deployment
run: unzip release.zip

- name: 'Deploy to Azure Web App'
uses: azure/webapps-deploy@v2
id: deploy-to-webapp
with:
app-name: 'translator-syntax-squad'
slot-name: 'Production'
publish-profile: ${{ secrets.AZUREAPPSERVICE_PUBLISHPROFILE_4FFDAD9CBC40474FBAD90E3F1361DB55 }}
128 changes: 94 additions & 34 deletions src/translator.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,94 @@
def translate_content(content: str) -> tuple[bool, str]:
if content == "这是一条中文消息":
return False, "This is a Chinese message"
if content == "Ceci est un message en français":
return False, "This is a French message"
if content == "Esta es un mensaje en español":
return False, "This is a Spanish message"
if content == "Esta é uma mensagem em português":
return False, "This is a Portuguese message"
if content == "これは日本語のメッセージです":
return False, "This is a Japanese message"
if content == "이것은 한국어 메시지입니다":
return False, "This is a Korean message"
if content == "Dies ist eine Nachricht auf Deutsch":
return False, "This is a German message"
if content == "Questo è un messaggio in italiano":
return False, "This is an Italian message"
if content == "Это сообщение на русском":
return False, "This is a Russian message"
if content == "هذه رسالة باللغة العربية":
return False, "This is an Arabic message"
if content == "यह हिंदी में संदेश है":
return False, "This is a Hindi message"
if content == "นี่คือข้อความภาษาไทย":
return False, "This is a Thai message"
if content == "Bu bir Türkçe mesajdır":
return False, "This is a Turkish message"
if content == "Đây là một tin nhắn bằng tiếng Việt":
return False, "This is a Vietnamese message"
if content == "Esto es un mensaje en catalán":
return False, "This is a Catalan message"
if content == "This is an English message":
return True, "This is an English message"
return True, content
import openai
import time

# Use your actual API Key and Endpoint
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.api_base = "https://barbol.openai.azure.com/" # Your endpoint base URL
openai.api_type = "azure"
openai.api_version = "2024-08-01-preview"
deployment_name = "barbol-gpt-4"

def get_translation(post: str) -> str:
# Define the translation prompt in a conversational format
messages = [
{"role": "system", "content": "You are a helpful assistant that translates text to English."},
{"role": "user", "content": f"Translate the following text to English: {post}"}
]

wait_time = 5

while True:
try:
# Use the ChatCompletion endpoint with the gpt-4 model
response = openai.ChatCompletion.create(
engine="barbol-gpt-4",
messages=messages,
max_tokens=100,
temperature=0.2,
)

# Extract and return the translation from the response
translation = response.choices[0].message['content'].strip()
return translation

except openai.error.RateLimitError:
print(f"Rate limit exceeded. Waiting for {wait_time} seconds before retrying...")
time.sleep(wait_time)
except Exception as e:
print("Error in translation:", e)
return ""

def get_language(post: str) -> str:
# Define the prompt to determine the exact language of the text
messages = [
{"role": "system", "content": "You are a helpful assistant that detects the language of the given text and returns the name of the language, starting with a capital letter and a one word response(eg. English, Spanish, Arabic, Russian)."},
{"role": "user", "content": f"Identify the language of the following text: {post}"}
]

wait_time = 5

while True:
try:
# Use the ChatCompletion endpoint to determine language
response = openai.ChatCompletion.create(
engine="barbol-gpt-4",
messages=messages,
max_tokens=10,
temperature=0.0,
)

# Extract and return the detected language from the response
detected_language = response.choices[0].message['content'].strip()
return detected_language

except openai.error.RateLimitError:
print(f"Rate limit exceeded. Waiting for {wait_time} seconds before retrying...")
time.sleep(wait_time)
except Exception as e:
print("Error in language detection:", e)
return ""

def translate_content(post: str) -> str:
"""
Detects the language of the text and translates it into English if it's not already in English.
"""
try:
# Step 1: Detect the language of the text
detected_language = get_language(post)
print(f"Detected Language: {detected_language}")

# Step 2: Translate if the text is not in English
if detected_language != "English":
print(f"Translating text from {detected_language} to English...")
return get_translation(post)
else:
print("Text is already in English. No translation needed.")
return post

except Exception as e:
print("Error in translate_content:", e)
return ""