Spaces:
Sleeping
Sleeping
File size: 7,754 Bytes
538dd80 5fef401 538dd80 84ec0a2 5fef401 538dd80 5fef401 538dd80 5fef401 538dd80 2fb9495 538dd80 2fb9495 538dd80 2fb9495 538dd80 2fb9495 538dd80 |
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 213 214 215 216 217 |
import gradio as gr
from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from deepgram import DeepgramClient, PrerecordedOptions
import os
import re
import pickle
import webbrowser
from threading import Thread
from flask import Flask, request
from dotenv import load_dotenv
load_dotenv('secret.env')
DEEPGRAM_API_KEY = os.getenv("DEEPGRAM_API_KEY")
CLIENT_SECRETS_FILE = os.getenv("CLIENT_SECRETS_FILE")
# OAuth 2.0 configuration
#CLIENT_SECRETS_FILE = "C:/Users/sathy/OneDrive/Desktop/gradio_app/gradio3/client_secret2.json"
SCOPES = ['https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/userinfo.profile']
API_SERVICE_NAME = 'drive'
API_VERSION = 'v3'
# Global variables to store user credentials and info
user_creds = None
user_info = None
auth_completed = False
function_variables = {}
# Flask app for handling OAuth callback
app = Flask(__name__)
@app.route('/oauth2callback')
def oauth2callback():
global user_creds, user_info, auth_completed
flow = Flow.from_client_secrets_file(
#CLIENT_SECRETS_FILE, SCOPES, redirect_uri='http://localhost:8080/oauth2callback')https://sathyaphaneeshwar-transcript_gradio.hf.space/oauth2callback
CLIENT_SECRETS_FILE, SCOPES, redirect_uri='https://sathyaphaneeshwar-transcript_gradio.hf.space/oauth2callback')
flow.fetch_token(code=request.args.get('code'))
user_creds = flow.credentials
# Save credentials for future use
with open('token.pickle', 'wb') as token:
pickle.dump(user_creds, token)
# Get user info
try:
service = build('oauth2', 'v2', credentials=user_creds)
user_info = service.userinfo().get().execute()
auth_completed = True
except Exception as e:
print(f"Error getting user info: {str(e)}")
user_info = None
auth_completed = False
return "Authentication successful! You can close this window and return to the app."
def start_server():
app.run(host='0.0.0.0', port=8080)
def login():
global user_creds, user_info, auth_completed
auth_completed = False
flow = Flow.from_client_secrets_file(
#CLIENT_SECRETS_FILE, SCOPES, redirect_uri='http://localhost:8080/oauth2callback')https://sathyaphaneeshwar-transcript-gradio.hf.space/oauth2callback
CLIENT_SECRETS_FILE, SCOPES, redirect_uri='https://sathyaphaneeshwar-transcript-gradio.hf.space/oauth2callback')
auth_url, _ = flow.authorization_url(prompt='consent')
# Start the local server in a separate thread
Thread(target=start_server).start()
# Open the authorization URL in the default browser
webbrowser.open(auth_url)
# Wait for the authentication to complete
import time
timeout = 60 # 60 seconds timeout
start_time = time.time()
while not auth_completed:
time.sleep(1)
if time.time() - start_time > timeout:
return "Login timed out. Please try again."
if user_info:
return f"Logged in as: {user_info.get('name', 'Unknown')}"
else:
return "Login failed. Please check your credentials and try again."
def create_folder_if_not_exists(service, folder_name):
query = f"name='{folder_name}' and mimeType='application/vnd.google-apps.folder'"
results = service.files().list(q=query, fields="files(id)").execute()
folders = results.get('files', [])
if not folders:
folder_metadata = {
'name': folder_name,
'mimeType': 'application/vnd.google-apps.folder'
}
folder = service.files().create(body=folder_metadata, fields='id').execute()
return folder['id']
else:
return folders[0]['id']
def upload_file(file):
global user_creds, user_info
if not user_creds:
return "Please login first."
try:
drive_service = build(API_SERVICE_NAME, API_VERSION, credentials=user_creds)
folder_id = create_folder_if_not_exists(drive_service, 'GradioUploads')
file_metadata = {
'name': os.path.basename(file.name),
'parents': [folder_id]
}
media = MediaFileUpload(file.name, resumable=True)
file = drive_service.files().create(body=file_metadata, media_body=media, fields='id,webViewLink,name').execute()
uploaded_filename = file.get('name')
# Set the file to be publicly accessible
permission = {
'type': 'anyone',
'role': 'reader',
}
drive_service.permissions().create(fileId=file['id'], body=permission).execute()
file_id = file['id']
function_variables['file_name']=file.get('name')
download_link = f"https://drive.google.com/uc?export=download&id={file_id}"
function_variables['download_link'] = download_link
return f"File uploaded by: {user_info.get('name', 'Unknown')}\nShareable Link: {file['webViewLink']}\nDownloadable Link: {function_variables['download_link'] }"
except Exception as e:
return f"An error occurred: {str(e)}"
def transcribe_audio():
try:
deepgram = DeepgramClient(DEEPGRAM_API_KEY)
options = PrerecordedOptions(
model="nova-2",
language="en",
smart_format=True,
)
#AUDIO_URL = function_variables['download_link']
AUDIO_URL = {
"url": str(function_variables['download_link'])
}
#print(f"Audio link: {AUDIO_URL}") # Debugging line to verify URL
response = deepgram.listen.prerecorded.v("1").transcribe_url(AUDIO_URL, options)
response_json = response.to_dict() # Convert response to a dictionary
transcript = response_json['results']['channels'][0]['alternatives'][0]['transcript']
function_variables['transcript'] = transcript
#return audio_link
return transcript
except Exception as e:
print(f"Exception: {e}")
def print_transcript():
try:
audioname=str(function_variables['file_name'])
transcript_file_name = re.sub(r'\..*', '', audioname) + "_transcript.txt"
with open(transcript_file_name, 'w') as file:
file.write(function_variables['transcript'])
function_variables['transcript_file_path'] = transcript_file_name # Save the file path
return transcript_file_name
#return function_variables['download_link']
#return transcript_file_name, text_op
except Exception as e:
return f"An error occurred while saving the transcript: {str(e)}"
# Gradio interface
with gr.Blocks() as demo:
gr.Markdown("# Upload File to Google Drive")
with gr.Row():
login_button = gr.Button("Login with Google")
login_output = gr.Textbox(label="Login Status", lines=3)
with gr.Row():
file_input = gr.File(label="Upload a file")
upload_output = gr.Textbox(label="Upload Result")
upload_button = gr.Button("Upload to Google Drive")
with gr.Row():
transcribe_button = gr.Button("Transcribe the audio")
print_transcript_button = gr.Button("Print Transcript")
downloadble_preview = gr.Textbox(label="Transcript")
download_file = gr.File(label="Download file")
login_button.click(login, outputs=login_output)
upload_button.click(upload_file, inputs=file_input, outputs=upload_output)
transcribe_button.click(transcribe_audio, outputs=downloadble_preview)
#print_transcript_button.click(print_transcript, outputs=downloadble_preview)
print_transcript_button.click(print_transcript, outputs=download_file)
if __name__ == '__main__':
Thread(target=start_server).start()
demo.launch() |