Spaces:
Build error
Build error
File size: 4,367 Bytes
9a95252 7b50442 2444ddb 9a95252 29110d2 7b50442 2444ddb 7b50442 2444ddb 9a95252 29110d2 9a95252 2444ddb 7b50442 2444ddb 7b50442 9a95252 7b50442 2444ddb 7b50442 2444ddb 7b50442 9a95252 7b50442 2444ddb |
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 |
# API = "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"
import os
import streamlit as st
from groq import Groq
import pandas as pd
import speech_recognition as sr
import pyttsx3
from tabulate import tabulate # Import tabulate for better table formatting
# API_KEY (Replace with your actual Groq API key)
API = "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"
# Set up the Groq client
client = Groq(api_key=API)
# Function to process user input with Llama model
def process_prompt(prompt, model="llama-3.3-70b-versatile"):
try:
chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": prompt}],
model=model,
stream=False
)
return chat_completion.choices[0].message.content
except Exception as e:
print(f"Error processing prompt: {e}") # Log the error for debugging
return "An error occurred. Please try again later."
# Function to process uploaded files
def process_file(file):
if file.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
data = pd.read_excel(file)
elif file.type == "text/csv":
data = pd.read_csv(file)
else:
return "Unsupported file format."
return data
# Function to generate human-friendly responses for file data
def analyze_file_data(data):
summary = f"File contains {data.shape[0]} rows and {data.shape[1]} columns."
response = f"""
**File Analysis:**
- π Total Rows: {data.shape[0]}
- π Total Columns: {data.shape[1]}
- First Few Rows:
{tabulate.tabulate(data.head(), headers='keys', tablefmt='pipe')} # Use tabulate for better table formatting
"""
return response
# Function for speech-to-text
def speech_to_text():
recognizer = sr.Recognizer()
with sr.Microphone() as source:
st.write("ποΈ Listening...")
audio = recognizer.listen(source)
try:
return recognizer.recognize_google(audio)
except sr.UnknownValueError:
return "Sorry, I didn't catch that."
# Function for text-to-speech
def text_to_speech(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
# Function for chat history management (using session_state)
def get_chat_history():
chat_history = st.session_state.get("chat_history", [])
return chat_history
def update_chat_history(user_input, response):
chat_history = get_chat_history()
chat_history.append(("User", user_input))
chat_history.append(("Bot", response))
st.session_state["chat_history"] = chat_history
# Streamlit UI
def chatbot_ui():
st.title("π’ Real-Time AI Chatbot")
# File upload feature
st.sidebar.header("π File Management")
uploaded_file = st.sidebar.file_uploader("Upload a file (CSV/Excel)", type=["csv", "xlsx"])
if uploaded_file:
data = process_file(uploaded_file)
st.sidebar.write(analyze_file_data(data))
if st.sidebar.button("Delete File"):
uploaded_file = None
st.sidebar.write("File deleted.")
# Chat section
st.header("π¬ Chat Section")
chat_history = get_chat_history()
with st.form("chat_form", clear_on_submit=True):
user_input = st.text_input("Type your message or prompt here...")
submitted = st.form_submit_button("Send")
if submitted and user_input:
response = process_prompt(user_input)
update_chat_history(user_input, response)
# Display chat history
for sender, message in chat_history:
if sender == "User":
st.write(f"**π€ You:** {message}")
else:
st.write(f"**π€ Bot:** {message}")
# Save/download chat
if st.button("Download Chat"):
chat_file = "\n".join([f"{sender}: {message}" for sender, message in chat_history])
st.download_button("Download", chat_file, "chat_history.txt", "text/plain")
# Speech-to-Text Section
st.header("ποΈ Speech-to-Text")
if st.button("Start Speech Recognition"):
st.write(f"**π You said:** {speech_to_text()}")
# Text-to-Speech Section
st.header("π Text-to-Speech")
tts_text = st.text_input("Enter text to convert to speech:")
if st.button("Speak Text"):
text_to_speech(tts_text)
if __name__ == "__main__":
chatbot_ui() |