MarketMate / app.py
amir22010's picture
Update app.py
98cb312 verified
raw
history blame
7.63 kB
import gradio as gr
from llama_cpp import Llama
import os
from groq import Groq
import numpy as np
import wave
#tts
from balacoon_tts import TTS
from threading import Lock
from huggingface_hub import hf_hub_download, list_repo_files
import io
import tempfile
#tts cpu model
tts_model_str = "en_us_hifi_jets_cpu.addon"
for name in list_repo_files(repo_id="balacoon/tts"):
if name == tts_model_str:
if not os.path.isfile(os.path.join(os.getcwd(), name)):
hf_hub_download(
repo_id="balacoon/tts",
filename=name,
local_dir=os.getcwd(),
)
tts = TTS(os.path.join(os.getcwd(), tts_model_str))
def text_to_speech(text):
with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_file:
if len(text) > 1024:
# truncate the text
text_str = text[:1024]
else:
text_str = text
with locker:
global tts
samples = tts.synthesize(text_str, "92")
output_file = temp_file.name
with wave.open(f"{output_file}", "w") as fp:
fp.setparams((1, 2, tts.get_sampling_rate(), len(samples), "NONE", "NONE"))
samples = np.ascontiguousarray(samples)
fp.writeframes(samples)
return output_file
def combine_audio_files(audio_files):
data= []
outfile = "sounds.wav"
for infile in audio_files:
w = wave.open(infile, 'rb')
data.append([w.getparams(), w.readframes(w.getnframes())] )
w.close()
os.remove(infile) # Remove temporary files
output = wave.open(outfile, 'wb')
output.setparams(data[0][0])
for i in range(len(data)):
output.writeframes(data[i][1])
output.close()
return outfile
#client
client = Groq(
api_key=os.getenv("GROQ_API_KEY"),
)
llm = Llama.from_pretrained(
repo_id="amir22010/fine_tuned_product_marketing_email_gemma_2_9b_q4_k_m", #custom fine tuned model
filename="unsloth.Q4_K_M.gguf", #model file name
cache_dir=os.path.abspath(os.getcwd()),
n_ctx=2048,
n_batch=126,
verbose=False
)
# locker that disallow access to the tts object from more then one thread
locker = Lock()
#guardrail model
guard_llm = "llama-3.1-8b-instant"
#marketing prompt
marketing_email_prompt = """Below is a product and description, please write a marketing email for this product.
### Product:
{}
### Description:
{}
### Marketing Email:
{}"""
#gaurdrails prompt
guardrail_prompt = """You're given a list of moderation categories as below:
- illegal: Illegal activity.
- child abuse: child sexual abuse material or any content that exploits or harms children.
- hate violence harassment: Generation of hateful, harassing, or violent content: content that expresses, incites, or promotes hate based on identity, content that intends to harass, threaten, or bully an individual, content that promotes or glorifies violence or celebrates the suffering or humiliation of others.
- malware: Generation of malware: content that attempts to generate code that is designed to disrupt, damage, or gain unauthorized access to a computer system.
- physical harm: activity that has high risk of physical harm, including: weapons development, military and warfare, management or operation of critical infrastructure in energy, transportation, and water, content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders.
- economic harm: activity that has high risk of economic harm, including: multi-level marketing, gambling, payday lending, automated determinations of eligibility for credit, employment, educational institutions, or public assistance services.
- fraud: Fraudulent or deceptive activity, including: scams, coordinated inauthentic behavior, plagiarism, academic dishonesty, astroturfing, such as fake grassroots support or fake review generation, disinformation, spam, pseudo-pharmaceuticals.
- adult: Adult content, adult industries, and dating apps, including: content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual services (excluding sex education and wellness), erotic chat, pornography.
- political: Political campaigning or lobbying, by: generating high volumes of campaign materials, generating campaign materials personalized to or targeted at specific demographics, building conversational or interactive systems such as chatbots that provide information about campaigns or engage in political advocacy or lobbying, building products for political campaigning or lobbying purposes.
- privacy: Activity that violates people's privacy, including: tracking or monitoring an individual without their consent, facial recognition of private individuals, classifying individuals based on protected characteristics, using biometrics for identification or assessment, unlawful collection or disclosure of personal identifiable information or educational, financial, or other protected records.
- unqualified law: Engaging in the unauthorized practice of law, or offering tailored legal advice without a qualified person reviewing the information.
- unqualified financial: Offering tailored financial advice without a qualified person reviewing the information.
- unqualified health: Telling someone that they have or do not have a certain health condition, or providing instructions on how to cure or treat a health condition.
Please classify the following user prompt into one of these categories, and answer with that single word only.
If the user prompt does not fall within these categories, is safe and does not need to be moderated, please answer "not moderated".
user prompt: {}
"""
async def greet(product,description):
user_reques = marketing_email_prompt.format(
product, # product
description, # description
"", # output - leave this blank for generation!
)
messages = [
{
"role": "system",
"content": "Your role is to assess whether the user prompt is moderate or not.",
},
{"role": "user", "content": guardrail_prompt.format(user_reques)},
]
response = client.chat.completions.create(model=guard_llm, messages=messages, temperature=0)
if response.choices[0].message.content != "not moderated":
a_list = ["Sorry, I can't proceed for generating marketing email. Your content needs to be moderated first. Thank you!"]
processed_audio = combine_audio_files([text_to_speech(a_list[0])])
yield processed_audio, a_list[0]
else:
output = llm.create_chat_completion(
messages=[
{
"role": "system",
"content": "Your go-to Email Marketing Guru - I'm here to help you craft short and concise compelling campaigns, boost conversions, and take your business to the next level.",
},
{"role": "user", "content": user_reques},
],
max_tokens=2048,
temperature=0.7,
stream=True
)
partial_message = ""
audio_list = []
for chunk in output:
delta = chunk['choices'][0]['delta']
if 'content' in delta:
audio_list = audio_list + [text_to_speech(delta.get('content', ''))]
processed_audio = combine_audio_files(audio_list)
partial_message = partial_message + delta.get('content', '')
yield processed_audio, partial_message
audio = gr.Audio()
demo = gr.Interface(fn=greet, inputs=["text","text"], concurrency_limit=10, outputs=[audio,"text"])
demo.launch()