Segizu commited on
Commit
900f49a
1 Parent(s): ac95619

Primer_commit

Browse files
Files changed (2) hide show
  1. app.py +127 -47
  2. requirements.txt +2 -9
app.py CHANGED
@@ -1,53 +1,133 @@
 
 
1
  import gradio as gr
2
- import torchaudio
3
  import torch
4
- from fairseq import checkpoint_utils
5
- import numpy as np
6
- import tempfile
7
- import os
8
-
9
- # Verificar si CUDA est谩 disponible
10
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
- print(f"Usando {device} para la clonaci贸n de voz")
12
-
13
- # Cargar el modelo en GPU si est谩 disponible
14
- models, cfg, task = checkpoint_utils.load_model_ensemble_and_task(["https://dl.fbaipublicfiles.com/vits/model.pt"])
15
- model = models[0].to(device)
16
- model.eval()
17
-
18
- def clone_voice(reference_audio, text):
19
- # Convertir el audio de referencia a tensor
20
- waveform, sample_rate = torchaudio.load(reference_audio.name)
21
-
22
- # Normalizar el audio de referencia
23
- waveform = waveform.mean(dim=0) # Convertir a mono
24
- waveform = torchaudio.transforms.Resample(sample_rate, 22050)(waveform) # Asegurar 22.05 kHz
25
-
26
- # Convertir el audio a tensor en la GPU si est谩 disponible
27
- waveform = waveform.unsqueeze(0).to(device)
28
-
29
- # Extraer la huella de voz del hablante
30
- speaker_embedding = model.get_speaker_embedding(waveform)
31
-
32
- # Generar la voz clonada
33
- synthesized_waveform = model.synthesize(text, speaker_embedding)
34
-
35
- # Pasar el audio generado a la CPU para guardarlo
36
- synthesized_waveform = synthesized_waveform.cpu()
37
 
38
- # Guardar temporalmente el audio generado
39
- output_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
40
- torchaudio.save(output_file.name, synthesized_waveform, 22050)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- return output_file.name
43
-
44
- # Crear interfaz Gradio
45
- interface = gr.Interface(
46
- fn=clone_voice,
47
- inputs=[gr.Audio(type="file"), gr.Textbox(label="Texto a sintetizar")],
48
- outputs=gr.Audio(label="Voz Clonada"),
49
- title="Clonaci贸n de Voz con GPU",
50
- description="Sube un audio de referencia y escribe un texto para clonarlo con aceleraci贸n en GPU (si est谩 disponible)."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  )
52
 
53
- interface.launch()
 
 
1
+ import datetime
2
+ import requests
3
  import gradio as gr
 
4
  import torch
5
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
6
+
7
+ # Detectar si hay GPU disponible
8
+ device = 0 if torch.cuda.is_available() else -1
9
+
10
+ # Cargar el modelo y el tokenizador en GPU (si est谩 disponible)
11
+ model_name = "microsoft/Phi-4-mini-instruct"
12
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
13
+ model = AutoModelForCausalLM.from_pretrained(model_name)
14
+ if device == 0:
15
+ model.to("cuda")
16
+
17
+ # Crear un pipeline de generaci贸n de texto utilizando GPU (si es posible)
18
+ generator = pipeline("text-generation", model=model, tokenizer=tokenizer, device=device)
19
+
20
+ # Funci贸n para obtener las reservaciones de hotel filtradas por t铆tulo
21
+ def get_hotel_reservations(title_filter):
22
+ url = "http://127.0.0.1:4000/api/accommodations"
23
+ try:
24
+ response = requests.get(url)
25
+ if response.status_code == 200:
26
+ data = response.json() # Se espera que 'data' sea una lista de reservaciones
27
+ summary = "Reservaciones de Hotel:\n\n"
28
+ found = False
29
+ for reservation in data:
30
+ hotel_title = reservation.get("title", "N/A")
31
+ # Filtrar solo las reservaciones que contengan el filtro en el t铆tulo
32
+ if title_filter.lower() not in hotel_title.lower():
33
+ continue
 
 
 
 
34
 
35
+ found = True
36
+ hotel_id = reservation.get("id", "N/A")
37
+
38
+ address = reservation.get("address", {})
39
+ street = address.get("street", "N/A")
40
+ zip_code = address.get("zip_code", "N/A")
41
+ latitude = address.get("latitude", "N/A")
42
+ longitude = address.get("longitude", "N/A")
43
+
44
+ guests = reservation.get("guests", {})
45
+ adult = guests.get("adult", "N/A")
46
+ child = guests.get("child", "N/A")
47
+
48
+ price = reservation.get("price", "N/A")
49
+
50
+ summary += (
51
+ f"Reservaci贸n {hotel_id}:\n"
52
+ f" - Hotel: {hotel_title}\n"
53
+ f" - Direcci贸n: {street}, C贸digo Postal: {zip_code}\n"
54
+ f" (Latitud: {latitude}, Longitud: {longitude})\n"
55
+ f" - Hu茅spedes: {adult} adultos, {child} ni帽os\n"
56
+ f" - Precio: {price}\n\n"
57
+ )
58
+ if not found:
59
+ summary += f"No se encontraron reservaciones que coincidan con el filtro '{title_filter}'.\n"
60
+ return summary
61
+ else:
62
+ return "Lo sentimos, no se pudieron obtener las reservaciones de hotel."
63
+ except Exception as e:
64
+ return f"Error al conectar con la API: {e}"
65
+
66
+ # Diccionario que asocia nombres de funciones a sus implementaciones
67
+ function_map = {
68
+ "get_hotel_reservations": get_hotel_reservations,
69
+ }
70
+
71
+ # Definir la herramienta para function calling (煤til para documentar la funci贸n)
72
+ tools = [
73
+ {
74
+ "type": "function",
75
+ "function": {
76
+ "name": "get_hotel_reservations",
77
+ "description": "Obtiene una lista de reservaciones de hotel filtradas por un t铆tulo. El par谩metro 'title' permite especificar parte del nombre del hotel o regi贸n.",
78
+ "parameters": {
79
+ "type": "object",
80
+ "properties": {
81
+ "title": {
82
+ "type": "string",
83
+ "description": "Parte del nombre del hotel o regi贸n, e.g., Medell铆n, Bogot谩, Cartagena"
84
+ }
85
+ },
86
+ "required": ["title"]
87
+ }
88
+ }
89
+ }
90
+ ]
91
+
92
+ def process_instruction(instruction: str):
93
+ """
94
+ Env铆a la instrucci贸n al modelo y verifica si se debe llamar a una funci贸n.
95
+ Se espera que el modelo devuelva una cadena que contenga un llamado a funci贸n en el siguiente formato:
96
+ "Llamada a funci贸n: get_hotel_reservations(Bogot谩)"
97
+ """
98
+ output = ""
99
+ result = generator(instruction, max_length=150)[0]['generated_text']
100
+ output += "Respuesta generada:\n" + result + "\n\n"
101
 
102
+ if "Llamada a funci贸n:" in result:
103
+ try:
104
+ # Extraer la parte de la cadena que contiene el llamado a funci贸n
105
+ start_index = result.find("Llamada a funci贸n:") + len("Llamada a funci贸n:")
106
+ # Se asume que el llamado est谩 en una 煤nica l铆nea, por ejemplo: get_hotel_reservations(Bogot谩)
107
+ call_str = result[start_index:].strip().split()[0]
108
+ func_name, params = call_str.split("(", 1)
109
+ params = params.rstrip(")")
110
+ func_name = func_name.strip()
111
+ params = params.strip()
112
+
113
+ if func_name in function_map:
114
+ function_result = function_map[func_name](params)
115
+ output += "Resultado de la funci贸n:\n" + str(function_result)
116
+ else:
117
+ output += "Funci贸n no encontrada: " + func_name
118
+ except Exception as e:
119
+ output += "Error al procesar la llamada a funci贸n: " + str(e)
120
+ else:
121
+ output += "No se encontr贸 ninguna llamada a funci贸n en la respuesta."
122
+ return output
123
+
124
+ # Crear una interfaz Gradio para interactuar con el sistema
125
+ iface = gr.Interface(
126
+ fn=process_instruction,
127
+ inputs=gr.Textbox(lines=5, placeholder="Escribe tu instrucci贸n aqu铆...", label="Instrucci贸n"),
128
+ outputs="text",
129
+ title="Demo de Function Calling con Phi-4-mini-instruct (GPU)"
130
  )
131
 
132
+ if __name__ == "__main__":
133
+ iface.launch()
requirements.txt CHANGED
@@ -1,11 +1,4 @@
1
  gradio
2
- torchaudio
3
  torch
4
- cython
5
- numpy
6
- sacrebleu
7
- sentencepiece
8
- regex
9
- tqdm
10
- bitarray
11
- fairseq
 
1
  gradio
 
2
  torch
3
+ transformers
4
+ requests