In the following code, the user is first authenticated via their Google account, and then their registration is verified by checking a database. Once authenticated and validated, a sentence is displayed for the user to record. After the user records the audio and stops it, the file is correctly saved in the /tmp/gradio/ directory. However, when the function from gr.Interface is triggered, it fails to retrieve the file path for the recorded audio.
I’m unable to get the file path from the gr.Audio component after the recording is saved. Any assistance would be greatly appreciated!
import os
from authlib.integrations.starlette_client import OAuth, OAuthError
from fastapi import FastAPI, Depends, Request
from starlette.config import Config
from starlette.responses import RedirectResponse
from starlette.middleware.sessions import SessionMiddleware
import uvicorn
import gradio as gr
import mysql.connector
app = FastAPI()
# The text to display
text_to_display = "Hello World!"
# Replace these with your own OAuth settings
GOOGLE_CLIENT_ID = "..."
GOOGLE_CLIENT_SECRET = "..."
SECRET_KEY = "..."
config_data = {'GOOGLE_CLIENT_ID': GOOGLE_CLIENT_ID, 'GOOGLE_CLIENT_SECRET': GOOGLE_CLIENT_SECRET}
starlette_config = Config(environ=config_data)
oauth = OAuth(starlette_config)
oauth.register(
name='google',
server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
client_kwargs={'scope': 'openid email profile'},
)
SECRET_KEY = os.environ.get('SECRET_KEY') or "a_very_secret_key"
app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY)
# MySQL database connection setup
def get_db_connection():
return mysql.connector.connect(
host = 'localhost', # Change if your MySQL server is on a different host
user = 'root',
password = 'password',
database = 'database'
)
# Dependency to get the current user and check registration
def get_user(request: Request):
user = request.session.get('user')
if user:
return user
return None
def validate_user(email):
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT COUNT(*) AS Count FROM sp WHERE id = %s", (email,))
result = cursor.fetchone()
conn.close()
# if verify_user_in_db(email):
if result['Count']!=0:
return 1
else:
return None
@app.get('/')
def public(user: dict = Depends(get_user)):
if user:
email=user['email']
if validate_user(email):
return RedirectResponse(url='/gradio')
else:
return RedirectResponse(url='/register')
else:
return RedirectResponse(url='/login-demo')
@app.route('/logout')
async def logout(request: Request):
request.session.pop('user', None)
return RedirectResponse(url='/')
@app.route('/login')
async def login(request: Request):
redirect_uri = request.url_for('auth')
return await oauth.google.authorize_redirect(request, redirect_uri)
@app.route('/auth')
async def auth(request: Request):
try:
access_token = await oauth.google.authorize_access_token(request)
except OAuthError:
return RedirectResponse(url='/')
request.session['user'] = dict(access_token)["userinfo"]
return RedirectResponse(url='/')
with gr.Blocks() as register:
sentence_to_display = gr.Markdown("Please register to contribute by contacting the Admin")
gr.Button("Logout", link="/logout")
app = gr.mount_gradio_app(app, register, path="/register")
with gr.Blocks() as login_demo:
gr.Button("Login", link="/login")
app = gr.mount_gradio_app(app, login_demo, path="/login-demo")
def save_audio(audio_file_path):#, hidden_state):
if not audio_file_path:
return audio_file_path
else:
return "Audio file path is not retrieved"
with gr.Blocks() as main_demo:
sentence_to_display=gr.Markdown(f"Please read the following sentence while recording:nn**{text_to_display}**")
audio_input = gr.Audio(type='filepath', sources="microphone", label="Record your audio here")
tb=gr.Textbox(label="Status", lines=3)
gr.Interface(fn=save_audio, inputs=[audio_input], outputs=[tb],flagging_options=[])
gr.Button("Logout", link="/logout")
app = gr.mount_gradio_app(app, main_demo, path="/gradio", auth_dependency=get_user)
if __name__ == '__main__':
uvicorn.run(app, host="127.0.0.1", port=8000)
Without authentication it is working when tried with bits and pieces.
1