Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -16,39 +16,38 @@ import base64
|
|
| 16 |
# Set Gemini API Key
|
| 17 |
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
|
| 18 |
|
| 19 |
-
# System prompt
|
| 20 |
-
SYSTEM_PROMPT = (
|
| 21 |
-
"You are part of an intelligent driver distraction detection system. "
|
| 22 |
-
"Your role is to analyze documents, images, and videos to help identify and classify driver states, "
|
| 23 |
-
"including: drowsy, alert, yawning, microsleep, eyes/lips open or closed, and other distractions. "
|
| 24 |
-
"The user may ask for timestamps of events in video, technical explanations from code/docs, "
|
| 25 |
-
"or structured summaries. Prioritize your answers for this use case and act as a helpful assistant "
|
| 26 |
-
"within this domain. "
|
| 27 |
-
"Additionally, your classification may rely on the State Farm Distracted Driver Detection dataset, "
|
| 28 |
-
"which defines 10 distraction categories such as texting, phone use, reaching behind, adjusting the radio, "
|
| 29 |
-
"and safe driving. Use this labeling scheme when interpreting relevant images or video frames."
|
| 30 |
-
)
|
| 31 |
-
|
| 32 |
# --------- File Extractors ---------
|
| 33 |
def extract_text_from_docx(docx_file):
|
| 34 |
-
|
|
|
|
| 35 |
|
| 36 |
def extract_text_from_csv(csv_file):
|
| 37 |
-
|
|
|
|
| 38 |
|
| 39 |
def extract_text_from_xlsx(xlsx_file):
|
| 40 |
-
|
|
|
|
| 41 |
|
| 42 |
def extract_text_from_pptx(pptx_file):
|
| 43 |
prs = Presentation(pptx_file)
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
def extract_text_from_pdf(pdf_file):
|
| 47 |
doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
def extract_text_from_html(html_file):
|
| 51 |
-
|
|
|
|
| 52 |
|
| 53 |
def extract_text_from_tex(tex_file):
|
| 54 |
content = tex_file.read().decode("utf-8")
|
|
@@ -57,131 +56,170 @@ def extract_text_from_tex(tex_file):
|
|
| 57 |
return content
|
| 58 |
|
| 59 |
def process_image(image_file):
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
def process_video(video_file):
|
|
|
|
| 66 |
filetype = video_file.name.split(".")[-1].lower()
|
| 67 |
mime_map = {
|
| 68 |
-
"avi": "video/x-msvideo",
|
| 69 |
-
"
|
|
|
|
|
|
|
| 70 |
"mpeg": "video/mpeg"
|
| 71 |
}
|
| 72 |
mime_type = mime_map.get(filetype, video_file.type)
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
def export_conversation_to_pdf(conversation_history):
|
| 76 |
pdf_path = "Conversation.pdf"
|
| 77 |
doc = SimpleDocTemplate(pdf_path, pagesize=A4)
|
| 78 |
styles = getSampleStyleSheet()
|
| 79 |
elements = []
|
|
|
|
| 80 |
for i, (user_q, gemini_a) in enumerate(conversation_history):
|
| 81 |
elements.append(Paragraph(f"<b>Q{i+1}:</b> {user_q}", styles["Normal"]))
|
| 82 |
elements.append(Spacer(1, 8))
|
| 83 |
elements.append(Paragraph(f"<b>A{i+1}:</b> {gemini_a.replace(chr(10), '<br/>')}", styles["Normal"]))
|
| 84 |
elements.append(Spacer(1, 16))
|
|
|
|
| 85 |
doc.build(elements)
|
| 86 |
return pdf_path
|
| 87 |
|
| 88 |
# --------- Main App ---------
|
| 89 |
def main():
|
| 90 |
-
st.set_page_config(page_title="
|
| 91 |
-
st.title("
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
uploaded_files = st.file_uploader(
|
| 98 |
-
"Upload
|
| 99 |
-
type=[
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
| 101 |
accept_multiple_files=True
|
| 102 |
)
|
| 103 |
|
| 104 |
if uploaded_files:
|
| 105 |
-
|
| 106 |
-
for
|
| 107 |
-
|
| 108 |
try:
|
| 109 |
-
if
|
| 110 |
-
|
| 111 |
-
elif
|
| 112 |
-
|
| 113 |
-
elif
|
| 114 |
-
|
| 115 |
-
elif
|
| 116 |
-
|
| 117 |
-
elif
|
| 118 |
-
|
| 119 |
-
elif
|
| 120 |
-
|
| 121 |
-
elif
|
| 122 |
-
|
| 123 |
-
elif
|
| 124 |
-
|
| 125 |
-
elif
|
| 126 |
-
st.session_state.image_data = process_image(
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
elif
|
| 130 |
-
st.session_state.video_data = process_video(
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
| 133 |
except Exception as e:
|
| 134 |
-
st.error(f"
|
| 135 |
-
|
|
|
|
| 136 |
|
| 137 |
if st.session_state.documents_text:
|
| 138 |
-
st.markdown("###
|
| 139 |
-
for
|
| 140 |
-
st.markdown(f"**You:** {
|
| 141 |
-
st.markdown(f"**Gemini:**
|
| 142 |
|
| 143 |
if st.session_state.chat_active:
|
| 144 |
-
with st.form("chat_form", clear_on_submit=True):
|
| 145 |
-
user_input = st.text_input("Ask a question about the
|
| 146 |
-
|
| 147 |
-
|
|
|
|
| 148 |
if user_input.strip().lower() == "exit":
|
| 149 |
st.session_state.chat_active = False
|
| 150 |
-
st.success("Chat ended.")
|
| 151 |
else:
|
| 152 |
with st.spinner("Gemini is thinking..."):
|
| 153 |
-
|
| 154 |
-
types.Content(role="user", parts=[types.Part(text=SYSTEM_PROMPT)])
|
| 155 |
-
]
|
| 156 |
|
| 157 |
if st.session_state.conversation:
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
-
if st.session_state.documents_text:
|
| 162 |
-
|
| 163 |
|
| 164 |
-
if st.session_state
|
| 165 |
-
|
| 166 |
|
| 167 |
-
if st.session_state
|
| 168 |
-
|
| 169 |
|
| 170 |
-
|
| 171 |
|
| 172 |
-
response = client.generate_content(
|
| 173 |
model="gemini-2.0-flash",
|
| 174 |
-
contents=
|
|
|
|
| 175 |
)
|
| 176 |
|
| 177 |
st.session_state.conversation.append((user_input, response.text))
|
| 178 |
-
st.success("
|
| 179 |
st.write(response.text)
|
| 180 |
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
if __name__ == "__main__":
|
| 187 |
-
main()
|
|
|
|
| 16 |
# Set Gemini API Key
|
| 17 |
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
# --------- File Extractors ---------
|
| 20 |
def extract_text_from_docx(docx_file):
|
| 21 |
+
document = Document(docx_file)
|
| 22 |
+
return "\n".join([para.text for para in document.paragraphs])
|
| 23 |
|
| 24 |
def extract_text_from_csv(csv_file):
|
| 25 |
+
df = pd.read_csv(csv_file)
|
| 26 |
+
return df.to_string(index=False)
|
| 27 |
|
| 28 |
def extract_text_from_xlsx(xlsx_file):
|
| 29 |
+
df = pd.read_excel(xlsx_file)
|
| 30 |
+
return df.to_string(index=False)
|
| 31 |
|
| 32 |
def extract_text_from_pptx(pptx_file):
|
| 33 |
prs = Presentation(pptx_file)
|
| 34 |
+
text_runs = []
|
| 35 |
+
for slide in prs.slides:
|
| 36 |
+
for shape in slide.shapes:
|
| 37 |
+
if hasattr(shape, "text"):
|
| 38 |
+
text_runs.append(shape.text)
|
| 39 |
+
return "\n".join(text_runs)
|
| 40 |
|
| 41 |
def extract_text_from_pdf(pdf_file):
|
| 42 |
doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
|
| 43 |
+
text = ""
|
| 44 |
+
for page in doc:
|
| 45 |
+
text += page.get_text()
|
| 46 |
+
return text
|
| 47 |
|
| 48 |
def extract_text_from_html(html_file):
|
| 49 |
+
soup = BeautifulSoup(html_file.read(), "html.parser")
|
| 50 |
+
return soup.get_text()
|
| 51 |
|
| 52 |
def extract_text_from_tex(tex_file):
|
| 53 |
content = tex_file.read().decode("utf-8")
|
|
|
|
| 56 |
return content
|
| 57 |
|
| 58 |
def process_image(image_file):
|
| 59 |
+
image_bytes = image_file.read()
|
| 60 |
+
encoded_image = base64.b64encode(image_bytes).decode("utf-8")
|
| 61 |
+
return {
|
| 62 |
+
"inline_data": {
|
| 63 |
+
"mime_type": image_file.type,
|
| 64 |
+
"data": encoded_image
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
|
| 68 |
def process_video(video_file):
|
| 69 |
+
video_bytes = video_file.read()
|
| 70 |
filetype = video_file.name.split(".")[-1].lower()
|
| 71 |
mime_map = {
|
| 72 |
+
"avi": "video/x-msvideo",
|
| 73 |
+
"mkv": "video/x-matroska",
|
| 74 |
+
"flv": "video/x-flv",
|
| 75 |
+
"wmv": "video/x-ms-wmv",
|
| 76 |
"mpeg": "video/mpeg"
|
| 77 |
}
|
| 78 |
mime_type = mime_map.get(filetype, video_file.type)
|
| 79 |
+
encoded_video = base64.b64encode(video_bytes).decode("utf-8")
|
| 80 |
+
return {
|
| 81 |
+
"inline_data": {
|
| 82 |
+
"mime_type": mime_type,
|
| 83 |
+
"data": encoded_video
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
|
| 87 |
def export_conversation_to_pdf(conversation_history):
|
| 88 |
pdf_path = "Conversation.pdf"
|
| 89 |
doc = SimpleDocTemplate(pdf_path, pagesize=A4)
|
| 90 |
styles = getSampleStyleSheet()
|
| 91 |
elements = []
|
| 92 |
+
|
| 93 |
for i, (user_q, gemini_a) in enumerate(conversation_history):
|
| 94 |
elements.append(Paragraph(f"<b>Q{i+1}:</b> {user_q}", styles["Normal"]))
|
| 95 |
elements.append(Spacer(1, 8))
|
| 96 |
elements.append(Paragraph(f"<b>A{i+1}:</b> {gemini_a.replace(chr(10), '<br/>')}", styles["Normal"]))
|
| 97 |
elements.append(Spacer(1, 16))
|
| 98 |
+
|
| 99 |
doc.build(elements)
|
| 100 |
return pdf_path
|
| 101 |
|
| 102 |
# --------- Main App ---------
|
| 103 |
def main():
|
| 104 |
+
st.set_page_config(page_title="Gemini 2.0 Flash Chat Q&A", layout="wide")
|
| 105 |
+
st.title("\U0001F4C4 Chat with Your Documents leveraging Internet Using Gemini 2.0 Flash (Team 18)")
|
| 106 |
+
|
| 107 |
+
if "conversation" not in st.session_state:
|
| 108 |
+
st.session_state.conversation = []
|
| 109 |
+
if "documents_text" not in st.session_state:
|
| 110 |
+
st.session_state.documents_text = []
|
| 111 |
+
if "chat_active" not in st.session_state:
|
| 112 |
+
st.session_state.chat_active = True
|
| 113 |
+
if "chat_history" not in st.session_state:
|
| 114 |
+
st.session_state.chat_history = []
|
| 115 |
|
| 116 |
uploaded_files = st.file_uploader(
|
| 117 |
+
"Upload files (.txt, .docx, .csv, .xlsx, .pptx, .pdf, .html, .htm, .tex, .jpg, .jpeg, .png, video formats):",
|
| 118 |
+
type=[
|
| 119 |
+
"txt", "docx", "csv", "xlsx", "pptx", "pdf", "html", "htm", "tex",
|
| 120 |
+
"jpg", "jpeg", "png",
|
| 121 |
+
"mp4", "webm", "mov", "avi", "mkv", "flv", "wmv", "mpeg"
|
| 122 |
+
],
|
| 123 |
accept_multiple_files=True
|
| 124 |
)
|
| 125 |
|
| 126 |
if uploaded_files:
|
| 127 |
+
all_text_content = ""
|
| 128 |
+
for uploaded_file in uploaded_files:
|
| 129 |
+
filetype = uploaded_file.name.split(".")[-1].lower()
|
| 130 |
try:
|
| 131 |
+
if filetype == "txt":
|
| 132 |
+
all_text_content += uploaded_file.read().decode("utf-8") + "\n"
|
| 133 |
+
elif filetype == "docx":
|
| 134 |
+
all_text_content += extract_text_from_docx(uploaded_file) + "\n"
|
| 135 |
+
elif filetype == "csv":
|
| 136 |
+
all_text_content += extract_text_from_csv(uploaded_file) + "\n"
|
| 137 |
+
elif filetype == "xlsx":
|
| 138 |
+
all_text_content += extract_text_from_xlsx(uploaded_file) + "\n"
|
| 139 |
+
elif filetype == "pptx":
|
| 140 |
+
all_text_content += extract_text_from_pptx(uploaded_file) + "\n"
|
| 141 |
+
elif filetype == "pdf":
|
| 142 |
+
all_text_content += extract_text_from_pdf(uploaded_file) + "\n"
|
| 143 |
+
elif filetype in ["html", "htm"]:
|
| 144 |
+
all_text_content += extract_text_from_html(uploaded_file) + "\n"
|
| 145 |
+
elif filetype == "tex":
|
| 146 |
+
all_text_content += extract_text_from_tex(uploaded_file) + "\n"
|
| 147 |
+
elif filetype in ["jpg", "jpeg", "png"]:
|
| 148 |
+
st.session_state.image_data = process_image(uploaded_file)
|
| 149 |
+
all_text_content += "Image uploaded and processed.\n"
|
| 150 |
+
st.image(uploaded_file, caption=uploaded_file.name, use_container_width=True)
|
| 151 |
+
elif filetype in ["mp4", "webm", "mov", "avi", "mkv", "flv", "wmv", "mpeg"]:
|
| 152 |
+
st.session_state.video_data = process_video(uploaded_file)
|
| 153 |
+
all_text_content += f"Video file '{uploaded_file.name}' uploaded and processed.\n"
|
| 154 |
+
st.video(uploaded_file)
|
| 155 |
+
else:
|
| 156 |
+
st.error(f"Unsupported file format: {uploaded_file.name}")
|
| 157 |
except Exception as e:
|
| 158 |
+
st.error(f"Failed to extract/process {uploaded_file.name}: {e}")
|
| 159 |
+
|
| 160 |
+
st.session_state.documents_text = all_text_content
|
| 161 |
|
| 162 |
if st.session_state.documents_text:
|
| 163 |
+
st.markdown("### \U0001F4AC Conversation")
|
| 164 |
+
for user_q, gemini_a in st.session_state.conversation:
|
| 165 |
+
st.markdown(f"**You:** {user_q}")
|
| 166 |
+
st.markdown(f"**Gemini:**\n\n{gemini_a}")
|
| 167 |
|
| 168 |
if st.session_state.chat_active:
|
| 169 |
+
with st.form(key="chat_form", clear_on_submit=True):
|
| 170 |
+
user_input = st.text_input("Ask a question about the documents (type 'exit' to stop):")
|
| 171 |
+
submit = st.form_submit_button("Send")
|
| 172 |
+
|
| 173 |
+
if submit and user_input:
|
| 174 |
if user_input.strip().lower() == "exit":
|
| 175 |
st.session_state.chat_active = False
|
| 176 |
+
st.success("Chat ended. Reload to start again.")
|
| 177 |
else:
|
| 178 |
with st.spinner("Gemini is thinking..."):
|
| 179 |
+
content_blocks = []
|
|
|
|
|
|
|
| 180 |
|
| 181 |
if st.session_state.conversation:
|
| 182 |
+
history_text = "\n\n".join(
|
| 183 |
+
f"Q: {entry[0]}\nA: {entry[1]}"
|
| 184 |
+
for entry in st.session_state.conversation
|
| 185 |
+
)
|
| 186 |
+
content_blocks.append({"text": f"Previous conversation:\n{history_text}"})
|
| 187 |
|
| 188 |
+
if st.session_state.documents_text.strip():
|
| 189 |
+
content_blocks.append({"text": f"Context:\n{st.session_state.documents_text}"})
|
| 190 |
|
| 191 |
+
if "image_data" in st.session_state:
|
| 192 |
+
content_blocks.append(st.session_state.image_data)
|
| 193 |
|
| 194 |
+
if "video_data" in st.session_state:
|
| 195 |
+
content_blocks.append(st.session_state.video_data)
|
| 196 |
|
| 197 |
+
content_blocks.append({"text": f"Question: {user_input}"})
|
| 198 |
|
| 199 |
+
response = client.models.generate_content(
|
| 200 |
model="gemini-2.0-flash",
|
| 201 |
+
contents=content_blocks,
|
| 202 |
+
config={"tools": [{"google_search": {}}]}
|
| 203 |
)
|
| 204 |
|
| 205 |
st.session_state.conversation.append((user_input, response.text))
|
| 206 |
+
st.success("\U0001F4A1 Answer:")
|
| 207 |
st.write(response.text)
|
| 208 |
|
| 209 |
+
st.session_state.chat_history.append({
|
| 210 |
+
"question": user_input,
|
| 211 |
+
"answer": response.text
|
| 212 |
+
})
|
| 213 |
+
|
| 214 |
+
if st.session_state.conversation:
|
| 215 |
+
pdf_path = export_conversation_to_pdf(st.session_state.conversation)
|
| 216 |
+
with open(pdf_path, "rb") as f:
|
| 217 |
+
st.download_button(
|
| 218 |
+
label="\U0001F4E5 Export Conversation as PDF",
|
| 219 |
+
data=f,
|
| 220 |
+
file_name="Conversation.pdf",
|
| 221 |
+
mime="application/pdf"
|
| 222 |
+
)
|
| 223 |
|
| 224 |
if __name__ == "__main__":
|
| 225 |
+
main()
|