Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,92 +1,107 @@
|
|
1 |
import gradio as gr
|
2 |
import os
|
3 |
-
import openai
|
4 |
-
import pdfplumber
|
5 |
-
import docx
|
6 |
-
import pandas as pd
|
7 |
-
from PIL import Image
|
8 |
-
from io import BytesIO
|
9 |
-
import base64
|
10 |
import tempfile
|
11 |
import whisper
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
-
|
14 |
-
|
15 |
-
# Load Whisper model
|
16 |
whisper_model = whisper.load_model("base")
|
17 |
|
18 |
-
def
|
19 |
-
if file.name.endswith(".pdf"):
|
20 |
-
with pdfplumber.open(file.name) as pdf:
|
21 |
-
text = "\n".join(page.extract_text() for page in pdf.pages if page.extract_text())
|
22 |
-
elif file.name.endswith(".docx"):
|
23 |
-
doc = docx.Document(file.name)
|
24 |
-
text = "\n".join(p.text for p in doc.paragraphs)
|
25 |
-
elif file.name.endswith(".xlsx"):
|
26 |
-
df = pd.read_excel(file.name)
|
27 |
-
text = df.to_string()
|
28 |
-
elif file.name.endswith((".png", ".jpg", ".jpeg")):
|
29 |
-
img = Image.open(file.name)
|
30 |
-
buffer = BytesIO()
|
31 |
-
img.save(buffer, format="PNG")
|
32 |
-
encoded = base64.b64encode(buffer.getvalue()).decode("utf-8")
|
33 |
-
text = f"[Image uploaded: data:image/png;base64,{encoded[:100]}... (truncated)]"
|
34 |
-
else:
|
35 |
-
with open(file.name, "r", encoding="utf-8", errors="ignore") as f:
|
36 |
-
text = f.read()
|
37 |
-
return text
|
38 |
-
|
39 |
-
def transcribe_audio(audio_path):
|
40 |
-
result = whisper_model.transcribe(audio_path)
|
41 |
-
return result["text"]
|
42 |
-
|
43 |
-
def generate_reply(history):
|
44 |
-
messages = [{"role": "system", "content": "You are a helpful assistant."}]
|
45 |
-
for user_msg, bot_msg in history:
|
46 |
-
messages.append({"role": "user", "content": user_msg})
|
47 |
-
messages.append({"role": "assistant", "content": bot_msg})
|
48 |
-
|
49 |
-
response = openai.ChatCompletion.create(
|
50 |
-
model="llama3-8b-8192",
|
51 |
-
messages=messages,
|
52 |
-
temperature=0.7
|
53 |
-
)
|
54 |
-
reply = response.choices[0].message.content
|
55 |
-
return reply
|
56 |
-
|
57 |
-
def respond(message, history):
|
58 |
-
reply = generate_reply(history + [[message, ""]])
|
59 |
-
history.append([message, reply])
|
60 |
-
return history, ""
|
61 |
-
|
62 |
-
def handle_file_upload(file, message):
|
63 |
if file is None:
|
64 |
-
return
|
65 |
-
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
-
def
|
69 |
if audio is None:
|
70 |
-
return
|
71 |
-
|
72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
-
|
75 |
-
gr.Markdown("<h1 style='text-align: center;'>Neobot</h1>")
|
76 |
-
chatbot = gr.Chatbot(label="Chat", elem_id="chatbox", height=450, type="messages")
|
77 |
|
78 |
with gr.Row():
|
79 |
-
|
|
|
|
|
|
|
|
|
|
|
80 |
send_btn = gr.Button("Send", scale=1)
|
81 |
|
82 |
with gr.Row():
|
83 |
-
|
84 |
-
|
85 |
|
86 |
-
|
87 |
|
88 |
-
send_btn.click(
|
89 |
-
|
90 |
-
|
91 |
|
92 |
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import tempfile
|
4 |
import whisper
|
5 |
+
import docx
|
6 |
+
import pdfplumber
|
7 |
+
import pandas as pd
|
8 |
+
from groq import Groq
|
9 |
+
from PyPDF2 import PdfReader
|
10 |
|
11 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
12 |
+
client = Groq(api_key=GROQ_API_KEY)
|
|
|
13 |
whisper_model = whisper.load_model("base")
|
14 |
|
15 |
+
def read_file(file):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
if file is None:
|
17 |
+
return ""
|
18 |
+
ext = os.path.splitext(file.name)[-1].lower()
|
19 |
+
try:
|
20 |
+
if ext == ".txt":
|
21 |
+
with open(file.name, "r", encoding="utf-8") as f:
|
22 |
+
return f.read()
|
23 |
+
elif ext == ".pdf":
|
24 |
+
text = ""
|
25 |
+
with pdfplumber.open(file.name) as pdf:
|
26 |
+
for page in pdf.pages:
|
27 |
+
text += page.extract_text() + "\n"
|
28 |
+
return text
|
29 |
+
elif ext in [".doc", ".docx"]:
|
30 |
+
doc = docx.Document(file.name)
|
31 |
+
return "\n".join([para.text for para in doc.paragraphs])
|
32 |
+
elif ext in [".xls", ".xlsx"]:
|
33 |
+
df = pd.read_excel(file.name)
|
34 |
+
return df.to_string(index=False)
|
35 |
+
else:
|
36 |
+
return f"[Unsupported file format: {ext}]"
|
37 |
+
except Exception as e:
|
38 |
+
return f"[Error reading file: {e}]"
|
39 |
|
40 |
+
def transcribe_audio(audio):
|
41 |
if audio is None:
|
42 |
+
return ""
|
43 |
+
try:
|
44 |
+
audio_path = audio.name
|
45 |
+
result = whisper_model.transcribe(audio_path)
|
46 |
+
return result["text"]
|
47 |
+
except Exception as e:
|
48 |
+
return f"[Error transcribing audio: {e}]"
|
49 |
+
|
50 |
+
def process_input(message, history):
|
51 |
+
if not message.strip():
|
52 |
+
return history
|
53 |
+
|
54 |
+
history = history or []
|
55 |
+
history.append({"role": "user", "content": message})
|
56 |
+
|
57 |
+
try:
|
58 |
+
response = client.chat.completions.create(
|
59 |
+
model="llama3-8b-8192",
|
60 |
+
messages=history,
|
61 |
+
)
|
62 |
+
reply = response.choices[0].message.content
|
63 |
+
history.append({"role": "assistant", "content": reply})
|
64 |
+
except Exception as e:
|
65 |
+
history.append({"role": "assistant", "content": f"[Error: {e}]"})
|
66 |
+
|
67 |
+
return history
|
68 |
+
|
69 |
+
def interface_func(message, history, file, audio):
|
70 |
+
file_text = read_file(file) if file else ""
|
71 |
+
audio_text = transcribe_audio(audio) if audio else ""
|
72 |
+
combined = ""
|
73 |
+
|
74 |
+
if file_text:
|
75 |
+
combined += f"{file.name} content:\n{file_text}\n\n"
|
76 |
+
if audio_text:
|
77 |
+
combined += f"Transcribed audio:\n{audio_text}\n\n"
|
78 |
+
if message:
|
79 |
+
combined += message
|
80 |
+
|
81 |
+
return combined.strip()
|
82 |
+
|
83 |
+
with gr.Blocks(css="textarea { font-size: 16px !important; }") as demo:
|
84 |
+
gr.Markdown("<h1 style='text-align: center;'>NEOBOT</h1>")
|
85 |
|
86 |
+
chatbot = gr.Chatbot(height=400, label="Chat")
|
|
|
|
|
87 |
|
88 |
with gr.Row():
|
89 |
+
msg_box = gr.Textbox(
|
90 |
+
scale=8,
|
91 |
+
placeholder="Ask something...",
|
92 |
+
show_label=False,
|
93 |
+
container=True
|
94 |
+
)
|
95 |
send_btn = gr.Button("Send", scale=1)
|
96 |
|
97 |
with gr.Row():
|
98 |
+
file_upload = gr.File(label="Upload File", file_types=[".txt", ".pdf", ".docx", ".xlsx"])
|
99 |
+
audio_upload = gr.Audio(source="upload", type="filepath", label="Upload Audio")
|
100 |
|
101 |
+
state = gr.State([])
|
102 |
|
103 |
+
send_btn.click(fn=process_input, inputs=[msg_box, state], outputs=[chatbot, state])
|
104 |
+
file_upload.change(fn=interface_func, inputs=[msg_box, state, file_upload, audio_upload], outputs=msg_box)
|
105 |
+
audio_upload.change(fn=interface_func, inputs=[msg_box, state, file_upload, audio_upload], outputs=msg_box)
|
106 |
|
107 |
demo.launch()
|