File size: 4,244 Bytes
aa99d75
 
 
 
 
 
 
e45a5c4
aa99d75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4dbe8ce
aa99d75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e45a5c4
aa99d75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f83431f
0959063
 
aa99d75
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from gradio_unifiedaudio import UnifiedAudio
from huggingface_hub import InferenceClient
from transformers import pipeline
import torch
import tempfile
import subprocess
import spaces

MODEL_NAME = "openai/whisper-large-v3"
BATCH_SIZE = 8
FILE_LIMIT_MB = 1000
YT_LENGTH_LIMIT_S = 3600

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Initialize ASR pipeline
asr_pipe = pipeline(
    task="automatic-speech-recognition",
    model=MODEL_NAME,
    chunk_length_s=30,
    device=device,
)

# Initialize Mistral model client
client1 = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
system_instructions1 = "[SYSTEM] Answer as Real Jarvis JARVIS, Made by 'Tony Stark', Keep conversation very short, clear, friendly and concise. The text provided is a request for a specific type of response from you, the virtual assistant. The request asks you to provide friendly responses as if You are the character Jarvis, made by 'Tony Stark.' The expectation is that I will avoid introductions and start answering the query directly, elaborating on all aspects of the request. As an AI-powered assistant, your task is to generate responses that appear as if they are created by the user and not an AI-powered assistant. [USER]"

# History of interactions
history = []


def transcribe(inputs, task="translate"):
    if inputs is None:
        raise ValueError("No audio file submitted! Please record an audio file before submitting your request.")

    text = asr_pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
    return text

def model(text):
    generate_kwargs = dict(
        temperature=0.7,
        max_new_tokens=512,
        top_p=0.95,
        repetition_penalty=1,
        do_sample=True,
        seed=42,
    )
    
    formatted_prompt = system_instructions1 + text + "[JARVIS]"
    stream = client1.text_generation(
        formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
    output = ""
    for response in stream:
        if not response.token.text == "</s>":
            output += response.token.text
    return output



@spaces.GPU
def process_audio(audio):
    if not audio:
        return "Please record an audio.", None

    # Provide user feedback
    print("Processing audio...")

    text = transcribe(audio)
    print("Whisper Response -> ", text)
    
    history.append(text)
    history_text = " ".join(history)

    mistral_response = model(history_text)
    print("Mistral Response -> ", mistral_response)

    with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
        tmp_path = tmp_file.name

    command = ["edge-tts", "-t", mistral_response, "--write-media", tmp_path]
    print(' '.join(command))

    result = subprocess.run(command, capture_output=True, text=True)

    if result.returncode == 0:
        print("Command executed successfully.")
    else:
        print(f"Command failed with return code {result.returncode}")
        print(f"Error message: {result.stderr}")
 
    return mistral_response,tmp_path

def clear_audio(audio):
    return UnifiedAudio(value=None),UnifiedAudio(value=None)


DESCRIPTION = """ # <center><b>Voice-Mistral-Voice ๐Ÿค—</b></center>
        ### <center>Voice-Mistral-Voice</center>
        """

MORE = """ ## TRY Other Models
        ###  https://huggingface.co/spaces/KingNish/Instant-Video
        ### Instant Image: 4k images in 5 Second -> https://huggingface.co/spaces/KingNish/Instant-Image
        """

BETA = """ ### Voice Chat (BETA)"""

FAST = """## Fastest Model"""

with gr.Blocks() as demo:
    gr.Markdown(DESCRIPTION)

    with gr.Row():
        audio_input = UnifiedAudio(sources="microphone", type="filepath", image="./robot.png")
        output_audio = UnifiedAudio(sources="microphone", type="filepath", image="./logo.png")
    audio_text = gr.Text()
    gr.Markdown(FAST)
    clear_audio_button = gr.Button("Record Again")
    audio_input.change(process_audio, inputs=audio_input, outputs=[audio_text,output_audio])
    clear_audio_button.click(clear_audio, inputs=None, outputs=[audio_input, output_audio])

gr.Markdown(MORE)

if __name__ == '__main__':
    demo.queue(max_size=200).launch()