Spaces:
Sleeping
Sleeping
File size: 4,227 Bytes
08999c8 7898038 ebb01c4 7898038 e26063f 7898038 530b43f 08999c8 ebb01c4 2efce39 e26063f ebb01c4 530b43f ebb01c4 e26063f 530b43f ebb01c4 e26063f 530b43f 7898038 ebb01c4 530b43f 7898038 530b43f 7898038 530b43f 7898038 530b43f e26063f 530b43f e26063f 530b43f dcd38cb 530b43f 08999c8 530b43f c2592ee 530b43f e26063f 530b43f dcd38cb 530b43f 08999c8 530b43f 08999c8 ebb01c4 e26063f 530b43f e26063f 08999c8 530b43f e26063f 08999c8 530b43f ebb01c4 7898038 e26063f | 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 | # import os
# from groq import Groq
# import gradio as gr
# # Initialize client
# client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
# # System prompt
# SYSTEM_PROMPT = {
# "role": "system",
# "content": "You are a helpful, friendly AI assistant."
# }
# # Clean message (IMPORTANT FIX)
# def clean_message(msg):
# return {
# "role": msg.get("role"),
# "content": msg.get("content")
# }
# # Chatbot function
# def chatbot(message, history):
# try:
# messages = [SYSTEM_PROMPT]
# # Limit history
# history = history[-6:] if history else []
# for item in history:
# # Case 1: tuple (user, bot)
# if isinstance(item, (list, tuple)) and len(item) == 2:
# user_msg, bot_msg = item
# if user_msg:
# messages.append({"role": "user", "content": str(user_msg)})
# if bot_msg:
# messages.append({"role": "assistant", "content": str(bot_msg)})
# # Case 2: dict (REMOVE metadata)
# elif isinstance(item, dict):
# if "role" in item and "content" in item:
# messages.append(clean_message(item))
# # Add current message
# messages.append({"role": "user", "content": str(message)})
# # Call Groq
# response = client.chat.completions.create(
# model="llama-3.3-70b-versatile",
# messages=messages,
# temperature=0.7,
# max_tokens=1024,
# )
# return response.choices[0].message.content.strip()
# except Exception as e:
# return f"β οΈ Error: {str(e)}"
# # UI
# demo = gr.ChatInterface(
# fn=chatbot,
# title="π Groq AI Chatbot",
# description="Fast chatbot powered by Groq",
# )
# # Launch
# if __name__ == "__main__":
# demo.launch()
import os
from groq import Groq
import gradio as gr
from PyPDF2 import PdfReader
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
SYSTEM_PROMPT = {
"role": "system",
"content": "You are a helpful AI assistant."
}
# -------- FILE TEXT --------
def get_file_text(file):
if not file:
return ""
try:
if file.name.endswith(".pdf"):
reader = PdfReader(file)
text = ""
for page in reader.pages:
text += page.extract_text() or ""
return text[:1500]
elif file.name.endswith(".txt"):
return file.read().decode("utf-8", errors="ignore")[:1500]
except Exception as e:
return f"(File error: {e})"
return ""
# -------- VOICE (placeholder) --------
def get_voice_text(audio):
if audio:
return "User sent a voice message"
return ""
# -------- MAIN FUNCTION --------
def respond(message, history, file, audio):
# Combine everything into ONE message
file_text = get_file_text(file)
voice_text = get_voice_text(audio)
full_message = message
if file_text:
full_message += f"\n\nπ File:\n{file_text}"
if voice_text:
full_message += f"\n\nπ€ Voice:\n{voice_text}"
# Build messages for Groq
messages = [SYSTEM_PROMPT]
for h in history:
messages.append({"role": "user", "content": h[0]})
messages.append({"role": "assistant", "content": h[1]})
messages.append({"role": "user", "content": full_message})
# Streaming response
stream = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=messages,
stream=True,
)
response = ""
for chunk in stream:
if chunk.choices[0].delta.content:
response += chunk.choices[0].delta.content
yield response
# -------- UI --------
with gr.Blocks(css="""
.gradio-container {background: #0f172a; color: white;}
""") as demo:
gr.Markdown("# π AI Chatbot (Fixed Version)")
gr.Markdown("π¬ Chat + π PDF + π€ Voice")
chatbot = gr.ChatInterface(
fn=respond,
additional_inputs=[
gr.File(file_types=[".pdf", ".txt"]),
gr.Audio(type="filepath")
],
)
# Launch
if __name__ == "__main__":
demo.launch() |