Ali Abdullah commited on
Commit
77f2e68
·
verified ·
1 Parent(s): 349d8d8

Rename gradio_frontend.py to app.py

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