Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,39 +1,3 @@
|
|
1 |
-
import os, uuid, requests, gradio as gr, pdfplumber, docx, pandas as pd
|
2 |
-
from PIL import Image
|
3 |
-
import whisper
|
4 |
-
|
5 |
-
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
6 |
-
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
|
7 |
-
MODEL_NAME = "llama3-8b-8192" # Update if using a different model
|
8 |
-
|
9 |
-
def extract_text_from_file(file):
|
10 |
-
if file is None: return ""
|
11 |
-
ext = os.path.splitext(file.name)[-1].lower()
|
12 |
-
try:
|
13 |
-
if ext == ".pdf":
|
14 |
-
with pdfplumber.open(file.name) as pdf:
|
15 |
-
return "\n".join([page.extract_text() or "" for page in pdf.pages])
|
16 |
-
elif ext == ".docx":
|
17 |
-
return "\n".join([p.text for p in docx.Document(file.name).paragraphs])
|
18 |
-
elif ext in [".xls", ".xlsx", ".csv"]:
|
19 |
-
df = pd.read_excel(file.name) if ext != ".csv" else pd.read_csv(file.name)
|
20 |
-
return df.to_string(index=False)
|
21 |
-
elif ext.endswith((".png", ".jpg", ".jpeg", ".bmp")):
|
22 |
-
return "Image uploaded. You can ask about it."
|
23 |
-
elif ext.endswith((".txt", ".py", ".json", ".html", ".md", ".css", ".js")):
|
24 |
-
with open(file.name, encoding="utf-8", errors="ignore") as f: return f.read()
|
25 |
-
except Exception as e:
|
26 |
-
return f"File extraction failed: {e}"
|
27 |
-
|
28 |
-
def transcribe_audio(audio_path):
|
29 |
-
try:
|
30 |
-
if not audio_path: return ""
|
31 |
-
model = whisper.load_model("base")
|
32 |
-
result = model.transcribe(audio_path)
|
33 |
-
return result["text"]
|
34 |
-
except Exception as e:
|
35 |
-
return f"Audio transcription failed: {e}"
|
36 |
-
|
37 |
def chat_response(history, message):
|
38 |
try:
|
39 |
headers = {
|
@@ -51,92 +15,10 @@ def chat_response(history, message):
|
|
51 |
}
|
52 |
|
53 |
response = requests.post(GROQ_API_URL, headers=headers, json=payload)
|
54 |
-
|
55 |
-
return
|
56 |
-
except Exception as e:
|
57 |
-
return f"Groq response failed: {e}"
|
58 |
|
59 |
-
|
60 |
-
|
61 |
-
audio_text = transcribe_audio(audio) if audio else ""
|
62 |
-
full_input = "\n".join([i for i in [msg, file_text, audio_text] if i])
|
63 |
-
if not full_input.strip():
|
64 |
-
return history, gr.Textbox.update(value=""), None, None, gr.Textbox.update(value="No input provided.")
|
65 |
-
reply = chat_response(history, full_input)
|
66 |
-
history.append(("user", msg.strip() or file_text or audio_text))
|
67 |
-
history.append(("assistant", reply))
|
68 |
-
return history, gr.Textbox.update(value=""), None, None, gr.Textbox.update(value="Response generated.")
|
69 |
-
|
70 |
-
def save_chat_history(history):
|
71 |
-
try:
|
72 |
-
os.makedirs("saved_chats", exist_ok=True)
|
73 |
-
title = history[-2][1][:30].replace(" ", "_") if len(history) >= 2 else str(uuid.uuid4())
|
74 |
-
filename = f"saved_chats/{title}.txt"
|
75 |
-
with open(filename, "w", encoding="utf-8") as f:
|
76 |
-
for role, text in history:
|
77 |
-
f.write(f"{role}: {text}\n")
|
78 |
-
return gr.Textbox.update(value="Chat saved successfully.")
|
79 |
except Exception as e:
|
80 |
-
return
|
81 |
-
|
82 |
-
def get_saved_chats():
|
83 |
-
if not os.path.exists("saved_chats"): return []
|
84 |
-
return sorted([f for f in os.listdir("saved_chats") if f.endswith(".txt")])
|
85 |
-
|
86 |
-
def load_selected_chat(filename):
|
87 |
-
filepath = os.path.join("saved_chats", filename)
|
88 |
-
if not os.path.exists(filepath): return [], gr.Textbox.update(value="File not found.")
|
89 |
-
history = []
|
90 |
-
with open(filepath, "r", encoding="utf-8") as f:
|
91 |
-
for line in f:
|
92 |
-
if ":" in line:
|
93 |
-
role, content = line.strip().split(":", 1)
|
94 |
-
history.append((role.strip(), content.strip()))
|
95 |
-
return history, gr.Textbox.update(value=f"Chat '{filename}' loaded.")
|
96 |
-
|
97 |
-
def clear_chat(): return [], gr.Textbox.update(value="Chat cleared. Start fresh!")
|
98 |
-
|
99 |
-
custom_css = """
|
100 |
-
.gradio-container { max-width: 1200px !important; margin: auto !important; }
|
101 |
-
select { appearance: auto !important; }
|
102 |
-
"""
|
103 |
-
|
104 |
-
with gr.Blocks(css=custom_css, title="Neobot - Chatbot") as demo:
|
105 |
-
gr.Markdown("# π€ Neobot - Advanced AI Chatbot")
|
106 |
-
|
107 |
-
chatbot = gr.Chatbot(label="Chat History", height=500, show_copy_button=True)
|
108 |
-
message_input = gr.Textbox(placeholder="Type your message or upload a file...", scale=4)
|
109 |
-
send_button = gr.Button("Send π€", scale=1)
|
110 |
-
|
111 |
-
file_upload = gr.File(label="π Upload File", file_types=[".pdf", ".docx", ".txt", ".xlsx", ".xls", ".csv", ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".py", ".js", ".html", ".css", ".json", ".md"])
|
112 |
-
audio_upload = gr.Audio(label="π€ Upload Audio", type="filepath")
|
113 |
-
|
114 |
-
save_button = gr.Button("πΎ Save Chat")
|
115 |
-
clear_button = gr.Button("π New Chat")
|
116 |
-
refresh_button = gr.Button("π Refresh List")
|
117 |
-
|
118 |
-
saved_chats_dropdown = gr.Dropdown(label="π Load Saved Chat", choices=get_saved_chats(), type="value")
|
119 |
-
load_button = gr.Button("π Load Chat")
|
120 |
-
|
121 |
-
status_message = gr.Textbox(label="Status", interactive=False)
|
122 |
-
chat_history = gr.State([])
|
123 |
-
|
124 |
-
send_button.click(process_input, [message_input, file_upload, audio_upload, chat_history], [chat_history, message_input, file_upload, audio_upload, status_message])\
|
125 |
-
.then(lambda h: h, [chat_history], [chatbot])
|
126 |
-
|
127 |
-
message_input.submit(process_input, [message_input, file_upload, audio_upload, chat_history], [chat_history, message_input, file_upload, audio_upload, status_message])\
|
128 |
-
.then(lambda h: h, [chat_history], [chatbot])
|
129 |
-
|
130 |
-
save_button.click(save_chat_history, [chat_history], [status_message])\
|
131 |
-
.then(lambda: gr.Dropdown.update(choices=get_saved_chats()), None, [saved_chats_dropdown])
|
132 |
-
|
133 |
-
clear_button.click(clear_chat, None, [chat_history, status_message])\
|
134 |
-
.then(lambda: [], None, [chatbot])
|
135 |
-
|
136 |
-
refresh_button.click(lambda: gr.Dropdown.update(choices=get_saved_chats()), None, [saved_chats_dropdown])
|
137 |
-
|
138 |
-
load_button.click(load_selected_chat, [saved_chats_dropdown], [chat_history, status_message])\
|
139 |
-
.then(lambda h: h, [chat_history], [chatbot])
|
140 |
-
|
141 |
-
if __name__ == "__main__":
|
142 |
-
demo.launch(server_name="0.0.0.0", server_port=7860, share=False, debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
def chat_response(history, message):
|
2 |
try:
|
3 |
headers = {
|
|
|
15 |
}
|
16 |
|
17 |
response = requests.post(GROQ_API_URL, headers=headers, json=payload)
|
18 |
+
response.raise_for_status() # catches HTTP errors
|
19 |
+
return response.json()["choices"][0]["message"]["content"].strip()
|
|
|
|
|
20 |
|
21 |
+
except requests.exceptions.HTTPError as http_err:
|
22 |
+
return f"HTTP error: {http_err}\nResponse: {response.text}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
except Exception as e:
|
24 |
+
return f"Groq response failed: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|