Spaces:
Sleeping
Sleeping
| import os | |
| import pandas as pd | |
| from reportlab.lib.pagesizes import letter | |
| from reportlab.pdfgen import canvas | |
| import openai | |
| import tempfile | |
| from google.cloud import texttospeech | |
| import time | |
| # Configura la variable de entorno para las credenciales de Google Cloud | |
| os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "botidinamix-g.json" | |
| # Instancia el cliente de Text-to-Speech | |
| client = texttospeech.TextToSpeechClient() | |
| # Menú definido directamente en el código | |
| menu = [ | |
| {"item": "Hamburguesa sencilla (200g)", "price": 14000}, | |
| {"item": "Hamburguesa doble (400g)", "price": 19000}, | |
| {"item": "Hamburguesa triple (600g)", "price": 24000}, | |
| {"item": "Hamburguesa napolitana", "price": 18000}, | |
| {"item": "Hamburguesa de la casa", "price": 22000}, | |
| {"item": "Perro caliente sencillo", "price": 11000}, | |
| {"item": "Perro caliente mixto (con tocino, queso y jalapeños)", "price": 16000}, | |
| {"item": "Jalapeños", "price": 2000}, | |
| {"item": "Tocineta", "price": 3000}, | |
| {"item": "Queso cheddar", "price": 3500}, | |
| {"item": "Queso americano", "price": 3500}, | |
| {"item": "Papas fritas naturales", "price": 4000}, | |
| {"item": "Papas fritas con limón", "price": 4500}, | |
| {"item": "Papas fritas con pollo BBQ", "price": 5000}, | |
| {"item": "Papas fritas con jalapeños y queso", "price": 5500}, | |
| {"item": "Papas fritas con tocineta y queso", "price": 6000}, | |
| {"item": "Cerveza Pilsen", "price": 4000}, | |
| {"item": "Cerveza Águila", "price": 5000}, | |
| {"item": "Cerveza Club Social", "price": 7000}, | |
| {"item": "Batido de chocolate", "price": 6000}, | |
| {"item": "Batido de vainilla", "price": 5500}, | |
| {"item": "Batido de fresa", "price": 6500}, | |
| {"item": "Agua mineral con gas", "price": 3000}, | |
| {"item": "Agua aromatizada", "price": 2500}, | |
| {"item": "Leche", "price": 3500}, | |
| {"item": "Jugo natural (en agua o leche)", "price": 4000} | |
| ] | |
| menu_df = pd.DataFrame(menu) | |
| class PedidoTool: | |
| def __init__(self, menu_df): | |
| self.menu_df = menu_df | |
| def tomar_pedido(self, pedido): | |
| items = pedido.split(',') | |
| confirmados = [] | |
| for item in items: | |
| if item.strip() in self.menu_df['item'].values: | |
| confirmados.append(item.strip()) | |
| return confirmados | |
| class OrdenTool: | |
| def __init__(self, menu_df): | |
| self.menu_df = menu_df | |
| def procesar_orden(self, pedido): | |
| items = pedido.split(',') | |
| total = 0 | |
| for item in items: | |
| price = self.menu_df[self.menu_df['item'] == item.strip()]['price'].values[0] | |
| total += price | |
| return total | |
| def generar_pdf_orden(order_details, filepath='orden_compra.pdf'): | |
| c = canvas.Canvas(filepath, pagesize=letter) | |
| width, height = letter | |
| c.drawString(100, height - 100, "Orden de Compra") | |
| y = height - 120 | |
| total = 0 | |
| for item, details in order_details.items(): | |
| c.drawString(100, y, f"{item}: ${details['price']}") | |
| y -= 20 | |
| total += details['price'] | |
| c.drawString(100, y - 20, f"Total: ${total}") | |
| c.save() | |
| return filepath | |
| def obtener_respuesta(pregunta, texto_preprocesado, modelo="gpt-4-turbo", temperatura=0.5): | |
| try: | |
| response = openai.ChatCompletion.create( | |
| model=modelo, | |
| messages=[ | |
| {"role": "system", "content": "Actua como Ana una asesora de ventas del restaurante Sazon Burguer, tienes un tono muy amable y cordial"}, | |
| {"role": "user", "content": f"{pregunta}\n\nContexto: {texto_preprocesado}"} | |
| ], | |
| temperature=temperatura | |
| ) | |
| respuesta = response.choices[0].message['content'].strip() | |
| # Configura la solicitud de síntesis de voz | |
| input_text = texttospeech.SynthesisInput(text=respuesta) | |
| voice = texttospeech.VoiceSelectionParams( | |
| language_code="es-ES", ssml_gender=texttospeech.SsmlVoiceGender.FEMALE, | |
| ) | |
| audio_config = texttospeech.AudioConfig( | |
| audio_encoding=texttospeech.AudioEncoding.MP3 | |
| ) | |
| # Realiza la solicitud de síntesis de voz | |
| response = client.synthesize_speech( | |
| input=input_text, voice=voice, audio_config=audio_config | |
| ) | |
| # Guarda el audio en un archivo temporal | |
| audio_path = tempfile.mktemp(suffix=".mp3") | |
| with open(audio_path, "wb") as audio_file: | |
| audio_file.write(response.audio_content) | |
| return respuesta, audio_path | |
| except openai.OpenAIError as e: | |
| return f"Error al comunicarse con OpenAI: {e}", None | |
| def tomar_pedido_agente(pedido): | |
| pedido_tool = PedidoTool(menu_df) | |
| confirmados = pedido_tool.tomar_pedido(pedido) | |
| return confirmados | |
| def procesar_orden_agente(pedido): | |
| orden_tool = OrdenTool(menu_df) | |
| total = orden_tool.procesar_orden(pedido) | |
| return total | |
| def generar_mensaje_automatico(confirmados): | |
| mensaje = f"¡Gracias por tu pedido! Has ordenado: {', '.join(confirmados)}. ¿Te gustaría agregar algo más a tu pedido? Tenemos opciones deliciosas como papas fritas, batidos y mucho más." | |
| return mensaje | |