Ali Abdullah commited on
Commit
38dc08b
·
verified ·
1 Parent(s): a265e6c

Upload gradio_frontend.py

Browse files
Files changed (1) hide show
  1. gradio_frontend.py +150 -0
gradio_frontend.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import mimetypes
4
+ import os
5
+
6
+ FILE_API_URL = "http://127.0.0.1:8000/chat-with-file"
7
+ URL_API_URL = "http://127.0.0.1:8000/chat-with-url"
8
+ IMAGE_API_URL = "http://127.0.0.1:8000/extract-text-from-image"
9
+ AUDIO_API_URL = "http://127.0.0.1:8000/transcribe-audio"
10
+
11
+ chat_sessions = {"file": [], "url": []}
12
+
13
+ def ask_from_file(file_obj, question, session_id):
14
+ if not file_obj or not question.strip():
15
+ return "⚠️ Please upload a file and enter a question.", chat_sessions["file"]
16
+
17
+ if os.path.getsize(file_obj.name) > 10 * 1024 * 1024:
18
+ return "❌ File too large. Please upload files under 10MB.", chat_sessions["file"]
19
+
20
+ try:
21
+ mime_type, _ = mimetypes.guess_type(file_obj.name)
22
+ with open(file_obj.name, "rb") as f:
23
+ files = {"file": (file_obj.name, f, mime_type or "application/octet-stream")}
24
+ history = chat_sessions["file"]
25
+ context = "\n".join([f"Q: {q}\nA: {a}" for q, a in history]) + f"\nQ: {question}"
26
+ data = {"question": context}
27
+ response = requests.post(FILE_API_URL, files=files, data=data)
28
+ answer = response.json().get("answer", "⚠️ No answer returned.")
29
+ chat_sessions["file"].append((question, answer))
30
+ return format_chat(chat_sessions["file"]), chat_sessions["file"]
31
+ except Exception as e:
32
+ return f"❌ Error: {str(e)}", chat_sessions["file"]
33
+
34
+ def ask_from_url(url, question, session_id):
35
+ if not url.strip() or not question.strip():
36
+ return "⚠️ Please enter both a valid URL and a question.", chat_sessions["url"]
37
+ try:
38
+ history = chat_sessions["url"]
39
+ context = "\n".join([f"Q: {q}\nA: {a}" for q, a in history]) + f"\nQ: {question}"
40
+ response = requests.post(URL_API_URL, json={"url": url, "question": context})
41
+ answer = response.json().get("answer", "⚠️ No answer returned.")
42
+ chat_sessions["url"].append((question, answer))
43
+ return format_chat(chat_sessions["url"]), chat_sessions["url"]
44
+ except Exception as e:
45
+ return f"❌ Error: {str(e)}", chat_sessions["url"]
46
+
47
+ def extract_text_from_image(image_path):
48
+ try:
49
+ with open(image_path, "rb") as f:
50
+ files = {"file": ("image.png", f, "image/png")}
51
+ response = requests.post(IMAGE_API_URL, files=files)
52
+ return response.json().get("answer", "⚠️ No text extracted.")
53
+ except Exception as e:
54
+ return f"❌ Error: {str(e)}"
55
+
56
+ def transcribe_audio(audio_path):
57
+ try:
58
+ with open(audio_path, "rb") as f:
59
+ files = {"file": ("audio.wav", f, "audio/wav")}
60
+ response = requests.post(AUDIO_API_URL, files=files)
61
+ return response.json().get("answer", "⚠️ No transcript returned.")
62
+ except Exception as e:
63
+ return f"❌ Error: {str(e)}"
64
+
65
+ def format_chat(history):
66
+ return "\n\n".join([f"👤 {q}\n🤖 {a}" for q, a in history])
67
+
68
+ def clear_file_chat():
69
+ chat_sessions["file"] = []
70
+ return "", chat_sessions["file"]
71
+
72
+ def clear_url_chat():
73
+ chat_sessions["url"] = []
74
+ return "", chat_sessions["url"]
75
+
76
+ custom_css = """
77
+ body, .gradio-container {
78
+ background-color: #111111 !important;
79
+ color: white !important;
80
+ }
81
+ footer { display: none !important; }
82
+ h1 {
83
+ font-size: 2.2em;
84
+ font-weight: bold;
85
+ text-align: center;
86
+ color: white;
87
+ margin-bottom: 20px;
88
+ }
89
+ .gr-button {
90
+ background-color: #00FF88;
91
+ color: black;
92
+ border: none;
93
+ border-radius: 6px;
94
+ font-weight: bold;
95
+ }
96
+ .gr-button:hover {
97
+ background-color: #00cc70;
98
+ }
99
+ .gr-input, .gr-textbox, .gr-file, textarea, input {
100
+ background-color: #1e1e1e !important;
101
+ color: white !important;
102
+ border: 1px solid #00FF88 !important;
103
+ border-radius: 6px !important;
104
+ }
105
+ .gr-tabitem[data-selected="true"] > button {
106
+ background-color: #00FF88 !important;
107
+ color: black !important;
108
+ }
109
+ .gr-tabitem > button {
110
+ background-color: transparent !important;
111
+ color: white !important;
112
+ }
113
+ """
114
+
115
+ with gr.Blocks(css=custom_css) as demo:
116
+ gr.Markdown("# 🤖 AI Chatbot with File, Web, Image, Audio & Chat History")
117
+
118
+ with gr.Tab("📂 Chat with File"):
119
+ file_input = gr.File(label="Upload File (.txt, .csv, .docx, .pdf)", file_types=[".txt", ".csv", ".docx", ".pdf"])
120
+ file_question = gr.Textbox(label="Your Question", placeholder="Ask something based on file")
121
+ file_button = gr.Button("Ask from File")
122
+ file_output = gr.Textbox(label="Chat History", lines=10)
123
+ clear_file = gr.Button("New File Chat")
124
+
125
+ file_button.click(fn=ask_from_file, inputs=[file_input, file_question, gr.State("file")], outputs=[file_output, gr.State("file")])
126
+ clear_file.click(fn=clear_file_chat, inputs=[], outputs=[file_output, gr.State("file")])
127
+
128
+ with gr.Tab("🌐 Chat with Website"):
129
+ url_input = gr.Textbox(label="Website URL", placeholder="https://example.com")
130
+ url_question = gr.Textbox(label="Your Question", placeholder="Ask something based on webpage")
131
+ url_button = gr.Button("Ask from URL")
132
+ url_output = gr.Textbox(label="Chat History", lines=10)
133
+ clear_url = gr.Button("New URL Chat")
134
+
135
+ url_button.click(fn=ask_from_url, inputs=[url_input, url_question, gr.State("url")], outputs=[url_output, gr.State("url")])
136
+ clear_url.click(fn=clear_url_chat, inputs=[], outputs=[url_output, gr.State("url")])
137
+
138
+ with gr.Tab("🖼 Extract Text from Image"):
139
+ image_input = gr.Image(label="Upload Image", type="filepath")
140
+ image_button = gr.Button("Extract Text")
141
+ image_output = gr.Textbox(label="Extracted Text", lines=8)
142
+ image_button.click(fn=extract_text_from_image, inputs=image_input, outputs=image_output)
143
+
144
+ with gr.Tab("🎤 Transcribe Audio"):
145
+ audio_input = gr.Audio(label="Upload Audio", type="filepath")
146
+ audio_button = gr.Button("Transcribe Audio")
147
+ audio_output = gr.Textbox(label="Transcript", lines=8)
148
+ audio_button.click(fn=transcribe_audio, inputs=audio_input, outputs=audio_output)
149
+
150
+ demo.launch(share=True)