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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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
import gradio as gr
import gspread
import shutil
import os
from datetime import datetime
from google.cloud import storage
import os
import shutil
import threading
from google.cloud import speech

# Set the environment variable for your service account JSON
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "story_legacy_service_account.json"


# GCS Bucket Configuration
GCS_BUCKET_NAME = "userrecordings"
# Google Sheets API setup
SHEET_URL = "https://docs.google.com/spreadsheets/d/1ZlO_YQyFV6HsZH6hWIEtCw4VHxa7NXKlRULG_2Dkyao/edit"
PROJECT_CODE = "P2401"  # Hardcoded project code

def fetch_sheet_data(sheet_url):
    gc = gspread.service_account(filename="story_legacy_service_account.json")
    sh = gc.open_by_url(sheet_url)
    worksheet = sh.sheet1
    data = worksheet.get_all_records()
    return data

# Load Google Sheet data
data = fetch_sheet_data(SHEET_URL)

# Global variables to track the state
current_project = None
current_prompt_index = 0
prompts = []
recording_status = []
responses = []

# Load the project using the hardcoded project code
current_project = [row for row in data if row["Project Code"] == PROJECT_CODE]
if current_project:
    current_project = current_project[0]
    prompts = [current_project[f"Prompt{i+1}"] for i in range(4) if current_project.get(f"Prompt{i+1}")]
    recording_status = [False] * len(prompts)  # Initialize recording status for each prompt
    responses = [None] * len(prompts) 
else:
    prompts = []
custom_html=""" 
<style>
        /* Body Styles */
        .gr-container {
            font-family: Arial, sans-serif !important;
            background-color: #F5F5DC !important;
            color: #333 !important;
        }

        /* Row Styles */
        .gr-row {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 15px 0;
            padding: 10px;
            width: 100%;
        }

        /* Audio Component Styles */
        .gr-audio {
            background-color: #F5F5DC;
            padding: 10px 10px;
            border-radius: 10px;
            font-size:20px;
            color:blue;
        }

        .gr-audio button[title="Clear"] {
        display: none !important;
        }

        /* Prompt style */
        .gr-prompt {
            background-color: #F5F5DC;
            color: #00008B; /* Deep Blue */
            padding: 10px 10px;
            border-radius: 10px;
      
        }
        .gr-submit_button{
            background-color: #28a745;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 20px;
            font-size: 20px;
            cursor: pointer;
            margin: 5px;
        }

        /* Erase button */
        .gr-erase_button {
            background-color: #EE4B2B;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 20px;
            font-size: 20px;
            cursor: pointer;
            margin: 5px;
        }

        .gr-erase_button:hover {
            background-color: #A52A2A;
        }

        /* NExt button */
        .gr-next_button {
            background-color: #28a745;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 20px;
            font-size: 20px;
            cursor: pointer;
            margin: 5px;
        }

        .gr-next_button:hover {
            background-color: #218838;
        }

        .warning-alert  {
            font-size: 16px;
            color: black;
            margin-top: 2px;
            text-align: center;
            font-weight: bold;
            border: 1px solid #d9534f;
            padding: 10px;
            background-color: #FFED01; /* Light red background for alert */
     
        }
        .fail-alert  {
            font-size: 16px;
            color: black;
            margin-top: 2px;
            text-align: center;
            font-weight: bold;
            border: 1px solid #d9534f;
            padding: 10px;
            background-color: #FF0000; /* Light red background for alert */
        }
        .sucess-alert  {
            font-size: 16px;
            color: black;
            margin-top: 2px;
            text-align: center;
            font-weight: bold;
            border: 1px solid #d9534f;
            padding: 10px;
            background-color:#90EE90; /* Light red background for alert */
        }
        .gr-story_legacy_heading {
                background-color: White;
                font-size: 30px;
                font-weight: bold;
                color:#00008B;
                text-align: left;
                margin-top:-10px;
                margin-bottom: 10px;
            }
        .gr-project_code {
                background-color: White;
                font-size: 30px;
                font-weight: bold;
                color:#00008B; 
                text-align: right;
                margin-top:-10px;
                margin-bottom: 10px;
        }
        .prompt-class {
            font-weight: bold;
            color:#00008B;
            font-size: 20px;

        }
    .gr-markdown {
            position: fixed;
            width: 95%;
            z-index: 1000;
            border-radius: 5px;
            margin-top:-10px;
            margin-bottom: 20px;
        } 
    .prompt-text {
        font-size: 15px;
    }
    </style>
    """
# Function to transcribe audio files and save them locally
def transcribe_audio(local_file_path):
    """Transcribes audio data from a Google Cloud Storage bucket."""
    
    with open(local_file_path, "rb") as audio_file:
        content = audio_file.read()

    client = speech.SpeechClient()
    audio = speech.RecognitionAudio(content=content)
    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=44100,  # Adjust if needed
        language_code="en-US",
    )
    response = client.recognize(config=config, audio=audio)
    return response.results[0].alternatives[0].transcript if response.results else "No transcription available."

# function to upload responses and generate transcripts
def upload_to_gcs_and_cleanup():
    try:
        # Initialize GCS client
        client = storage.Client(project="story-legacy-442314")
        bucket = client.bucket(GCS_BUCKET_NAME)

        # Walk through the responses directory
        for root, _, files in os.walk(f"responses/{PROJECT_CODE}"):
            for file in files:
                local_path = os.path.join(root, file)

                # Define the relative path for GCS
                relative_path = os.path.relpath(local_path, f"responses/{PROJECT_CODE}")
                gcs_path = f"{PROJECT_CODE}/responses/{relative_path}"

                # Upload the file to GCS
                blob = bucket.blob(gcs_path)
                blob.upload_from_filename(local_path)
                print(f"Uploaded {local_path} to {gcs_path}")

                # Generate the transcript
                transcript_text = transcribe_audio(local_path)

                # Save the transcript in GCS under the transcripts folder with the new structure
                transcript_relative_path = relative_path.replace("responses/", "")  # Remove "responses/" from path
                transcript_gcs_path = f"{PROJECT_CODE}/transcripts/{transcript_relative_path.replace(os.path.splitext(file)[1], '.txt')}"
                transcript_blob = bucket.blob(transcript_gcs_path)
                transcript_blob.upload_from_string(transcript_text)
                print(f"Transcript uploaded to {transcript_gcs_path}")

                # Delete the local response file
                os.remove(local_path)

        # Remove the responses directory after successful upload
        response_dir = f"responses/{PROJECT_CODE}"
        if os.path.exists(response_dir):
            shutil.rmtree(response_dir)
            print(f"Local directory {response_dir} has been deleted.")

        return True, "All responses and transcripts have been uploaded to GCS, and local files deleted."
    except Exception as e:
        print(f"Error during GCS upload: {e}")
        return False, f"Error during GCS upload: {str(e)}"

# Background task function
def async_upload_to_gcs_and_cleanup():
    success, message = upload_to_gcs_and_cleanup()
    print(message)



def submit_audio(audio_path):
    global current_prompt_index
    print(f"Received audio_path: {audio_path}")  # Debugging line to check the value

    # Check if the response has already been submitted
    if recording_status[current_prompt_index]:
        return (
            f"""<div class ="prompt-class">Prompt {current_prompt_index + 1}/{len(prompts)}:</div> <div class="prompt-text">{prompts[current_prompt_index]}</div>""",
            gr.update(value=f"""<div class="sucess-alert">⚠️  Response for Prompt {current_prompt_index + 1} has already been submitted.</div>""", visible=True),
        )
    
    # Check if no audio is recorded
    if audio_path is None:
        return (
            f"""<div class ="prompt-class">Prompt {current_prompt_index + 1}/{len(prompts)}:</div><div class="prompt-text"> {prompts[current_prompt_index]}</div>""",
            gr.update(value="", visible=True),
        )
    
    try:
        # Ensure the directory exists and move the file
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        folder_path = f"responses/{PROJECT_CODE}/Prompt{current_prompt_index + 1}"
        os.makedirs(folder_path, exist_ok=True)
        file_path = f"{folder_path}/response_{timestamp}.wav"
        shutil.move(audio_path, file_path)
        
        # Update recording status and responses
        recording_status[current_prompt_index] = True
        responses[current_prompt_index] = file_path
        
        return (
            f"""<div class ="prompt-class">Prompt {current_prompt_index + 1}/{len(prompts)}:</div><div class="prompt-text"> {prompts[current_prompt_index]}</div>""",
            gr.update(value=f"""<div class = "sucess-alert">Response for Prompt {current_prompt_index + 1} has been submitted successfully!</div>""", visible=True),
        )
    except Exception as e:
        print(f"Error occurred during submission: {e}")  # Debugging line for exception
        return (
            f"""<div class="prompt-class">Prompt {current_prompt_index + 1}/{len(prompts)}:</div><div class="prompt-text"> {prompts[current_prompt_index]}</div>""",
            gr.update(value=f"""<div class= "fail-alert">⚠️  An error occurred during submission: {str(e)}</div>""", visible=True),
        )

def save_and_next():
    global current_prompt_index
    if not recording_status[current_prompt_index]:
        return (
            f"""<div class ="prompt-class">Prompt {current_prompt_index + 1} of {len(prompts)}:</div><div class="prompt-text">{prompts[current_prompt_index]}</div>""",
            gr.update(value=f"""<div class="warning-alert">⚠️ Please record and submit your response before moving to the next prompt.</div>""", visible=True),
            gr.update(visible=True),
            gr.update(visible=True),
            gr.update(visible=True),

        )

    if current_prompt_index < len(prompts) - 1:
        current_prompt_index += 1
        is_last_prompt = current_prompt_index == len(prompts) - 1
        next_button_text = "Finish" if is_last_prompt else f"Next Prompt ({current_prompt_index + 2} of {len(prompts)})"
        return (
            f"""<div class ="prompt-class">Prompt {current_prompt_index + 1} of {len(prompts)}:</div><div class="prompt-text"> {prompts[current_prompt_index]}</div>""",
            gr.update(value="", visible=False),  # Clear the alert message
            gr.update(value=None, visible=True),
            gr.update(value=next_button_text, visible=True),
            gr.update(visible=True),

        )
    else:
        # "Finish" button clicked
        threading.Thread(target=async_upload_to_gcs_and_cleanup, daemon=True).start()

        # print(upload_to_gcs_and_cleanup())
        # alert_class = "success-alert" if success else "fail-alert"
        return (
            "Thank you for your participation in this research, all of your stories have been submitted. We place great value on your stories and will treat them with the respect they deserve.",
            gr.update(value="", visible=True),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),

        )

def erase_and_record():
    global current_prompt_index
    # Check if a response exists for the current prompt
    if responses[current_prompt_index]:
        # Delete the file
        try:
            os.remove(responses[current_prompt_index])
        except FileNotFoundError:
            pass  # Ignore if the file doesn't exist
        responses[current_prompt_index] = None  # Reset the response
        recording_status[current_prompt_index] = False  # Reset recording status

        # Return updated prompt and alert message
        return (
            f"""<div class="prompt-class">Prompt {current_prompt_index + 1}/{len(prompts)}:</div><div class="prompt-text"> {prompts[current_prompt_index]}</div>""",
            gr.update(value=None, visible=True),  # Reset the audio input
            gr.update(value=f"""<div class= "sucess-alert">Your previous response has been erased. Please re-record your response.</div>""", visible=True),  # Updated alert message
        )
    else:
        return (
            f"""<div class="prompt-class">Prompt {current_prompt_index + 1}/{len(prompts)}:</div><div class="prompt-text"> {prompts[current_prompt_index]}</div>""",
            gr.update(visible=True),  # Reset the audio input
            gr.update(value=f"""<div class= "warning-alert">⚠️ Please record and submit your response first.</div>""", visible=True),  # Updated alert message
        )
# Gradio Interface
def gradio_app():
    # reset_state()
    with gr.Blocks(css=custom_html) as demo:
        with gr.Row():
            gr.Markdown("""
            <div class ="gr-story_legacy_heading">StoryLegacy</div>
            """)
            gr.Markdown(f"""
            <div class="gr-project_code">Project: {PROJECT_CODE}</div>
            """)

        with gr.Row():
            alert_box = gr.Markdown("", elem_id="alert-box", visible=False)
        with gr.Row():
            prompt_display = gr.Markdown(
                f"""<div class ="prompt-class">Prompt {current_prompt_index + 1} of {len(prompts)}:</div> <div class="prompt-text">{prompts[0] if prompts else 'No prompts available.'}</div>",
                """,elem_classes=["gr-prompt"]
            )
        with gr.Row():
            # Create a hidden label to dynamically update microphone status
            record_audio = gr.Audio(
                sources="microphone", 
                type="filepath", 
                label="Record your response",
                elem_classes=["gr-audio"]
        )
        with gr.Row():
            erase_button = gr.Button("Erase & Re - Record Current Prompt", elem_classes=["gr-erase_button"])
            save_next_button = gr.Button(f"Next Prompt (2 of {len(prompts)})", elem_classes=["gr-next_button"])

        record_audio.change(submit_audio, inputs=record_audio, outputs=[prompt_display,alert_box])

        save_next_button.click(
            save_and_next,
            inputs=[],
            outputs=[
                prompt_display,
                alert_box,
                record_audio,
                save_next_button,
                erase_button,
                
            ],
        )
        erase_button.click(
            erase_and_record,
            inputs=[],
            outputs=[
                prompt_display,
                record_audio,
                alert_box,
                
            ],
        )
                
        @demo.load
        def initialize_state():
            """Initialize or reset the app's state when reloaded."""
            global current_project, current_prompt_index, prompts, recording_status, responses, custom_html

            # Load the Google Sheet data
            data = fetch_sheet_data(SHEET_URL)

            # Load the project using the hardcoded project code
            current_project = [row for row in data if row["Project Code"] == PROJECT_CODE]
            if current_project:
                current_project = current_project[0]
                prompts = [current_project[f"Prompt{i+1}"] for i in range(4) if current_project.get(f"Prompt{i+1}")]
                recording_status = [False] * len(prompts)
                responses = [None] * len(prompts)
            else:
                prompts = []
            
            # Reset the current prompt index
            current_prompt_index = 0
            print("State has been initialized.")

    return demo

# Run the app
# reset_state()
app = gradio_app()
app.launch()