File size: 20,165 Bytes
9dac3f4
 
 
e0b3b4f
20b2044
d509284
57a62f9
a2e2c3e
d509284
9dac3f4
 
 
e0b3b4f
9dac3f4
 
 
 
 
 
 
 
 
d509284
9dac3f4
 
 
 
 
d509284
 
 
9dac3f4
 
 
 
c6d0876
 
 
9dac3f4
 
 
e0b3b4f
9dac3f4
 
20b2044
9dac3f4
e0b3b4f
 
20b2044
9dac3f4
 
e0b3b4f
9dac3f4
 
 
 
 
 
 
20b2044
4bfe417
9dac3f4
 
20b2044
4bfe417
 
 
 
 
 
e0b3b4f
 
 
20b2044
9dac3f4
20b2044
9dac3f4
 
20b2044
9dac3f4
20b2044
e0b3b4f
9dac3f4
e0b3b4f
20b2044
9dac3f4
e0b3b4f
9dac3f4
20b2044
9dac3f4
 
 
4bfe417
 
 
 
 
 
 
20b2044
e0b3b4f
d509284
e0b3b4f
d509284
 
 
9dac3f4
d509284
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0b3b4f
d53a07b
 
 
 
 
 
bfd0ee5
d509284
 
 
 
e0b3b4f
9dac3f4
d509284
 
 
 
 
 
9dac3f4
 
e0b3b4f
9dac3f4
e0b3b4f
9dac3f4
 
 
 
e4d272c
9dac3f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0b3b4f
 
 
 
 
40d601a
e0b3b4f
 
 
 
 
 
9dac3f4
 
 
e0b3b4f
9dac3f4
 
 
 
 
 
 
 
 
 
 
20b2044
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58e0366
 
3066087
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
import os
import whisper
import requests
from flask import Flask, request, jsonify, render_template
from dotenv import load_dotenv
from deepgram import DeepgramClient, PrerecordedOptions
import tempfile
import json

import warnings
warnings.filterwarnings("ignore", message="FP16 is not supported on CPU; using FP32 instead")

app = Flask(__name__)
print("APP IS RUNNING, ANIKET")

# Load the .env file
load_dotenv()

print("ENV LOADED, ANIKET")

# Fetch the API key from the .env file
API_KEY = os.getenv("FIRST_API_KEY")
DEEPGRAM_API_KEY = os.getenv("SECOND_API_KEY")

# Ensure the API key is loaded correctly
if not API_KEY:
    raise ValueError("API Key not found. Make sure it is set in the .env file.")

if not DEEPGRAM_API_KEY:
    raise ValueError("DEEPGRAM_API_KEY not found. Make sure it is set in the .env file.")

GEMINI_API_ENDPOINT = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent"
GEMINI_API_KEY = API_KEY

# Load Whisper AI model at startup
# print("Loading Whisper AI model..., ANIKET")
# whisper_model = whisper.load_model("base")  # Choose model size: tiny, base, small, medium, large
# print("Whisper AI model loaded successfully, ANIKET")


@app.route("/", methods=["GET"])
def health_check():
    return jsonify({"status": "success", "message": "API is running successfully!"}), 200


@app.route("/mbsa")
def mbsa():
    return render_template("mbsa.html")


@app.route('/process-audio', methods=['POST'])
def process_audio():
    print("GOT THE PROCESS AUDIO REQUEST, ANIKET")
    
    if 'audio' not in request.files:
        return jsonify({"error": "No audio file provided"}), 400

    audio_file = request.files['audio']
    print("AUDIO FILE NAME: ", audio_file)

    temp_audio_path = None
    try:
        print("STARTING TRANSCRIPTION, ANIKET")
        
        # Step 1: Save the audio file temporarily to a specific location
        with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_audio_file:
            temp_audio_path = temp_audio_file.name  # Get the file path
            temp_audio_file.write(audio_file.read())  # Write the uploaded audio to the temp file
        
        print(f"Temporary audio file saved at: {temp_audio_path}")
        
        # Step 2: Transcribe the uploaded audio file synchronously
        transcription = transcribe_audio(temp_audio_path)

        print("BEFORE THE transcription FAILED ERROR, CHECKING IF I GOT THE TRANSCRIPTION", transcription)

        if not transcription:
            return jsonify({"error": "Audio transcription failed"}), 500

        print("GOT THE transcription")

        # Step 3: Generate structured recipe information using Gemini API synchronously
        print("Starting the GEMINI REQUEST TO STRUCTURE IT")
        structured_data = query_gemini_api(transcription)

        print("GOT THE STRUCTURED DATA", structured_data)
        # Step 4: Return the structured data
        return jsonify(structured_data)

    except Exception as e:
        return jsonify({"error": str(e)}), 500

    finally:
        # Clean up the temporary WAV file
        if temp_audio_path and os.path.exists(temp_audio_path):
            os.remove(temp_audio_path)
            print(f"Temporary WAV file deleted: {temp_audio_path}")



def transcribe_audio(wav_file_path):
    """
    Transcribe audio from a video file using Deepgram API synchronously.
    
    Args:
        wav_file_path (str): Path to save the converted WAV file.

    Returns:
        dict: A dictionary containing status, transcript, or error message.
    """
    print("Entered the transcribe_audio function")
    try:
        # Initialize Deepgram client
        deepgram = DeepgramClient(DEEPGRAM_API_KEY)

        # Open the converted WAV file
        with open(wav_file_path, 'rb') as buffer_data:
            payload = {'buffer': buffer_data}

            # Configure transcription options
            options = PrerecordedOptions(
                smart_format=True, model="nova-2", language="en-US"
            )

            # Transcribe the audio
            response = deepgram.listen.prerecorded.v('1').transcribe_file(payload, options)

            # Check if the response is valid
            if response:
                print("Request successful! Processing response.")

                # Convert response to JSON string
                try:
                    data_str = response.to_json(indent=4)
                except AttributeError as e:
                    return {"status": "error", "message": f"Error converting response to JSON: {e}"}

                # Parse the JSON string to a Python dictionary
                try:
                    data = json.loads(data_str)
                except json.JSONDecodeError as e:
                    return {"status": "error", "message": f"Error parsing JSON string: {e}"}

                # Extract the transcript
                try:
                    transcript = data["results"]["channels"][0]["alternatives"][0]["transcript"]
                except KeyError as e:
                    return {"status": "error", "message": f"Error extracting transcript: {e}"}

                print(f"Transcript obtained: {transcript}")
                # Step: Save the transcript to a text file
                transcript_file_path = "transcript_from_transcribe_audio.txt"
                with open(transcript_file_path, "w", encoding="utf-8") as transcript_file:
                    transcript_file.write(transcript)
                print(f"Transcript saved to file: {transcript_file_path}")
                
                return transcript
            else:
                return {"status": "error", "message": "Invalid response from Deepgram."}

    except FileNotFoundError:
        return {"status": "error", "message": f"Video file not found: {wav_file_path}"}
    except Exception as e:
        return {"status": "error", "message": f"Unexpected error: {e}"}
    finally:
        # Clean up the temporary WAV file
        if os.path.exists(wav_file_path):
            os.remove(wav_file_path)
            print(f"Temporary WAV file deleted: {wav_file_path}")


def query_gemini_api(transcription):
    """
    Send transcription text to Gemini API and fetch structured recipe information synchronously.
    """
    try:
        # Define the structured prompt
        prompt = (
            "Print the transcription in the response as well"
            "Analyze the provided cooking video transcription and extract the following structured information:\n"
            "1. Recipe Name: Identify the name of the dish being prepared.\n"
            "2. Ingredients List: Extract a detailed list of ingredients with their respective quantities (if mentioned).\n"
            "3. Steps for Preparation: Provide a step-by-step breakdown of the recipe's preparation process, organized and numbered sequentially.\n"
            "4. Cooking Techniques Used: Highlight the cooking techniques demonstrated in the video, such as searing, blitzing, wrapping, etc.\n"
            "5. Equipment Needed: List all tools, appliances, or utensils mentioned, e.g., blender, hot pan, cling film, etc.\n"
            "6. Nutritional Information (if inferred): Provide an approximate calorie count or nutritional breakdown based on the ingredients used.\n"
            "7. Serving size: In count of people or portion size.\n"
            "8. Special Notes or Variations: Include any specific tips, variations, or alternatives mentioned.\n"
            "9. Festive or Thematic Relevance: Note if the recipe has any special relevance to holidays, events, or seasons.\n"
            f"Text: {transcription}\n"
        )

        # Prepare the payload and headers
        payload = {
            "contents": [
                {
                    "parts": [
                        {"text": prompt}
                    ]
                }
            ]
        }
        headers = {"Content-Type": "application/json"}

        # Send request to Gemini API synchronously
        response = requests.post(
            f"{GEMINI_API_ENDPOINT}?key={GEMINI_API_KEY}",
            json=payload,
            headers=headers,
            
        )

        # Raise error if response code is not 200
        response.raise_for_status()

        data = response.json()

        return data.get("candidates", [{}])[0].get("content", {}).get("parts", [{}])[0].get("text", "No result found")

    except requests.exceptions.RequestException as e:
        print(f"Error querying Gemini API: {e}")
        return {"error": str(e)}


if __name__ == '__main__':
    app.run(debug=True)





# # Above code is without polling and sleep
# import os
# import whisper
# import requests
# from flask import Flask, request, jsonify, render_template
# import tempfile
# import warnings
# warnings.filterwarnings("ignore", message="FP16 is not supported on CPU; using FP32 instead")

# app = Flask(__name__)
# print("APP IS RUNNING, ANIKET")

# # Gemini API settings
# from dotenv import load_dotenv
# # Load the .env file
# load_dotenv()

# print("ENV LOADED, ANIKET")

# # Fetch the API key from the .env file
# API_KEY = os.getenv("FIRST_API_KEY")

# # Ensure the API key is loaded correctly
# if not API_KEY:
#     raise ValueError("API Key not found. Make sure it is set in the .env file.")

# GEMINI_API_ENDPOINT = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent"
# GEMINI_API_KEY = API_KEY


# # Load Whisper AI model at startup
# print("Loading Whisper AI model..., ANIKET")
# whisper_model = whisper.load_model("base")  # Choose model size: tiny, base, small, medium, large
# print("Whisper AI model loaded successfully, ANIKET")


# # Define the "/" endpoint for health check
# @app.route("/", methods=["GET"])
# def health_check():
#     return jsonify({"status": "success", "message": "API is running successfully!"}), 200

# @app.route("/mbsa")
# def mbsa():
#     return render_template("mbsa.html")

# @app.route('/process-audio', methods=['POST'])
# def process_audio():
#     print("GOT THE PROCESS AUDIO REQUEST, ANIKET")
#     """
#     Flask endpoint to process audio:
#     1. Transcribe provided audio file using Whisper AI.
#     2. Send transcription to Gemini API for recipe information extraction.
#     3. Return structured data in the response.
#     """
    
#     if 'audio' not in request.files:
#         return jsonify({"error": "No audio file provided"}), 400

#     audio_file = request.files['audio']
#     print("AUDIO FILE NAME: ", audio_file)
    
#     try:
#         print("STARTING TRANSCRIPTION, ANIKET")
#         # Step 1: Transcribe the uploaded audio file directly
#         audio_file = request.files['audio']
#         transcription = transcribe_audio(audio_file)
    
#         print("BEFORE THE transcription FAILED ERROR, CHECKING IF I GOT THE TRANSCRIPTION", transcription)
    
#         if not transcription:
#             return jsonify({"error": "Audio transcription failed"}), 500
        
#         print("GOT THE transcription")
    
#         print("Starting the GEMINI REQUEST TO STRUCTURE IT")
#         # Step 2: Generate structured recipe information using Gemini API
#         structured_data = query_gemini_api(transcription)
        
#         print("GOT THE STRUCTURED DATA", structured_data)
#         # Step 3: Return the structured data
#         return jsonify(structured_data)
    
#     except Exception as e:
#         return jsonify({"error": str(e)}), 500

# def transcribe_audio(audio_path):
#     """
#     Transcribe audio using Whisper AI.
#     """
#     print("CAME IN THE transcribe audio function")
#     try:
#         # Transcribe audio using Whisper AI
#         print("Transcribing audio...")
#         result = whisper_model.transcribe(audio_path)
#         print("THE RESULTS ARE", result)
        
#         return result.get("text", "").strip()

#     except Exception as e:
#         print(f"Error in transcription: {e}")
#         return None


# def query_gemini_api(transcription):
#     """
#     Send transcription text to Gemini API and fetch structured recipe information.
#     """
#     try:
#         # Define the structured prompt
#         prompt = (
#             "Analyze the provided cooking video transcription and extract the following structured information:\n"
#             "1. Recipe Name: Identify the name of the dish being prepared.\n"
#             "2. Ingredients List: Extract a detailed list of ingredients with their respective quantities (if mentioned).\n"
#             "3. Steps for Preparation: Provide a step-by-step breakdown of the recipe's preparation process, organized and numbered sequentially.\n"
#             "4. Cooking Techniques Used: Highlight the cooking techniques demonstrated in the video, such as searing, blitzing, wrapping, etc.\n"
#             "5. Equipment Needed: List all tools, appliances, or utensils mentioned, e.g., blender, hot pan, cling film, etc.\n"
#             "6. Nutritional Information (if inferred): Provide an approximate calorie count or nutritional breakdown based on the ingredients used.\n"
#             "7. Serving size: In count of people or portion size.\n"
#             "8. Special Notes or Variations: Include any specific tips, variations, or alternatives mentioned.\n"
#             "9. Festive or Thematic Relevance: Note if the recipe has any special relevance to holidays, events, or seasons.\n"
#             f"Text: {transcription}\n"
#         )

#         # Prepare the payload and headers
#         payload = {
#             "contents": [
#                 {
#                     "parts": [
#                         {"text": prompt}
#                     ]
#                 }
#             ]
#         }
#         headers = {"Content-Type": "application/json"}

#         # Send request to Gemini API and wait for the response
#         print("Querying Gemini API...")
#         response = requests.post(
#             f"{GEMINI_API_ENDPOINT}?key={GEMINI_API_KEY}",
#             json=payload,
#             headers=headers,
#             timeout=60  # 60 seconds timeout for the request
#         )
#         response.raise_for_status()

#         # Extract and return the structured data
#         data = response.json()
#         return data.get("candidates", [{}])[0].get("content", {}).get("parts", [{}])[0].get("text", "No result found")

#     except requests.exceptions.RequestException as e:
#         print(f"Error querying Gemini API: {e}")
#         return {"error": str(e)}


# if __name__ == '__main__':
#     app.run(debug=True)







# import os
# import subprocess
# import whisper
# import requests
# import tempfile
# import warnings
# import threading
# from flask import Flask, request, jsonify, send_file, render_template

# from dotenv import load_dotenv
# import requests




# warnings.filterwarnings("ignore", category=UserWarning, module="whisper")


# app = Flask(__name__)


# # Gemini API settings
# load_dotenv()
# API_KEY = os.getenv("FIRST_API_KEY")

# # Ensure the API key is loaded correctly
# if not API_KEY:
#     raise ValueError("API Key not found. Make sure it is set in the .env file.")

# GEMINI_API_ENDPOINT = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent"
# GEMINI_API_KEY = API_KEY

# # Load Whisper AI model at startup
# print("Loading Whisper AI model...")
# whisper_model = whisper.load_model("base")
# print("Whisper AI model loaded successfully.")

# # Define the "/" endpoint for health check
# @app.route("/", methods=["GET"])
# def health_check():
#     return jsonify({"status": "success", "message": "API is running successfully!"}), 200


# def process_video_in_background(video_file, temp_video_file_name):
#     """
#     This function is executed in a separate thread to handle the long-running
#     video processing tasks such as transcription and querying the Gemini API.
#     """
#     try:
#         transcription = transcribe_audio(temp_video_file_name)

#         if not transcription:
#             print("Audio transcription failed")
#             return

#         structured_data = query_gemini_api(transcription)

#         # Send structured data back or store it in a database, depending on your use case
#         print("Processing complete. Structured data:", structured_data)

#     except Exception as e:
#         print(f"Error processing video: {e}")

#     finally:
#         # Clean up temporary files
#         if os.path.exists(temp_video_file_name):
#             os.remove(temp_video_file_name)


# @app.route('/process-video', methods=['POST'])
# def process_video():
#     if 'video' not in request.files:
#         return jsonify({"error": "No video file provided"}), 400

#     video_file = request.files['video']

#     try:
#         # Save video to a temporary file
#         with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_video_file:
#             video_file.save(temp_video_file.name)
#             print(f"Video file saved: {temp_video_file.name}")

#             # Start the video processing in a background thread
#             threading.Thread(target=process_video_in_background, args=(video_file, temp_video_file.name)).start()

#             return jsonify({"message": "Video is being processed in the background."}), 202

#     except Exception as e:
#         return jsonify({"error": str(e)}), 500


# def transcribe_audio(video_path):
#     """
#     Transcribe audio directly from a video file using Whisper AI.
#     """
#     try:
#         print(f"Transcribing video: {video_path}")
#         result = whisper_model.transcribe(video_path)
#         return result['text']
#     except Exception as e:
#         print(f"Error in transcription: {e}")
#         return None


# def query_gemini_api(transcription):
#     """
#     Send transcription text to Gemini API and fetch structured recipe information.
#     """
#     try:
#         # Define the structured prompt
#         prompt = (
#             "Analyze the provided cooking video transcription and extract the following structured information:\n"
#             "1. Recipe Name: Identify the name of the dish being prepared.\n"
#             "2. Ingredients List: Extract a detailed list of ingredients with their respective quantities (if mentioned).\n"
#             "3. Steps for Preparation: Provide a step-by-step breakdown of the recipe's preparation process, organized and numbered sequentially.\n"
#             "4. Cooking Techniques Used: Highlight the cooking techniques demonstrated in the video, such as searing, blitzing, wrapping, etc.\n"
#             "5. Equipment Needed: List all tools, appliances, or utensils mentioned, e.g., blender, hot pan, cling film, etc.\n"
#             "6. Nutritional Information (if inferred): Provide an approximate calorie count or nutritional breakdown based on the ingredients used.\n"
#             "7. Serving size: In count of people or portion size.\n"
#             "8. Special Notes or Variations: Include any specific tips, variations, or alternatives mentioned.\n"
#             "9. Festive or Thematic Relevance: Note if the recipe has any special relevance to holidays, events, or seasons.\n"
#             f"Text: {transcription}\n"
#         )

#         payload = {
#             "contents": [
#                 {"parts": [{"text": prompt}]}
#             ]
#         }
#         headers = {"Content-Type": "application/json"}

#         # Send request to Gemini API
#         response = requests.post(
#             f"{GEMINI_API_ENDPOINT}?key={GEMINI_API_KEY}",
#             json=payload,
#             headers=headers
#         )
#         response.raise_for_status()

#         # Extract and return the structured data
#         data = response.json()
#         return data.get("candidates", [{}])[0].get("content", {}).get("parts", [{}])[0].get("text", "No result found")

#     except requests.exceptions.RequestException as e:
#         print(f"Error querying Gemini API: {e}")
#         return {"error": str(e)}


# if __name__ == '__main__':
#     app.run(debug=True)