Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import time
|
3 |
+
import json
|
4 |
+
import logging
|
5 |
+
import threading
|
6 |
+
import gradio as gr
|
7 |
+
import google.generativeai as genai
|
8 |
+
from googleapiclient.discovery import build
|
9 |
+
from googleapiclient.http import MediaIoBaseDownload
|
10 |
+
from google.oauth2 import service_account
|
11 |
+
from langchain_community.vectorstores import Chroma
|
12 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
13 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
14 |
+
from langchain_community.document_loaders import PyPDFLoader, TextLoader, Docx2txtLoader
|
15 |
+
from langchain.chains import RetrievalQA
|
16 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
17 |
+
from PyPDF2 import PdfReader
|
18 |
+
from gtts import gTTS
|
19 |
+
|
20 |
+
# ✅ Configure logging
|
21 |
+
logging.basicConfig(level=logging.INFO)
|
22 |
+
|
23 |
+
# ✅ Load API Keys
|
24 |
+
logging.info("🔑 Loading API keys...")
|
25 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY_1")
|
26 |
+
SERVICE_ACCOUNT_JSON = os.getenv("SERVICE_ACCOUNT_JSON")
|
27 |
+
|
28 |
+
if not GOOGLE_API_KEY or not SERVICE_ACCOUNT_JSON:
|
29 |
+
logging.error("❌ Missing API Key or Service Account JSON.")
|
30 |
+
raise ValueError("❌ Missing API Key or Service Account JSON. Please add them as environment variables.")
|
31 |
+
|
32 |
+
os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
|
33 |
+
SERVICE_ACCOUNT_FILE = json.loads(SERVICE_ACCOUNT_JSON)
|
34 |
+
SCOPES = ["https://www.googleapis.com/auth/drive"]
|
35 |
+
FOLDER_ID = "1xqOpwgwUoiJYf9GkeuB4dayme4zJcujf"
|
36 |
+
creds = service_account.Credentials.from_service_account_info(SERVICE_ACCOUNT_FILE)
|
37 |
+
drive_service = build("drive", "v3", credentials=creds)
|
38 |
+
|
39 |
+
# ✅ Initialize variables
|
40 |
+
vector_store = None
|
41 |
+
file_id_map = {}
|
42 |
+
temp_dir = "./temp_downloads"
|
43 |
+
os.makedirs(temp_dir, exist_ok=True)
|
44 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
45 |
+
|
46 |
+
# ✅ Get list of files from Google Drive
|
47 |
+
def get_files_from_drive():
|
48 |
+
logging.info("📂 Fetching files from Google Drive...")
|
49 |
+
query = f"'{FOLDER_ID}' in parents and trashed = false"
|
50 |
+
results = drive_service.files().list(q=query, fields="files(id, name)").execute()
|
51 |
+
files = results.get("files", [])
|
52 |
+
global file_id_map
|
53 |
+
file_id_map = {file["name"]: file["id"] for file in files}
|
54 |
+
return list(file_id_map.keys()) if files else []
|
55 |
+
|
56 |
+
# ✅ Download file from Google Drive
|
57 |
+
def download_file(file_id, file_name):
|
58 |
+
file_path = os.path.join(temp_dir, file_name)
|
59 |
+
request = drive_service.files().get_media(fileId=file_id)
|
60 |
+
with open(file_path, "wb") as f:
|
61 |
+
downloader = MediaIoBaseDownload(f, request)
|
62 |
+
done = False
|
63 |
+
while not done:
|
64 |
+
_, done = downloader.next_chunk()
|
65 |
+
return file_path
|
66 |
+
|
67 |
+
# ✅ Process documents
|
68 |
+
def process_documents(selected_files):
|
69 |
+
global vector_store
|
70 |
+
docs = []
|
71 |
+
for file_name in selected_files:
|
72 |
+
file_path = download_file(file_id_map[file_name], file_name)
|
73 |
+
if file_name.endswith(".pdf"):
|
74 |
+
loader = PyPDFLoader(file_path)
|
75 |
+
elif file_name.endswith(".txt"):
|
76 |
+
loader = TextLoader(file_path)
|
77 |
+
elif file_name.endswith(".docx"):
|
78 |
+
loader = Docx2txtLoader(file_path)
|
79 |
+
else:
|
80 |
+
logging.warning(f"⚠️ Unsupported file type: {file_name}")
|
81 |
+
continue
|
82 |
+
docs.extend(loader.load())
|
83 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
|
84 |
+
split_docs = text_splitter.split_documents(docs)
|
85 |
+
vector_store = Chroma.from_documents(split_docs, embeddings)
|
86 |
+
return "✅ Documents processed successfully!"
|
87 |
+
|
88 |
+
# ✅ Query document
|
89 |
+
def query_document(question):
|
90 |
+
if vector_store is None:
|
91 |
+
return "❌ No documents processed.", None
|
92 |
+
retriever = vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 5})
|
93 |
+
model = ChatGoogleGenerativeAI(model="gemini-2.0-flash", google_api_key=GOOGLE_API_KEY)
|
94 |
+
qa_chain = RetrievalQA.from_chain_type(llm=model, retriever=retriever)
|
95 |
+
response = qa_chain.invoke({"query": question})["result"]
|
96 |
+
tts = gTTS(text=response, lang="en")
|
97 |
+
temp_audio_path = os.path.join(temp_dir, "response.mp3")
|
98 |
+
tts.save(temp_audio_path)
|
99 |
+
return response, temp_audio_path
|
100 |
+
|
101 |
+
# ✅ Gradio UI
|
102 |
+
with gr.Blocks() as demo:
|
103 |
+
gr.Markdown("# 📄 AI-Powered Multi-Document Chatbot with Voice Output")
|
104 |
+
file_dropdown = gr.Dropdown(choices=get_files_from_drive(), label="📂 Select Files", multiselect=True)
|
105 |
+
process_button = gr.Button("🚀 Process Documents")
|
106 |
+
user_input = gr.Textbox(label="🔎 Ask a Question")
|
107 |
+
submit_button = gr.Button("💬 Get Answer")
|
108 |
+
response_output = gr.Textbox(label="📝 Response")
|
109 |
+
audio_output = gr.Audio(label="🔊 Audio Response")
|
110 |
+
process_button.click(process_documents, inputs=file_dropdown, outputs=response_output)
|
111 |
+
submit_button.click(query_document, inputs=user_input, outputs=[response_output, audio_output])
|
112 |
+
|
113 |
+
demo.launch()
|
114 |
+
|