Spaces:
Build error
Build error
Commit
·
ad298ab
1
Parent(s):
c85077c
ddssd
Browse files- test_llama_omni_api.py +5 -5
- tests/README.md +88 -0
- test.mp3 → tests/test.mp3 +0 -0
- tests/test_llama_omni_api.py +155 -0
test_llama_omni_api.py
CHANGED
@@ -1,7 +1,7 @@
|
|
1 |
#!/usr/bin/env python3
|
2 |
"""
|
3 |
Test script for LLaMA-Omni API on Hugging Face Spaces.
|
4 |
-
This script sends a text message to the LLaMA-Omni2 API and saves the response.
|
5 |
"""
|
6 |
|
7 |
import os
|
@@ -10,7 +10,7 @@ from pathlib import Path
|
|
10 |
from gradio_client import Client
|
11 |
|
12 |
# API endpoint
|
13 |
-
API_URL = "https://marcosremar2-llama-omni.hf.space"
|
14 |
|
15 |
# Input and output paths
|
16 |
INPUT_AUDIO_PATH = "/Users/marcos/Documents/projects/test/whisper-realtime/llama-omni/llama-omni/test.mp3"
|
@@ -43,14 +43,14 @@ def main():
|
|
43 |
print("\nUsing the text generation endpoint (/lambda_1)...")
|
44 |
|
45 |
# Create a text prompt describing the audio
|
46 |
-
prompt = """This is a test of the LLaMA-Omni2 API.
|
47 |
Please respond with a sample of what you can do as an AI assistant."""
|
48 |
|
49 |
# Submit the text to the API
|
50 |
print(f"Sending text prompt: '{prompt[:50]}...'")
|
51 |
job = client.submit(
|
52 |
prompt,
|
53 |
-
"LLaMA-Omni2-
|
54 |
api_name="/lambda_1"
|
55 |
)
|
56 |
|
@@ -76,7 +76,7 @@ def main():
|
|
76 |
print(f"Error during API request: {str(e)}")
|
77 |
print("This could be because the Space is currently sleeping and needs time to wake up.")
|
78 |
print("Try accessing the Space directly in a browser first: " + API_URL)
|
79 |
-
print("\nNote: This API
|
80 |
print("To work with audio, you would need to first transcribe the audio using a service like Whisper,")
|
81 |
print("then send the transcribed text to this API.")
|
82 |
|
|
|
1 |
#!/usr/bin/env python3
|
2 |
"""
|
3 |
Test script for LLaMA-Omni API on Hugging Face Spaces.
|
4 |
+
This script sends a text message to the LLaMA-Omni2-0.5B API and saves the response.
|
5 |
"""
|
6 |
|
7 |
import os
|
|
|
10 |
from gradio_client import Client
|
11 |
|
12 |
# API endpoint
|
13 |
+
API_URL = "https://marcosremar2-llama-omni.hf.space" # Gradio Space URL
|
14 |
|
15 |
# Input and output paths
|
16 |
INPUT_AUDIO_PATH = "/Users/marcos/Documents/projects/test/whisper-realtime/llama-omni/llama-omni/test.mp3"
|
|
|
43 |
print("\nUsing the text generation endpoint (/lambda_1)...")
|
44 |
|
45 |
# Create a text prompt describing the audio
|
46 |
+
prompt = """This is a test of the LLaMA-Omni2-0.5B API.
|
47 |
Please respond with a sample of what you can do as an AI assistant."""
|
48 |
|
49 |
# Submit the text to the API
|
50 |
print(f"Sending text prompt: '{prompt[:50]}...'")
|
51 |
job = client.submit(
|
52 |
prompt,
|
53 |
+
"LLaMA-Omni2-0.5B", # Updated model name
|
54 |
api_name="/lambda_1"
|
55 |
)
|
56 |
|
|
|
76 |
print(f"Error during API request: {str(e)}")
|
77 |
print("This could be because the Space is currently sleeping and needs time to wake up.")
|
78 |
print("Try accessing the Space directly in a browser first: " + API_URL)
|
79 |
+
print("\nNote: This API is for the LLaMA-Omni2-0.5B model and does not directly process audio files.")
|
80 |
print("To work with audio, you would need to first transcribe the audio using a service like Whisper,")
|
81 |
print("then send the transcribed text to this API.")
|
82 |
|
tests/README.md
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Teste LLaMA-Omni2-0.5B no Hugging Face
|
2 |
+
|
3 |
+
Este diretório contém um script simples para testar o modelo LLaMA-Omni2-0.5B implantado no Hugging Face.
|
4 |
+
|
5 |
+
## Pré-requisitos
|
6 |
+
|
7 |
+
Antes de executar o script de teste, certifique-se de ter instalado as dependências necessárias:
|
8 |
+
|
9 |
+
```bash
|
10 |
+
pip install requests
|
11 |
+
```
|
12 |
+
|
13 |
+
Para transcrição de áudio (opcional), você pode instalar o Whisper:
|
14 |
+
|
15 |
+
```bash
|
16 |
+
pip install openai-whisper
|
17 |
+
```
|
18 |
+
|
19 |
+
## Uso
|
20 |
+
|
21 |
+
Você pode executar o script de teste usando o seguinte comando:
|
22 |
+
|
23 |
+
```bash
|
24 |
+
cd tests
|
25 |
+
python test_llama_omni_api.py
|
26 |
+
```
|
27 |
+
|
28 |
+
Por padrão, o script irá:
|
29 |
+
1. Tentar transcrever o arquivo test.mp3 usando Whisper (se disponível)
|
30 |
+
2. Se o Whisper não estiver disponível, usará uma mensagem de teste padrão
|
31 |
+
3. Salvar a transcrição em um arquivo de texto para facilitar a cópia
|
32 |
+
4. Abrir a interface web do LLaMA-Omni2-0.5B no Hugging Face no seu navegador padrão
|
33 |
+
5. Fornecer instruções para teste manual
|
34 |
+
|
35 |
+
### Parâmetros de linha de comando
|
36 |
+
|
37 |
+
O script aceita os seguintes argumentos de linha de comando:
|
38 |
+
|
39 |
+
- `--api-url`: URL da interface Gradio (padrão: https://marcosremar2-llama-omni.hf.space)
|
40 |
+
- `--audio-file`: Caminho para o arquivo de áudio a ser transcrito localmente (padrão: ../test.mp3)
|
41 |
+
- `--text`: Texto para usar diretamente (em vez de transcrever áudio)
|
42 |
+
- `--output-dir`: Diretório para salvar a transcrição (padrão: ../output)
|
43 |
+
|
44 |
+
Exemplos de uso com parâmetros personalizados:
|
45 |
+
|
46 |
+
```bash
|
47 |
+
# Usando entrada de texto direta
|
48 |
+
python test_llama_omni_api.py --text "Olá, esta é uma mensagem de teste para o LLaMA-Omni2-0.5B."
|
49 |
+
|
50 |
+
# Usando um arquivo de áudio personalizado para transcrição
|
51 |
+
python test_llama_omni_api.py --audio-file /caminho/para/seu/audio.mp3
|
52 |
+
```
|
53 |
+
|
54 |
+
## Processo de Teste Manual
|
55 |
+
|
56 |
+
O script facilita o teste manual com o seguinte fluxo de trabalho:
|
57 |
+
|
58 |
+
1. **Transcrição de Áudio**: Se um arquivo de áudio for fornecido, o script tentará transcrevê-lo localmente usando Whisper
|
59 |
+
2. **Preparação do Texto**: O texto transcrito ou fornecido é salvo em um arquivo para fácil cópia
|
60 |
+
3. **Abertura do Navegador**: O script abre a interface web no seu navegador padrão
|
61 |
+
4. **Interação Manual**: Você precisa manualmente:
|
62 |
+
- Copiar o texto do arquivo salvo
|
63 |
+
- Colar no campo "Input Text" na interface web
|
64 |
+
- Clicar no botão "Generate"
|
65 |
+
- Aguardar a resposta
|
66 |
+
- Copiar e salvar a resposta para seus registros
|
67 |
+
|
68 |
+
## Solução de Problemas
|
69 |
+
|
70 |
+
Se encontrar algum problema:
|
71 |
+
|
72 |
+
1. Verifique se a URL da interface web está correta e o serviço está em execução
|
73 |
+
2. Certifique-se de ter uma conexão com a internet
|
74 |
+
3. Se estiver usando transcrição de áudio, certifique-se de que o Whisper esteja instalado corretamente
|
75 |
+
|
76 |
+
## Erros Comuns
|
77 |
+
|
78 |
+
### Dependências Ausentes
|
79 |
+
|
80 |
+
Se você ver erros como `ModuleNotFoundError: No module named 'torch'`, você precisa instalar os pacotes Python necessários:
|
81 |
+
|
82 |
+
```bash
|
83 |
+
pip install openai-whisper
|
84 |
+
```
|
85 |
+
|
86 |
+
### Deploy no Hugging Face
|
87 |
+
|
88 |
+
Este script é apenas para teste do modelo LLaMA-Omni2-0.5B já implantado no Hugging Face. Para fazer o deploy do modelo no Hugging Face Spaces, você só precisa fazer push do seu código para o repositório correspondente no Hugging Face.
|
test.mp3 → tests/test.mp3
RENAMED
File without changes
|
tests/test_llama_omni_api.py
ADDED
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
"""
|
3 |
+
Teste simples para o LLaMA-Omni2-0.5B no Hugging Face
|
4 |
+
Este script transcreve áudio localmente e facilita o teste manual do modelo.
|
5 |
+
"""
|
6 |
+
|
7 |
+
import os
|
8 |
+
import sys
|
9 |
+
import argparse
|
10 |
+
import requests
|
11 |
+
import subprocess
|
12 |
+
import webbrowser
|
13 |
+
from pathlib import Path
|
14 |
+
|
15 |
+
def transcribe_audio_locally(audio_file_path):
|
16 |
+
"""
|
17 |
+
Transcreve áudio localmente usando whisper se disponível
|
18 |
+
Caso contrário, retorna uma mensagem padrão
|
19 |
+
"""
|
20 |
+
try:
|
21 |
+
# Tenta usar whisper CLI se disponível
|
22 |
+
result = subprocess.run(
|
23 |
+
["whisper", audio_file_path, "--model", "tiny", "--output_format", "txt"],
|
24 |
+
capture_output=True,
|
25 |
+
text=True,
|
26 |
+
check=True
|
27 |
+
)
|
28 |
+
transcript_file = f"{os.path.splitext(audio_file_path)[0]}.txt"
|
29 |
+
if os.path.exists(transcript_file):
|
30 |
+
with open(transcript_file, "r") as f:
|
31 |
+
transcript = f.read().strip()
|
32 |
+
print(f"Transcrição: {transcript}")
|
33 |
+
return transcript
|
34 |
+
except (subprocess.CalledProcessError, FileNotFoundError) as e:
|
35 |
+
print(f"Whisper não disponível ou erro: {e}")
|
36 |
+
|
37 |
+
# Mensagem padrão
|
38 |
+
print("Usando mensagem de teste padrão, já que whisper não está disponível")
|
39 |
+
return "Olá, estou testando o modelo LLaMA-Omni2-0.5B. Você pode me responder em português?"
|
40 |
+
|
41 |
+
def check_url_accessibility(url):
|
42 |
+
"""Verifica se a URL é acessível"""
|
43 |
+
try:
|
44 |
+
response = requests.get(url, timeout=10)
|
45 |
+
if response.status_code == 200:
|
46 |
+
return True
|
47 |
+
else:
|
48 |
+
print(f"URL retornou código {response.status_code}")
|
49 |
+
return False
|
50 |
+
except Exception as e:
|
51 |
+
print(f"Erro ao acessar URL: {e}")
|
52 |
+
return False
|
53 |
+
|
54 |
+
def save_transcription_to_file(text, output_dir, filename="transcription.txt"):
|
55 |
+
"""Salva transcrição em arquivo para fácil cópia"""
|
56 |
+
os.makedirs(output_dir, exist_ok=True)
|
57 |
+
filepath = os.path.join(output_dir, filename)
|
58 |
+
|
59 |
+
with open(filepath, "w") as f:
|
60 |
+
f.write(text)
|
61 |
+
|
62 |
+
print(f"Transcrição salva em: {filepath}")
|
63 |
+
return filepath
|
64 |
+
|
65 |
+
def test_llama_omni_manual(api_url, audio_file_path=None, text_input=None, output_dir="./output"):
|
66 |
+
"""
|
67 |
+
Prepara o teste manual do LLaMA-Omni2-0.5B:
|
68 |
+
1. Transcreve áudio localmente (se fornecido)
|
69 |
+
2. Salva o texto em arquivo para fácil cópia
|
70 |
+
3. Abre a interface web para teste manual
|
71 |
+
|
72 |
+
Args:
|
73 |
+
api_url: URL da interface Gradio
|
74 |
+
audio_file_path: Caminho para o arquivo de áudio
|
75 |
+
text_input: Texto para usar diretamente (em vez de transcrever áudio)
|
76 |
+
output_dir: Diretório para salvar a transcrição
|
77 |
+
|
78 |
+
Returns:
|
79 |
+
bool: True se a preparação foi bem-sucedida, False caso contrário
|
80 |
+
"""
|
81 |
+
# Cria diretório de saída se não existir
|
82 |
+
os.makedirs(output_dir, exist_ok=True)
|
83 |
+
|
84 |
+
# Verifica se a URL é acessível
|
85 |
+
print(f"Verificando acessibilidade de {api_url}...")
|
86 |
+
if not check_url_accessibility(api_url):
|
87 |
+
print(f"Aviso: {api_url} não está acessível. Teste manual pode não ser possível.")
|
88 |
+
|
89 |
+
# Obtém texto de entrada da transcrição ou do parâmetro
|
90 |
+
input_text = text_input
|
91 |
+
if not input_text and audio_file_path:
|
92 |
+
input_text = transcribe_audio_locally(audio_file_path)
|
93 |
+
if not input_text:
|
94 |
+
input_text = "Olá, estou testando o modelo LLaMA-Omni2-0.5B. Você pode me responder em português?"
|
95 |
+
|
96 |
+
print(f"Texto para usar: {input_text}")
|
97 |
+
|
98 |
+
# Salva o texto em arquivo para fácil cópia
|
99 |
+
transcript_file = save_transcription_to_file(input_text, output_dir)
|
100 |
+
|
101 |
+
# Instruções para teste manual
|
102 |
+
print("\n" + "=" * 50)
|
103 |
+
print("INSTRUÇÕES PARA TESTE MANUAL")
|
104 |
+
print("=" * 50)
|
105 |
+
print(f"1. A transcrição foi salva em: {transcript_file}")
|
106 |
+
print(f"2. Abrindo {api_url} no navegador...")
|
107 |
+
print("3. Copie o texto do arquivo salvo e cole no campo 'Input Text'")
|
108 |
+
print("4. Clique no botão 'Generate'")
|
109 |
+
print("5. Quando receber a resposta, copie e salve para seus registros")
|
110 |
+
print("=" * 50 + "\n")
|
111 |
+
|
112 |
+
# Abre a URL no navegador padrão
|
113 |
+
try:
|
114 |
+
webbrowser.open(api_url)
|
115 |
+
return True
|
116 |
+
except Exception as e:
|
117 |
+
print(f"Erro ao abrir navegador: {e}")
|
118 |
+
print(f"Por favor, visite manualmente: {api_url}")
|
119 |
+
return False
|
120 |
+
|
121 |
+
def main():
|
122 |
+
parser = argparse.ArgumentParser(description="Teste para LLaMA-Omni2-0.5B no Hugging Face")
|
123 |
+
parser.add_argument("--api-url", type=str, default="https://huggingface.co/ICTNLP/LLaMA-Omni2-0.5B",
|
124 |
+
help="URL da interface Gradio (padrão: https://huggingface.co/ICTNLP/LLaMA-Omni2-0.5B)")
|
125 |
+
parser.add_argument("--audio-file", type=str, default="../test.mp3",
|
126 |
+
help="Caminho para o arquivo de áudio a ser transcrito localmente (opcional)")
|
127 |
+
parser.add_argument("--text", type=str, default=None,
|
128 |
+
help="Texto para usar diretamente (em vez de transcrever áudio)")
|
129 |
+
parser.add_argument("--output-dir", type=str, default="../output",
|
130 |
+
help="Diretório para salvar a transcrição")
|
131 |
+
args = parser.parse_args()
|
132 |
+
|
133 |
+
# Converte caminhos relativos para absolutos
|
134 |
+
if args.audio_file and not os.path.isabs(args.audio_file):
|
135 |
+
if not os.path.exists(args.audio_file):
|
136 |
+
script_dir = os.path.dirname(os.path.abspath(__file__))
|
137 |
+
args.audio_file = os.path.join(script_dir, args.audio_file)
|
138 |
+
|
139 |
+
if args.output_dir and not os.path.isabs(args.output_dir):
|
140 |
+
script_dir = os.path.dirname(os.path.abspath(__file__))
|
141 |
+
args.output_dir = os.path.join(script_dir, args.output_dir)
|
142 |
+
|
143 |
+
# Executa o teste
|
144 |
+
success = test_llama_omni_manual(
|
145 |
+
api_url=args.api_url,
|
146 |
+
audio_file_path=args.audio_file if not args.text else None,
|
147 |
+
text_input=args.text,
|
148 |
+
output_dir=args.output_dir
|
149 |
+
)
|
150 |
+
|
151 |
+
# Sai com código apropriado
|
152 |
+
sys.exit(0 if success else 1)
|
153 |
+
|
154 |
+
if __name__ == "__main__":
|
155 |
+
main()
|