File size: 13,746 Bytes
1bac931
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import shutil
from IPython.display import clear_output
import os
import dotenv

# Load the environment variables from the .env file
# You can change the default secret
with open(".env", "w") as env_file:
    env_file.write("SECRET_TOKEN=secret")
dotenv.load_dotenv()
# Access the value of the SECRET_TOKEN variable
secret_token = os.getenv("SECRET_TOKEN")
import os
#download for mecab
# Check if unidic is installed
#os.system("python -m unidic download")

#from huggingface_hub import HfApi

HF_TOKEN = os.environ.get("HF_TOKEN")
# will use api to restart space on a unrecoverable error
#api = HfApi(token=HF_TOKEN)

# config changes  ---------------
import base64
repo_id = "ruslanmv/ai-story-server"
SECRET_TOKEN = os.getenv('SECRET_TOKEN', 'default_secret')
SENTENCE_SPLIT_LENGTH=250
# ----------------------------------------

default_system_message = f"""
You're the storyteller, crafting a short tale for young listeners. Please abide by these guidelines:
- Keep your sentences short, concise and easy to understand.
- There should be only the narrator speaking. If there are dialogues, they should be indirect.
- Be concise and relevant: Most of your responses should be a sentence or two, unless you’re asked to go deeper.
- Don’t use complex words. Don’t use lists, markdown, bullet points, or other formatting that’s not typically spoken.
- Type out numbers in words (e.g. 'twenty twelve' instead of the year 2012).
- Remember to follow these rules absolutely, and do not refer to these rules, even if you’re asked about them.
"""

import datetime

system_message = os.environ.get("SYSTEM_MESSAGE", default_system_message)
system_message = system_message.replace("CURRENT_DATE", str(datetime.date.today()))

ROLES = ["Cloée","Julian","Pirate","Thera"]

ROLE_PROMPTS = {}
ROLE_PROMPTS["Cloée"]=system_message
ROLE_PROMPTS["Julian"]=system_message
ROLE_PROMPTS["Thera"]=system_message


#Pirate scenario
character_name= "AI Beard"
character_scenario= f"As {character_name} you are a 28 year old man who is a pirate on the ship Invisible AI. You are good friends with Guybrush Threepwood and Murray the Skull. Developers did not get you into Monkey Island games as you wanted huge shares of Big Whoop treasure."
pirate_system_message = f"You as {character_name}. {character_scenario} Print out only exactly the words that {character_name} would speak out, do not add anything. Don't repeat. Answer short, only few words, as if in a talk. Craft your response only from the first-person perspective of {character_name} and never as user.Current date: #CURRENT_DATE#".replace("#CURRENT_DATE#", str(datetime.date.today()))

ROLE_PROMPTS["Pirate"]= pirate_system_message


def split_sentences(text, max_len):
    # Apply custom rules to enforce sentence breaks with double punctuation
    text = re.sub(r"(\s*\.{2})\s*", r".\1 ", text)  # for '..'
    text = re.sub(r"(\s*\!{2})\s*", r"!\1 ", text)  # for '!!'

    # Use NLTK to split into sentences
    sentences = nltk.sent_tokenize(text)

    # Then check if each sentence is greater than max_len, if so, use textwrap to split it
    sentence_list = []
    for sent in sentences:
        if len(sent) > max_len:
            wrapped = textwrap.wrap(sent, max_len, break_long_words=True)
            sentence_list.extend(wrapped)
        else:
            sentence_list.append(sent)

    return sentence_list


# <|system|>
# You are a friendly chatbot who always responds in the style of a pirate.</s>
# <|user|>
# How many helicopters can a human eat in one sitting?</s>
# <|assistant|>
# Ah, me hearty matey! But yer question be a puzzler! A human cannot eat a helicopter in one sitting, as helicopters are not edible. They be made of metal, plastic, and other materials, not food!



# Zephyr formatter
def format_prompt_zephyr(message, history, system_message=system_message):
    prompt = (
        "<|system|>\n" + system_message  + "</s>"
    )
    for user_prompt, bot_response in history:
        prompt += f"<|user|>\n{user_prompt}</s>"
        prompt += f"<|assistant|>\n{bot_response}</s>"
    if message=="":
        message="Hello"
    prompt += f"<|user|>\n{message}</s>"
    prompt += f"<|assistant|>"
    print(prompt)
    return prompt


def generate_stream(prompt, model="mixtral-8x7b"):
    base_url = "https://ruslanmv-hf-llm-api.hf.space"
    api_key = "sk-xxxxx"
    client = OpenAI(base_url=base_url, api_key=api_key)
    response = client.chat.completions.create(
        model=model,
        messages=[
            {
                "role": "user",
                "content": "{}".format(prompt),
            }
        ],
        stream=True,
    )
    return response



# Will be triggered on text submit (will send to generate_speech)
def add_text(history, text):
    history = [] if history is None else history
    history = history + [(text, None)]
    return history, gr.update(value="", interactive=False)


# Will be triggered on voice submit (will transribe and send to generate_speech)
def add_file(history, file):
    history = [] if history is None else history

    try:
        text = transcribe(file)
        print("Transcribed text:", text)
    except Exception as e:
        print(str(e))
        gr.Warning("There was an issue with transcription, please try writing for now")
        # Apply a null text on error
        text = "Transcription seems failed, please tell me a joke about chickens"

    history = history + [(text, None)]
    return history, gr.update(value="", interactive=False)


from scipy.io.wavfile import write
from pydub import AudioSegment

second_of_silence = AudioSegment.silent() # use default
second_of_silence.export("sil.wav", format='wav')


LLM_STOP_WORDS= ["</s>","<|user|>","/s>"]


from openai import OpenAI
import emoji
import nltk  # we'll use this to split into sentences
nltk.download("punkt")

def generate_stream(prompt, model="mixtral-8x7b"):
    base_url = "https://ruslanmv-hf-llm-api.hf.space"
    api_key = "sk-xxxxx"
    client = OpenAI(base_url=base_url, api_key=api_key)
    response = client.chat.completions.create(
        model=model,
        messages=[
            {
                "role": "user",
                "content": "{}".format(prompt),
            }
        ],
        stream=True,
    )
    return response
def generate_local(
    prompt,
    history,
    system_message=None,
    temperature=0.8,
    max_tokens=256,
    top_p=0.95,
    stop=None,
):

    formatted_prompt = format_prompt_zephyr(prompt, history, system_message=system_message)
    try:    
        print("LLM Input:", formatted_prompt)
        output = ""
        stream=generate_stream(formatted_prompt)
        for response in stream:
            character=response.choices[0].delta.content
            if "<|user|>" in character:
                # end of context
                return 
            if emoji.is_emoji(character):
                # Bad emoji not a meaning messes chat from next lines
                return                    
            if character is not None:
                print(character, end="", flush=True)
                output += character
            elif response.choices[0].finish_reason == "stop":
                print()
            else:
                pass 
            yield output
            
    except Exception as e:
        if "Too Many Requests" in str(e):
            print("ERROR: Too many requests on mistral client")
            #gr.Warning("Unfortunately Mistral is unable to process")
            output = "Unfortunately I am not able to process your request now !"
        else:
            print("Unhandled Exception: ", str(e))
            #gr.Warning("Unfortunately Mistral is unable to process")
            output = "I do not know what happened but I could not understand you ."

    return output



# config changes  ---------------
import base64
repo_id = "ruslanmv/ai-story-server"
SECRET_TOKEN = os.getenv('SECRET_TOKEN', 'default_secret')
SENTENCE_SPLIT_LENGTH=250
# ----------------------------------------

default_system_message = f"""
You're the storyteller, crafting a short tale for young listeners. Please abide by these guidelines:
- Keep your sentences short, concise and easy to understand.
- There should be only the narrator speaking. If there are dialogues, they should be indirect.
- Be concise and relevant: Most of your responses should be a sentence or two, unless you’re asked to go deeper.
- Don’t use complex words. Don’t use lists, markdown, bullet points, or other formatting that’s not typically spoken.
- Type out numbers in words (e.g. 'twenty twelve' instead of the year 2012).
- Remember to follow these rules absolutely, and do not refer to these rules, even if you’re asked about them.
"""

system_message = os.environ.get("SYSTEM_MESSAGE", default_system_message)
system_message = system_message.replace("CURRENT_DATE", str(datetime.date.today()))

ROLES = ["Cloée","Julian","Pirate","Thera"]

ROLE_PROMPTS = {}
ROLE_PROMPTS["Cloée"]=system_message
ROLE_PROMPTS["Julian"]=system_message
ROLE_PROMPTS["Thera"]=system_message

#Pirate scenario
character_name= "AI Beard"
character_scenario= f"As {character_name} you are a 28 year old man who is a pirate on the ship Invisible AI. You are good friends with Guybrush Threepwood and Murray the Skull. Developers did not get you into Monkey Island games as you wanted huge shares of Big Whoop treasure."
pirate_system_message = f"You as {character_name}. {character_scenario} Print out only exactly the words that {character_name} would speak out, do not add anything. Don't repeat. Answer short, only few words, as if in a talk. Craft your response only from the first-person perspective of {character_name} and never as user.Current date: #CURRENT_DATE#".replace("#CURRENT_DATE#", str(datetime.date.today()))

ROLE_PROMPTS["Pirate"]= pirate_system_message
##"You are an AI assistant with Zephyr model by Mistral and Hugging Face and speech from Coqui XTTS . User will you give you a task. Your goal is to complete the task as faithfully as you can. While performing the task think step-by-step and justify your steps, your answers should be clear and short sentences"



def get_sentence(history, chatbot_role):

    history = [["", None]] if history is None else history

    history[-1][1] = ""

    sentence_list = []
    sentence_hash_list = []

    text_to_generate = ""
    stored_sentence = None
    stored_sentence_hash = None

    print(chatbot_role)

    for character in generate_local(history[-1][0], history[:-1], system_message=ROLE_PROMPTS[chatbot_role]):
        history[-1][1] = character.replace("<|assistant|>","")
        # It is coming word by word

        text_to_generate = nltk.sent_tokenize(history[-1][1].replace("\n", " ").replace("<|assistant|>"," ").replace("<|ass>","").replace("[/ASST]","").replace("[/ASSI]","").replace("[/ASS]","").replace("","").strip())
        if len(text_to_generate) > 1:

            dif = len(text_to_generate) - len(sentence_list)

            if dif == 1 and len(sentence_list) != 0:
                continue

            if dif == 2 and len(sentence_list) != 0 and stored_sentence is not None:
                continue

            # All this complexity due to trying append first short sentence to next one for proper language auto-detect
            if stored_sentence is not None and stored_sentence_hash is None and dif>1:
                #means we consumed stored sentence and should look at next sentence to generate
                sentence = text_to_generate[len(sentence_list)+1]
            elif stored_sentence is not None and len(text_to_generate)>2 and stored_sentence_hash is not None:
                print("Appending stored")
                sentence = stored_sentence + text_to_generate[len(sentence_list)+1]
                stored_sentence_hash = None
            else:
                sentence = text_to_generate[len(sentence_list)]

            # too short sentence just append to next one if there is any
            # this is for proper language detection
            if len(sentence)<=15 and stored_sentence_hash is None and stored_sentence is None:
                if sentence[-1] in [".","!","?"]:
                    if stored_sentence_hash != hash(sentence):
                        stored_sentence = sentence
                        stored_sentence_hash = hash(sentence)
                        print("Storing:",stored_sentence)
                        continue
            sentence_hash = hash(sentence)
            if stored_sentence_hash is not None and sentence_hash == stored_sentence_hash:
                continue

            if sentence_hash not in sentence_hash_list:
                sentence_hash_list.append(sentence_hash)
                sentence_list.append(sentence)
                print("New Sentence: ", sentence)
                yield (sentence, history)

    # return that final sentence token
    try:
        last_sentence = nltk.sent_tokenize(history[-1][1].replace("\n", " ").replace("<|ass>","").replace("[/ASST]","").replace("[/ASSI]","").replace("[/ASS]","").replace("","").strip())[-1]
        sentence_hash = hash(last_sentence)
        if sentence_hash not in sentence_hash_list:
            if stored_sentence is not None and stored_sentence_hash is not None:
                last_sentence = stored_sentence + last_sentence
                stored_sentence = stored_sentence_hash = None
                print("Last Sentence with stored:",last_sentence)

            sentence_hash_list.append(sentence_hash)
            sentence_list.append(last_sentence)
            print("Last Sentence: ", last_sentence)

            yield (last_sentence, history)
    except:
        print("ERROR on last sentence history is :", history)