sathyaphaneeshwar commited on
Commit
538dd80
1 Parent(s): 8e3ff94

Speech_to_test_Version1

Browse files
Files changed (4) hide show
  1. app.py +209 -0
  2. client_secret.json +1 -0
  3. requirements.txt +12 -0
  4. secret.env +2 -0
app.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from google_auth_oauthlib.flow import Flow
3
+ from googleapiclient.discovery import build
4
+ from googleapiclient.http import MediaFileUpload
5
+ from deepgram import DeepgramClient, PrerecordedOptions
6
+ import os
7
+ import re
8
+ import pickle
9
+ import webbrowser
10
+ from threading import Thread
11
+ from flask import Flask, request
12
+
13
+ # OAuth 2.0 configuration
14
+ CLIENT_SECRETS_FILE = "C:/Users/sathy/OneDrive/Desktop/gradio_app/gradio3/client_secret2.json"
15
+ SCOPES = ['https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/userinfo.profile']
16
+ API_SERVICE_NAME = 'drive'
17
+ API_VERSION = 'v3'
18
+
19
+ # Global variables to store user credentials and info
20
+ user_creds = None
21
+ user_info = None
22
+ auth_completed = False
23
+ DEEPGRAM_API_KEY = "1e124afa2a0bdb7fbc62306edf5cb73f5439dc4c"
24
+
25
+ function_variables = {}
26
+
27
+ # Flask app for handling OAuth callback
28
+ app = Flask(__name__)
29
+
30
+ @app.route('/oauth2callback')
31
+ def oauth2callback():
32
+ global user_creds, user_info, auth_completed
33
+ flow = Flow.from_client_secrets_file(
34
+ CLIENT_SECRETS_FILE, SCOPES, redirect_uri='http://localhost:8080/oauth2callback')
35
+ flow.fetch_token(code=request.args.get('code'))
36
+ user_creds = flow.credentials
37
+
38
+ # Save credentials for future use
39
+ with open('token.pickle', 'wb') as token:
40
+ pickle.dump(user_creds, token)
41
+
42
+ # Get user info
43
+ try:
44
+ service = build('oauth2', 'v2', credentials=user_creds)
45
+ user_info = service.userinfo().get().execute()
46
+ auth_completed = True
47
+ except Exception as e:
48
+ print(f"Error getting user info: {str(e)}")
49
+ user_info = None
50
+ auth_completed = False
51
+
52
+ return "Authentication successful! You can close this window and return to the app."
53
+
54
+ def start_server():
55
+ app.run(port=8080)
56
+
57
+ def login():
58
+ global user_creds, user_info, auth_completed
59
+ auth_completed = False
60
+ flow = Flow.from_client_secrets_file(
61
+ CLIENT_SECRETS_FILE, SCOPES, redirect_uri='http://localhost:8080/oauth2callback')
62
+ auth_url, _ = flow.authorization_url(prompt='consent')
63
+
64
+ # Start the local server in a separate thread
65
+ Thread(target=start_server).start()
66
+
67
+ # Open the authorization URL in the default browser
68
+ webbrowser.open(auth_url)
69
+
70
+ # Wait for the authentication to complete
71
+ import time
72
+ timeout = 60 # 60 seconds timeout
73
+ start_time = time.time()
74
+ while not auth_completed:
75
+ time.sleep(1)
76
+ if time.time() - start_time > timeout:
77
+ return "Login timed out. Please try again."
78
+
79
+ if user_info:
80
+ return f"Logged in as: {user_info.get('name', 'Unknown')}"
81
+ else:
82
+ return "Login failed. Please check your credentials and try again."
83
+
84
+ def create_folder_if_not_exists(service, folder_name):
85
+ query = f"name='{folder_name}' and mimeType='application/vnd.google-apps.folder'"
86
+ results = service.files().list(q=query, fields="files(id)").execute()
87
+ folders = results.get('files', [])
88
+
89
+ if not folders:
90
+ folder_metadata = {
91
+ 'name': folder_name,
92
+ 'mimeType': 'application/vnd.google-apps.folder'
93
+ }
94
+ folder = service.files().create(body=folder_metadata, fields='id').execute()
95
+ return folder['id']
96
+ else:
97
+ return folders[0]['id']
98
+
99
+
100
+ def upload_file(file):
101
+ global user_creds, user_info
102
+ if not user_creds:
103
+ return "Please login first."
104
+
105
+ try:
106
+ drive_service = build(API_SERVICE_NAME, API_VERSION, credentials=user_creds)
107
+
108
+ folder_id = create_folder_if_not_exists(drive_service, 'GradioUploads')
109
+
110
+ file_metadata = {
111
+ 'name': os.path.basename(file.name),
112
+ 'parents': [folder_id]
113
+ }
114
+
115
+ media = MediaFileUpload(file.name, resumable=True)
116
+ file = drive_service.files().create(body=file_metadata, media_body=media, fields='id,webViewLink,name').execute()
117
+ uploaded_filename = file.get('name')
118
+ # Set the file to be publicly accessible
119
+ permission = {
120
+ 'type': 'anyone',
121
+ 'role': 'reader',
122
+ }
123
+ drive_service.permissions().create(fileId=file['id'], body=permission).execute()
124
+
125
+ file_id = file['id']
126
+ function_variables['file_name']=file.get('name')
127
+
128
+ download_link = f"https://drive.google.com/uc?export=download&id={file_id}"
129
+
130
+ function_variables['download_link'] = download_link
131
+
132
+ return f"File uploaded by: {user_info.get('name', 'Unknown')}\nShareable Link: {file['webViewLink']}\nDownloadable Link: {function_variables['download_link'] }"
133
+ except Exception as e:
134
+ return f"An error occurred: {str(e)}"
135
+
136
+ def transcribe_audio():
137
+ try:
138
+ deepgram = DeepgramClient(DEEPGRAM_API_KEY)
139
+
140
+ options = PrerecordedOptions(
141
+ model="nova-2",
142
+ language="en",
143
+ smart_format=True,
144
+ )
145
+
146
+ #AUDIO_URL = function_variables['download_link']
147
+ AUDIO_URL = {
148
+ "url": str(function_variables['download_link'])
149
+ }
150
+ #print(f"Audio link: {AUDIO_URL}") # Debugging line to verify URL
151
+ response = deepgram.listen.prerecorded.v("1").transcribe_url(AUDIO_URL, options)
152
+ response_json = response.to_dict() # Convert response to a dictionary
153
+ transcript = response_json['results']['channels'][0]['alternatives'][0]['transcript']
154
+ function_variables['transcript'] = transcript
155
+ #return audio_link
156
+ return transcript
157
+
158
+ except Exception as e:
159
+ print(f"Exception: {e}")
160
+
161
+ def print_transcript():
162
+ try:
163
+ audioname=str(function_variables['file_name'])
164
+ transcript_file_name = re.sub(r'\..*', '', audioname) + "_transcript.txt"
165
+
166
+ with open(transcript_file_name, 'w') as file:
167
+ file.write(function_variables['transcript'])
168
+
169
+ function_variables['transcript_file_path'] = transcript_file_name # Save the file path
170
+
171
+ return transcript_file_name
172
+
173
+ #return function_variables['download_link']
174
+ #return transcript_file_name, text_op
175
+
176
+ except Exception as e:
177
+ return f"An error occurred while saving the transcript: {str(e)}"
178
+
179
+
180
+ # Gradio interface
181
+ with gr.Blocks() as demo:
182
+ gr.Markdown("# Upload File to Google Drive")
183
+
184
+ with gr.Row():
185
+ login_button = gr.Button("Login with Google")
186
+ login_output = gr.Textbox(label="Login Status", lines=3)
187
+
188
+ with gr.Row():
189
+ file_input = gr.File(label="Upload a file")
190
+ upload_output = gr.Textbox(label="Upload Result")
191
+
192
+ upload_button = gr.Button("Upload to Google Drive")
193
+
194
+ with gr.Row():
195
+ transcribe_button = gr.Button("Transcribe the audio")
196
+ print_transcript_button = gr.Button("Print Transcript")
197
+
198
+
199
+ downloadble_preview = gr.Textbox(label="Transcript")
200
+ download_file = gr.File(label="Download file")
201
+
202
+ login_button.click(login, outputs=login_output)
203
+ upload_button.click(upload_file, inputs=file_input, outputs=upload_output)
204
+ transcribe_button.click(transcribe_audio, outputs=downloadble_preview)
205
+ #print_transcript_button.click(print_transcript, outputs=downloadble_preview)
206
+ print_transcript_button.click(print_transcript, outputs=download_file)
207
+
208
+ if __name__ == '__main__':
209
+ demo.launch()
client_secret.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"installed":{"client_id":"416573340049-hnv2nll4f5iqn5bckdd67v8j7qt1tgi5.apps.googleusercontent.com","project_id":"audiofilesbucket","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"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","redirect_uris":["http://localhost"]}}
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ google-auth-oauthlib
3
+ google-auth-httplib2
4
+ google-api-python-client
5
+ cryptography
6
+ pyasn1
7
+
8
+ app_1 - working till file upload part
9
+
10
+ app_login - working till login part
11
+
12
+ 1e124afa2a0bdb7fbc62306edf5cb73f5439dc4c - apikey
secret.env ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ DEEPGRAM_API_KEY="1e124afa2a0bdb7fbc62306edf5cb73f5439dc4c"
2
+ CLIENT_SECRETS_FILE=client_secret.json