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

ID now returned with stt endpoint #39

Merged
merged 1 commit into from
Jul 1, 2024
Merged
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ key.json
# Private JSON files
service_account_key.json
credentials.json
service-account-file.json

# Audio files
*.wav
Expand Down
7 changes: 6 additions & 1 deletion app/crud/audio_transcription.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,16 @@ def create_audio_transcription(


async def get_audio_transcriptions(
db: Session, username: str
db: Session, username: str, params
) -> List[AudioTranscription]:
order_column = getattr(AudioTranscription, params.order_by)
if params.descending:
order_column = order_column.desc()

return (
db.query(AudioTranscription)
.filter(AudioTranscription.username == username)
.order_by(order_column)
.all()
)

Expand Down
16 changes: 11 additions & 5 deletions app/inference_services/user_preference.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import logging
import os

import firebase_admin
from firebase_admin import credentials, firestore
import logging


logging.basicConfig(level=logging.INFO)

Expand Down Expand Up @@ -63,7 +62,15 @@ def save_user_preference(user_id, source_language, target_language):
# }
# )

def save_translation(user_id, original_text, translated_text, source_language, target_language, message_id):

def save_translation(
user_id,
original_text,
translated_text,
source_language,
target_language,
message_id,
):
"""
Save translation details to Firestore

Expand Down Expand Up @@ -108,7 +115,7 @@ def update_feedback(message_id, feedback):
try:
translations_ref = db.collection("whatsapp_translations")
query = translations_ref.where("message_id", "==", message_id).stream()

for doc in query:
doc_ref = translations_ref.document(doc.id)
doc_ref.update({"feedback": feedback})
Expand All @@ -119,4 +126,3 @@ def update_feedback(message_id, feedback):
except Exception as e:
logging.error(f"Error updating feedback: {e}")
return False

41 changes: 21 additions & 20 deletions app/inference_services/whats_app_services.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
# logging.info(f"Response: {r.json()}")
# return r.json()


def send_message(message, token, recipient_id, phone_number_id, preview_url=True):
"""
Sends a text message to a WhatsApp user and returns the message ID
Expand All @@ -62,10 +63,7 @@ def send_message(message, token, recipient_id, phone_number_id, preview_url=True
str: ID of the sent message
"""
base_url = "https://graph.facebook.com/v12.0"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
url = f"{base_url}/{phone_number_id}/messages"
data = {
"messaging_product": "whatsapp",
Expand All @@ -76,7 +74,7 @@ def send_message(message, token, recipient_id, phone_number_id, preview_url=True
r = requests.post(url, headers=headers, json=data)
if r.status_code == 200:
response_json = r.json()
message_id = response_json.get('messages', [{}])[0].get('id')
message_id = response_json.get("messages", [{}])[0].get("id")
logging.info(f"Message sent to {recipient_id} with ID: {message_id}")
return message_id
else:
Expand All @@ -86,7 +84,6 @@ def send_message(message, token, recipient_id, phone_number_id, preview_url=True
return None



def reply_to_message(
token,
message_id: str,
Expand Down Expand Up @@ -974,8 +971,10 @@ def get_media_url(media_id, token):
f"Failed to retrieve media URL. HTTP Status: {response.status_code}, Response: {response.text}"
)


# my new code


def valid_payload(payload):
return "object" in payload and (
"entry" in payload
Expand Down Expand Up @@ -1040,6 +1039,7 @@ def welcome_message(sender_name=""):
"The Translation and Transcription Service Team"
)


def help_message():
return (
"Help Guide:\n\n"
Expand All @@ -1065,14 +1065,15 @@ def help_message():
)



def set_default_target_language(user_id, save_user_preference):
default_target_language = "Luganda"
defualt_source_language = "English"
save_user_preference(user_id, defualt_source_language, default_target_language)


def handle_language_selection(user_id, selection, source_language, save_user_preference, languages_obj):
def handle_language_selection(
user_id, selection, source_language, save_user_preference, languages_obj
):
if int(selection) == 6:
save_user_preference(user_id, source_language, languages_obj[selection])
return f"Language set to {languages_obj[selection]}. You can now send texts to translate."
Expand All @@ -1084,27 +1085,27 @@ def handle_language_selection(user_id, selection, source_language, save_user_pre
def get_audio(payload: dict):
"""
Extracts audio information from the webhook payload.

Args:
payload (dict): The incoming webhook payload.

Returns:
dict: Audio information if available, otherwise None.
"""
try:
if 'entry' in payload:
for entry in payload['entry']:
if 'changes' in entry:
for change in entry['changes']:
if 'value' in change and 'messages' in change['value']:
for message in change['value']['messages']:
if 'audio' in message:
if "entry" in payload:
for entry in payload["entry"]:
if "changes" in entry:
for change in entry["changes"]:
if "value" in change and "messages" in change["value"]:
for message in change["value"]["messages"]:
if "audio" in message:
audio_info = {
"id": message['audio']['id'],
"mime_type": message['audio']['mime_type']
"id": message["audio"]["id"],
"mime_type": message["audio"]["mime_type"],
}
return audio_info
return None
except KeyError:
logging.error("KeyError: Missing expected key in payload.")
return None
return None
11 changes: 8 additions & 3 deletions app/routers/frontend.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import logging
from datetime import timedelta
from typing import List

Expand All @@ -16,7 +17,7 @@
from app.crud.users import create_user, get_user_by_email, get_user_by_username
from app.deps import get_db
from app.routers.auth import get_current_user
from app.schemas.audio_transcription import AudioTranscriptionBase
from app.schemas.audio_transcription import AudioTranscriptionBase, ItemQueryParams
from app.schemas.users import User, UserCreate, UserInDB
from app.utils.auth_utils import (
ACCESS_TOKEN_EXPIRE_MINUTES,
Expand All @@ -31,6 +32,7 @@
router = APIRouter()
templates = Jinja2Templates(directory="app/templates")
oauth2_scheme = OAuth2PasswordBearerWithCookie(tokenUrl="/auth/token")
logging.basicConfig(level=logging.INFO)


@router.get("/")
Expand Down Expand Up @@ -175,7 +177,9 @@ async def account(
response_model=List[AudioTranscriptionBase],
)
async def get_audio_transcriptions(
current_user=Depends(get_current_user), db: Session = Depends(get_db)
current_user=Depends(get_current_user),
params: ItemQueryParams = Depends(),
db: Session = Depends(get_db),
):
"""
This endpoint returns all the transcriptions per user.
Expand All @@ -184,7 +188,7 @@ async def get_audio_transcriptions(
"""

transcriptions = await crud_audio_transcriptions(
db=db, username=current_user.username
db=db, username=current_user.username, params=params
)

if not transcriptions:
Expand Down Expand Up @@ -233,6 +237,7 @@ async def update_audio_transcription(
db.commit()
db.refresh(transcription)
except Exception as e:
logging.error(f"Error: {str(e)}")
db.rollback()
raise HTTPException(
status_code=500, detail="An error occurred while updating the transcription"
Expand Down
Loading
Loading