from flask import Flask, request, redirect, url_for
from werkzeug.utils import secure_filename
import os
from pydub import AudioSegment
from google.cloud import storage
from google.cloud import speech
from dotenv import load_dotenv
import pymysql
import openai


app = Flask(__name__)

# Cargar las variables de entorno
load_dotenv()
google_cloud_api_key = os.getenv('GOOGLE_CLOUD_API_KEY')
openai_api_key = os.getenv('OPENAI_API_KEY')
openai.api_key = openai_api_key

ffmpeg_binaries_path = '/home/andrespa/.local/share/ffmpeg-downloader/ffmpeg'
os.environ["PATH"] += os.pathsep + ffmpeg_binaries_path

# Configura expl¨ªcitamente la ruta de los ejecutables de FFmpeg para PyDub
AudioSegment.ffmpeg = os.path.join(ffmpeg_binaries_path, 'ffmpeg')
AudioSegment.ffprobe = os.path.join(ffmpeg_binaries_path, 'ffprobe')

UPLOAD_FOLDER = '/home/andrespa/audioentrenador/subidos'
ALLOWED_EXTENSIONS = {'wav', 'mp3', 'flac'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def convert_to_flac(input_path):
    ext = input_path.split('.')[-1].lower()
    if ext not in ['mp3', 'wav']:
        return None

    output_path = input_path.rsplit('.', 1)[0] + '.flac'
    audio = AudioSegment.from_file(input_path, format=ext)
    audio.export(output_path, format='flac')
    return output_path

def upload_to_gcs(bucket_name, source_file_name, destination_blob_name):
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)
    blob.upload_from_filename(source_file_name)
    print(f"Archivo {source_file_name} subido a {destination_blob_name}.")
    return f'gs://{bucket_name}/{destination_blob_name}'

def transcribe_gcs(gcs_uri):
    client = speech.SpeechClient()
    audio = speech.RecognitionAudio(uri=gcs_uri)
    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.FLAC, 
        language_code='en-US'
    )
    operation = client.long_running_recognize(config, audio)
    response = operation.result(timeout=90)
    transcript = ''
    for result in response.results:
        transcript += result.alternatives[0].transcript
    return transcript

def ask_chatgpt(transcript):
    response = openai.Completion.create(engine="text-davinci-003", prompt=f"{transcript}\n\nMejorar redacciÃ³n:", max_tokens=150)
    return response.choices[0].text.strip()

def save_to_database(transcript, chatgpt_response):
    connection = pymysql.connect(host='tu_host', user='tu_usuario', password='tu_contraseÃ±a', db='apmaudio', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
    try:
        with connection.cursor() as cursor:
            sql = "INSERT INTO `respuestas` (`transcript`, `response`) VALUES (%s, %s)"
            cursor.execute(sql, (transcript, chatgpt_response))
        connection.commit()
    finally:
        connection.close()

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '' or not allowed_file(file.filename):
            return redirect(request.url)
        filename = secure_filename(file.filename)
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(file_path)

        converted_file_path = convert_to_flac(file_path)
        if converted_file_path:
            gcs_uri = upload_to_gcs('repositorio-audio', converted_file_path, os.path.basename(converted_file_path))
            transcript = transcribe_gcs(gcs_uri)
            chatgpt_response = ask_chatgpt(transcript)
            save_to_database(transcript, chatgpt_response)

        return redirect(url_for('upload_file', filename=filename))

    return '''
    <!doctype html>
    <title>Subir nuevo archivo</title>
    <h1>Subir nuevo archivo</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Subir>
    </form>
    '''

if __name__ == '__main__':
    app.run(debug=True)
