Dahee_AI / utils.py
resulmamiyev's picture
Upload folder using huggingface_hub
4ed309e verified
from google.cloud import translate_v3 as translate
from translation import TOPICS, DIFFICULTY
# -----------------------------
# Helper Function: Translate Text
# -----------------------------
def translate_text(text, project_id, target_lang="az", source_lang=None):
"""Translate text to the target language using Google Translate API."""
if not text.strip():
return text # Return empty text unchanged
try:
translate_client = translate.TranslationServiceClient()
parent = f"projects/{project_id}/locations/global"
response = translate_client.translate_text(
contents=[text],
target_language_code=target_lang,
parent=parent,
mime_type="text/plain",
source_language_code=source_lang,
)
return response.translations[0].translated_text
except Exception as e:
return f"Translation Error: {str(e)}"
# -----------------------------
# Helper Function: Get Topics List
# -----------------------------
def get_topic_names(lang):
return [topic[lang] for topic in TOPICS]
# -----------------------------
# Helper Function: Get Subtopics List
# -----------------------------
def get_subtopics(selected_topic, lang):
if not selected_topic:
return []
# Reverse map to find subtopics of selected topic
subtopics = next(
(topic["subtopics"] for topic in TOPICS if topic[lang] == selected_topic), None
)
return [subtopic[lang] for subtopic in subtopics]
# -----------------------------
# Helper Function: Get English Topic and Subtopic Names
# -----------------------------
def get_eng_names(selected_topic, selected_subtopic, difficulty, lang):
if not selected_topic or not selected_subtopic:
return None, None
# Reverse map to find English names of selected topic and subtopic
topic_en, subtopics = next(
(
(topic["en"], topic["subtopics"])
for topic in TOPICS
if topic[lang] == selected_topic
),
None,
)
subtopic_en = next(
(
subtopic["en"]
for subtopic in subtopics
if subtopic[lang] == selected_subtopic
),
None,
)
difficulty_en = next(
(
difficulty["en"]
for difficulty in DIFFICULTY
if difficulty[lang] == difficulty
),
None,
)
return topic_en, subtopic_en, difficulty_en