Ali Abdullah commited on
Commit
0777ffb
·
verified ·
1 Parent(s): 735359c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -15
app.py CHANGED
@@ -4,14 +4,22 @@ 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"
@@ -19,6 +27,9 @@ 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"]
@@ -34,7 +45,7 @@ def ask_from_file(file_obj, question, session_id):
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:
@@ -47,7 +58,7 @@ def ask_from_url(url, question, session_id):
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:
@@ -58,7 +69,7 @@ def extract_text_from_image(image_path):
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
 
@@ -67,13 +78,10 @@ def transcribe_audio(audio_path):
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"]
@@ -122,9 +130,9 @@ h1 {
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")
@@ -134,7 +142,7 @@ with gr.Blocks(css=custom_css) as demo:
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")
@@ -144,16 +152,16 @@ with gr.Blocks(css=custom_css) as demo:
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)
 
4
  import os
5
  import threading
6
  import uvicorn
7
+ import re
8
 
9
+ # === Fix surrogate character issue ===
10
+ def sanitize(text):
11
+ if isinstance(text, str):
12
+ text = re.sub(r'[\uD800-\uDFFF]', '', text)
13
+ return text.encode("utf-8", "ignore").decode("utf-8")
14
+ return text
15
+
16
+ # Start FastAPI in a background thread
17
  def run_fastapi():
18
  uvicorn.run("main:app", host="0.0.0.0", port=8000)
19
 
20
  threading.Thread(target=run_fastapi, daemon=True).start()
21
 
22
+ # Backend API endpoints
23
  FILE_API_URL = "http://127.0.0.1:8000/chat-with-file"
24
  URL_API_URL = "http://127.0.0.1:8000/chat-with-url"
25
  IMAGE_API_URL = "http://127.0.0.1:8000/extract-text-from-image"
 
27
 
28
  chat_sessions = {"file": [], "url": []}
29
 
30
+ def format_chat(history):
31
+ return "\n\n".join([f"👤 {sanitize(q)}\n🤖 {sanitize(a)}" for q, a in history])
32
+
33
  def ask_from_file(file_obj, question, session_id):
34
  if not file_obj or not question.strip():
35
  return "⚠️ Please upload a file and enter a question.", chat_sessions["file"]
 
45
  context = "\n".join([f"Q: {q}\nA: {a}" for q, a in history]) + f"\nQ: {question}"
46
  data = {"question": context}
47
  response = requests.post(FILE_API_URL, files=files, data=data)
48
+ answer = sanitize(response.json().get("answer", "⚠️ No answer returned."))
49
  chat_sessions["file"].append((question, answer))
50
  return format_chat(chat_sessions["file"]), chat_sessions["file"]
51
  except Exception as e:
 
58
  history = chat_sessions["url"]
59
  context = "\n".join([f"Q: {q}\nA: {a}" for q, a in history]) + f"\nQ: {question}"
60
  response = requests.post(URL_API_URL, json={"url": url, "question": context})
61
+ answer = sanitize(response.json().get("answer", "⚠️ No answer returned."))
62
  chat_sessions["url"].append((question, answer))
63
  return format_chat(chat_sessions["url"]), chat_sessions["url"]
64
  except Exception as e:
 
69
  with open(image_path, "rb") as f:
70
  files = {"file": ("image.png", f, "image/png")}
71
  response = requests.post(IMAGE_API_URL, files=files)
72
+ return sanitize(response.json().get("answer", "⚠️ No text extracted."))
73
  except Exception as e:
74
  return f"❌ Error: {str(e)}"
75
 
 
78
  with open(audio_path, "rb") as f:
79
  files = {"file": ("audio.wav", f, "audio/wav")}
80
  response = requests.post(AUDIO_API_URL, files=files)
81
+ return sanitize(response.json().get("answer", "⚠️ No transcript returned."))
82
  except Exception as e:
83
  return f"❌ Error: {str(e)}"
84
 
 
 
 
85
  def clear_file_chat():
86
  chat_sessions["file"] = []
87
  return "", chat_sessions["file"]
 
130
  """
131
 
132
  with gr.Blocks(css=custom_css) as demo:
133
+ gr.Markdown("# 🤖 AI Chatbot with File, Web, Image, Audio & Chat History")
134
 
135
+ with gr.Tab("📂 Chat with File"):
136
  file_input = gr.File(label="Upload File (.txt, .csv, .docx, .pdf)", file_types=[".txt", ".csv", ".docx", ".pdf"])
137
  file_question = gr.Textbox(label="Your Question", placeholder="Ask something based on file")
138
  file_button = gr.Button("Ask from File")
 
142
  file_button.click(fn=ask_from_file, inputs=[file_input, file_question, gr.State("file")], outputs=[file_output, gr.State("file")])
143
  clear_file.click(fn=clear_file_chat, inputs=[], outputs=[file_output, gr.State("file")])
144
 
145
+ with gr.Tab("🌐 Chat with Website"):
146
  url_input = gr.Textbox(label="Website URL", placeholder="https://example.com")
147
  url_question = gr.Textbox(label="Your Question", placeholder="Ask something based on webpage")
148
  url_button = gr.Button("Ask from URL")
 
152
  url_button.click(fn=ask_from_url, inputs=[url_input, url_question, gr.State("url")], outputs=[url_output, gr.State("url")])
153
  clear_url.click(fn=clear_url_chat, inputs=[], outputs=[url_output, gr.State("url")])
154
 
155
+ with gr.Tab("🖼️ Extract Text from Image"):
156
  image_input = gr.Image(label="Upload Image", type="filepath")
157
  image_button = gr.Button("Extract Text")
158
  image_output = gr.Textbox(label="Extracted Text", lines=8)
159
  image_button.click(fn=extract_text_from_image, inputs=image_input, outputs=image_output)
160
 
161
+ with gr.Tab("🎤 Transcribe Audio"):
162
  audio_input = gr.Audio(label="Upload Audio", type="filepath")
163
  audio_button = gr.Button("Transcribe Audio")
164
  audio_output = gr.Textbox(label="Transcript", lines=8)
165
  audio_button.click(fn=transcribe_audio, inputs=audio_input, outputs=audio_output)
166
 
167
+ demo.launch(share=False)