JaweriaGenAI commited on
Commit
90a3808
Β·
verified Β·
1 Parent(s): df6af57

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -2
app.py CHANGED
@@ -1,3 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  def chat_response(history, message):
2
  try:
3
  headers = {
@@ -15,10 +51,94 @@ def chat_response(history, message):
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}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"
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
  }
52
 
53
  response = requests.post(GROQ_API_URL, headers=headers, json=payload)
54
+ response.raise_for_status()
55
  return response.json()["choices"][0]["message"]["content"].strip()
56
 
57
  except requests.exceptions.HTTPError as http_err:
58
  return f"HTTP error: {http_err}\nResponse: {response.text}"
59
  except Exception as e:
60
+ return f"Groq response failed: {e}"
61
+
62
+ def process_input(msg, file, audio, history):
63
+ file_text = extract_text_from_file(file) if file else ""
64
+ audio_text = transcribe_audio(audio) if audio else ""
65
+ full_input = "\n".join([i for i in [msg, file_text, audio_text] if i])
66
+ if not full_input.strip():
67
+ return history, gr.Textbox.update(value=""), None, None, gr.Textbox.update(value="No input provided.")
68
+ reply = chat_response(history, full_input)
69
+ history.append(("user", msg.strip() or file_text or audio_text))
70
+ history.append(("assistant", reply))
71
+ return history, gr.Textbox.update(value=""), None, None, gr.Textbox.update(value="Response generated.")
72
+
73
+ def save_chat_history(history):
74
+ try:
75
+ os.makedirs("saved_chats", exist_ok=True)
76
+ title = history[-2][1][:30].replace(" ", "_") if len(history) >= 2 else str(uuid.uuid4())
77
+ filename = f"saved_chats/{title}.txt"
78
+ with open(filename, "w", encoding="utf-8") as f:
79
+ for role, text in history:
80
+ f.write(f"{role}: {text}\n")
81
+ return gr.Textbox.update(value="Chat saved successfully.")
82
+ except Exception as e:
83
+ return gr.Textbox.update(value=f"Failed to save chat: {e}")
84
+
85
+ def get_saved_chats():
86
+ if not os.path.exists("saved_chats"): return []
87
+ return sorted([f for f in os.listdir("saved_chats") if f.endswith(".txt")])
88
+
89
+ def load_selected_chat(filename):
90
+ filepath = os.path.join("saved_chats", filename)
91
+ if not os.path.exists(filepath): return [], gr.Textbox.update(value="File not found.")
92
+ history = []
93
+ with open(filepath, "r", encoding="utf-8") as f:
94
+ for line in f:
95
+ if ":" in line:
96
+ role, content = line.strip().split(":", 1)
97
+ history.append((role.strip(), content.strip()))
98
+ return history, gr.Textbox.update(value=f"Chat '{filename}' loaded.")
99
+
100
+ def clear_chat(): return [], gr.Textbox.update(value="Chat cleared. Start fresh!")
101
+
102
+ custom_css = """
103
+ .gradio-container { max-width: 1200px !important; margin: auto !important; }
104
+ select { appearance: auto !important; }
105
+ """
106
+
107
+ with gr.Blocks(css=custom_css, title="Neobot - Chatbot") as demo:
108
+ gr.Markdown("# πŸ€– Neobot - Advanced AI Chatbot")
109
+
110
+ chatbot = gr.Chatbot(label="Chat History", height=500, show_copy_button=True)
111
+ message_input = gr.Textbox(placeholder="Type your message or upload a file...", scale=4)
112
+ send_button = gr.Button("Send πŸ“€", scale=1)
113
+
114
+ 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"])
115
+ audio_upload = gr.Audio(label="🎀 Upload Audio", type="filepath")
116
+
117
+ save_button = gr.Button("πŸ’Ύ Save Chat")
118
+ clear_button = gr.Button("πŸ†• New Chat")
119
+ refresh_button = gr.Button("πŸ”„ Refresh List")
120
+
121
+ saved_chats_dropdown = gr.Dropdown(label="πŸ“‚ Load Saved Chat", choices=get_saved_chats(), type="value")
122
+ load_button = gr.Button("πŸ“‚ Load Chat")
123
+
124
+ status_message = gr.Textbox(label="Status", interactive=False)
125
+ chat_history = gr.State([])
126
+
127
+ send_button.click(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
+ message_input.submit(process_input, [message_input, file_upload, audio_upload, chat_history], [chat_history, message_input, file_upload, audio_upload, status_message])\
131
+ .then(lambda h: h, [chat_history], [chatbot])
132
+
133
+ save_button.click(save_chat_history, [chat_history], [status_message])\
134
+ .then(lambda: gr.Dropdown.update(choices=get_saved_chats()), None, [saved_chats_dropdown])
135
+
136
+ clear_button.click(clear_chat, None, [chat_history, status_message])\
137
+ .then(lambda: [], None, [chatbot])
138
+
139
+ refresh_button.click(lambda: gr.Dropdown.update(choices=get_saved_chats()), None, [saved_chats_dropdown])
140
+
141
+ load_button.click(load_selected_chat, [saved_chats_dropdown], [chat_history, status_message])\
142
+ .then(lambda h: h, [chat_history], [chatbot])
143
+
144
+ app = demo # Required for Hugging Face Spaces to detect the Gradio app