Chord-Bot-API / app.py
kshahnathwani's picture
Update app.py
972e191 verified
raw
history blame
2.95 kB
import gradio as gr
from huggingface_hub import InferenceClient
import os
import traceback
# Styling
fancy_css = """
#main-container {
background-color: #f0f0f0;
font-family: 'Arial', sans-serif;
}
.gradio-container {
max-width: 700px;
margin: 0 auto;
padding: 20px;
background: white;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
border-radius: 10px;
}
.gr-button {
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
padding: 10px 20px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.gr-button:hover {
background-color: #45a049;
}
.gr-chat {
font-size: 16px;
}
#title {
text-align: center;
font-size: 2em;
margin-bottom: 20px;
color: #333;
}
"""
# System prompt specialized for chord bot
CHORD_SYSTEM_PROMPT = """You are a music theory expert specialized in chord identification.
Given a list of notes (like "C E G" or "D F# A C"), identify the chord name.
Always respond with the chord name and a short explanation of the intervals.
"""
# Hugging Face API token (in Space secrets)
HF_TOKEN = os.environ.get("HF_TOKEN")
# Inference client
client = InferenceClient(token=HF_TOKEN)
def respond(message, history, system_message, max_tokens, temperature, top_p):
if HF_TOKEN is None:
return "⚠️ No HF_TOKEN found. Please add it in your Space secrets."
try:
# Build a simple prompt
prompt = f"{system_message}\nUser: {message}\nAnswer:"
# Raw POST to Hugging Face Inference API
output = client.post_json(
"https://api-inference.huggingface.co/models/gpt2", # ✅ change model here if needed
{
"inputs": prompt,
"parameters": {
"max_new_tokens": max_tokens,
"temperature": temperature,
"top_p": top_p,
},
},
)
# Parse response
if isinstance(output, list) and len(output) > 0 and "generated_text" in output[0]:
response = output[0]["generated_text"]
else:
response = str(output)
return response.strip()
except Exception as e:
tb = traceback.format_exc()
return f"⚠️ Error: {str(e)}\n\nTraceback:\n{tb}"
# Gradio ChatInterface
chatbot = gr.ChatInterface(
fn=respond,
additional_inputs=[
gr.Textbox(value=CHORD_SYSTEM_PROMPT, label="System message"),
gr.Slider(minimum=1, maximum=512, value=128, step=1, label="Max new tokens"),
gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature"),
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p"),
],
type="messages",
)
# Layout
with gr.Blocks(css=fancy_css) as demo:
gr.Markdown("<h1 id='title'>🎶 Chord Bot (API-based) 🎶</h1>")
chatbot.render()
if __name__ == "__main__":
demo.launch()