Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,174 +1,150 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import base64
|
| 3 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
from docx import Document
|
| 5 |
-
import openpyxl
|
| 6 |
-
from pdfminer.high_level import extract_text
|
| 7 |
-
import csv
|
| 8 |
from pptx import Presentation
|
| 9 |
-
from
|
| 10 |
-
from
|
| 11 |
-
import
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
#
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
# Add current question
|
| 152 |
-
content_blocks.append({"text": f"Question: {question}"})
|
| 153 |
-
|
| 154 |
-
response = model.generate_content(contents=content_blocks)
|
| 155 |
-
st.success("💡 Answer:")
|
| 156 |
-
st.write(response.text)
|
| 157 |
-
|
| 158 |
-
# Save to session history
|
| 159 |
-
st.session_state.chat_history.append({
|
| 160 |
-
"question": question,
|
| 161 |
-
"answer": response.text
|
| 162 |
-
})
|
| 163 |
-
|
| 164 |
-
except Exception as e:
|
| 165 |
-
st.error(f"Error generating answer: {e}")
|
| 166 |
-
else:
|
| 167 |
-
st.warning("No valid documents or images processed.")
|
| 168 |
-
|
| 169 |
-
# Optional: Show full conversation history
|
| 170 |
-
if st.session_state.chat_history:
|
| 171 |
-
st.markdown("### 🗂️ Chat History")
|
| 172 |
-
for i, entry in enumerate(st.session_state.chat_history, 1):
|
| 173 |
-
st.markdown(f"**Q{i}:** {entry['question']}")
|
| 174 |
-
st.markdown(f"**A{i}:** {entry['answer']}")
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import os
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import fitz # PyMuPDF
|
| 5 |
+
from google import genai
|
| 6 |
+
from google.genai import types
|
| 7 |
from docx import Document
|
|
|
|
|
|
|
|
|
|
| 8 |
from pptx import Presentation
|
| 9 |
+
from reportlab.lib.pagesizes import A4
|
| 10 |
+
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
|
| 11 |
+
from reportlab.lib.styles import getSampleStyleSheet
|
| 12 |
+
|
| 13 |
+
# Set Gemini API Key
|
| 14 |
+
os.environ["GEMINI_API_KEY"] = "AIzaSyAQLUStrjXv2_zrAjssapa_sYXQWOqVeiE" # Ensure this is set securely in Hugging Face environment
|
| 15 |
+
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
|
| 16 |
+
|
| 17 |
+
# Function to extract text from different file formats
|
| 18 |
+
def extract_text_from_docx(docx_file):
|
| 19 |
+
document = Document(docx_file)
|
| 20 |
+
return "\n".join([para.text for para in document.paragraphs])
|
| 21 |
+
|
| 22 |
+
def extract_text_from_csv(csv_file):
|
| 23 |
+
df = pd.read_csv(csv_file)
|
| 24 |
+
return df.to_string(index=False)
|
| 25 |
+
|
| 26 |
+
def extract_text_from_xlsx(xlsx_file):
|
| 27 |
+
df = pd.read_excel(xlsx_file)
|
| 28 |
+
return df.to_string(index=False)
|
| 29 |
+
|
| 30 |
+
def extract_text_from_pptx(pptx_file):
|
| 31 |
+
prs = Presentation(pptx_file)
|
| 32 |
+
text_runs = []
|
| 33 |
+
for slide in prs.slides:
|
| 34 |
+
for shape in slide.shapes:
|
| 35 |
+
if hasattr(shape, "text"):
|
| 36 |
+
text_runs.append(shape.text)
|
| 37 |
+
return "\n".join(text_runs)
|
| 38 |
+
|
| 39 |
+
def extract_text_from_pdf(pdf_file):
|
| 40 |
+
doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
|
| 41 |
+
text = ""
|
| 42 |
+
for page in doc:
|
| 43 |
+
text += page.get_text()
|
| 44 |
+
return text
|
| 45 |
+
|
| 46 |
+
def export_conversation_to_pdf(conversation_history):
|
| 47 |
+
pdf_path = "conversation_clean.pdf"
|
| 48 |
+
doc = SimpleDocTemplate(pdf_path, pagesize=A4)
|
| 49 |
+
styles = getSampleStyleSheet()
|
| 50 |
+
elements = []
|
| 51 |
+
|
| 52 |
+
for i, (user_q, gemini_a) in enumerate(conversation_history):
|
| 53 |
+
elements.append(Paragraph(f"<b>Q{i+1}:</b> {user_q}", styles["Normal"]))
|
| 54 |
+
elements.append(Spacer(1, 8))
|
| 55 |
+
elements.append(Paragraph(f"<b>A{i+1}:</b> {gemini_a.replace(chr(10), '<br/>')}", styles["Normal"]))
|
| 56 |
+
elements.append(Spacer(1, 16))
|
| 57 |
+
|
| 58 |
+
doc.build(elements)
|
| 59 |
+
return pdf_path
|
| 60 |
+
|
| 61 |
+
def main():
|
| 62 |
+
st.set_page_config(page_title="Gemini Chat QA", layout="wide")
|
| 63 |
+
st.title("📄 Chat with Your Document using Gemini (Sayandip+Dhiraj+Fazal)")
|
| 64 |
+
|
| 65 |
+
if "conversation" not in st.session_state:
|
| 66 |
+
st.session_state.conversation = []
|
| 67 |
+
if "document_text" not in st.session_state:
|
| 68 |
+
st.session_state.document_text = ""
|
| 69 |
+
if "chat_active" not in st.session_state:
|
| 70 |
+
st.session_state.chat_active = True
|
| 71 |
+
|
| 72 |
+
uploaded_file = st.file_uploader("Upload a file (.txt, .docx, .csv, .xlsx, .pptx, .pdf):",
|
| 73 |
+
type=["txt", "docx", "csv", "xlsx", "pptx", "pdf"])
|
| 74 |
+
|
| 75 |
+
if uploaded_file and not st.session_state.document_text:
|
| 76 |
+
filetype = uploaded_file.name.split(".")[-1].lower()
|
| 77 |
+
try:
|
| 78 |
+
if filetype == "txt":
|
| 79 |
+
st.session_state.document_text = uploaded_file.read().decode("utf-8")
|
| 80 |
+
elif filetype == "docx":
|
| 81 |
+
st.session_state.document_text = extract_text_from_docx(uploaded_file)
|
| 82 |
+
elif filetype == "csv":
|
| 83 |
+
st.session_state.document_text = extract_text_from_csv(uploaded_file)
|
| 84 |
+
elif filetype == "xlsx":
|
| 85 |
+
st.session_state.document_text = extract_text_from_xlsx(uploaded_file)
|
| 86 |
+
elif filetype == "pptx":
|
| 87 |
+
st.session_state.document_text = extract_text_from_pptx(uploaded_file)
|
| 88 |
+
elif filetype == "pdf":
|
| 89 |
+
st.session_state.document_text = extract_text_from_pdf(uploaded_file)
|
| 90 |
+
else:
|
| 91 |
+
st.error("Unsupported file format.")
|
| 92 |
+
except Exception as e:
|
| 93 |
+
st.error(f"Failed to extract text: {e}")
|
| 94 |
+
|
| 95 |
+
if st.session_state.document_text:
|
| 96 |
+
st.markdown("### 💬 Conversation")
|
| 97 |
+
for user_q, gemini_a in st.session_state.conversation:
|
| 98 |
+
st.markdown(f"**You:** {user_q}")
|
| 99 |
+
st.markdown(f"**Gemini:**\\n\\n{gemini_a}")
|
| 100 |
+
|
| 101 |
+
if st.session_state.chat_active:
|
| 102 |
+
with st.form(key="chat_form", clear_on_submit=True):
|
| 103 |
+
user_input = st.text_input("Ask a question about the document (type 'exit' to stop):")
|
| 104 |
+
submit = st.form_submit_button("Send")
|
| 105 |
+
|
| 106 |
+
if submit and user_input:
|
| 107 |
+
if user_input.strip().lower() == "exit":
|
| 108 |
+
st.session_state.chat_active = False
|
| 109 |
+
st.success("Chat ended. Reload to start again.")
|
| 110 |
+
else:
|
| 111 |
+
with st.spinner("Gemini is thinking..."):
|
| 112 |
+
contents = [
|
| 113 |
+
types.Content(
|
| 114 |
+
role="user",
|
| 115 |
+
parts=[
|
| 116 |
+
types.Part.from_text(text=st.session_state.document_text),
|
| 117 |
+
types.Part.from_text(text=user_input),
|
| 118 |
+
types.Part.from_text(text="If needed, search the web for more context.")
|
| 119 |
+
]
|
| 120 |
+
)
|
| 121 |
+
]
|
| 122 |
+
tools = [types.Tool(google_search=types.GoogleSearch())]
|
| 123 |
+
generate_config = types.GenerateContentConfig(
|
| 124 |
+
tools=tools,
|
| 125 |
+
response_mime_type="text/plain",
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
response_text = ""
|
| 129 |
+
for chunk in client.models.generate_content_stream(
|
| 130 |
+
model="gemini-2.0-flash",
|
| 131 |
+
contents=contents,
|
| 132 |
+
config=generate_config,
|
| 133 |
+
):
|
| 134 |
+
response_text += chunk.text
|
| 135 |
+
|
| 136 |
+
st.session_state.conversation.append((user_input, response_text))
|
| 137 |
+
st.rerun()
|
| 138 |
+
|
| 139 |
+
if st.session_state.conversation:
|
| 140 |
+
pdf_path = export_conversation_to_pdf(st.session_state.conversation)
|
| 141 |
+
with open(pdf_path, "rb") as f:
|
| 142 |
+
st.download_button(
|
| 143 |
+
label="📥 Download Cleaned Conversation as PDF",
|
| 144 |
+
data=f,
|
| 145 |
+
file_name="clean_conversation.pdf",
|
| 146 |
+
mime="application/pdf"
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
if __name__ == "__main__":
|
| 150 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|