Spaces:
Sleeping
Sleeping
Upload 5 files
Browse files- Dockerfile +22 -0
- app.py +102 -0
- chatbot.py +195 -0
- requirements.txt +18 -0
- templates/index.html +252 -0
Dockerfile
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use the official Python base image
|
| 2 |
+
FROM python:3.11-slim
|
| 3 |
+
|
| 4 |
+
# Set environment variables
|
| 5 |
+
ENV PYTHONDONTWRITEBYTECODE=1
|
| 6 |
+
ENV PYTHONUNBUFFERED=1
|
| 7 |
+
|
| 8 |
+
# Set work directory
|
| 9 |
+
WORKDIR /app
|
| 10 |
+
|
| 11 |
+
# Install dependencies
|
| 12 |
+
COPY requirements.txt .
|
| 13 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 14 |
+
|
| 15 |
+
# Copy project files
|
| 16 |
+
COPY . .
|
| 17 |
+
|
| 18 |
+
# Expose the port Flask runs on
|
| 19 |
+
EXPOSE 5000
|
| 20 |
+
|
| 21 |
+
# Run the app
|
| 22 |
+
CMD ["python", "app.py"]
|
app.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, render_template, request, jsonify
|
| 2 |
+
from googletrans import Translator
|
| 3 |
+
import io
|
| 4 |
+
import asyncio
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
import os
|
| 7 |
+
import logging
|
| 8 |
+
from chatbot import process_uploaded_file, index_documents, rag_chatbot
|
| 9 |
+
|
| 10 |
+
# Set up logging
|
| 11 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
# Load environment variables
|
| 15 |
+
load_dotenv()
|
| 16 |
+
app = Flask(__name__)
|
| 17 |
+
|
| 18 |
+
LANGUAGE_MAP = {
|
| 19 |
+
"English (US)": "en",
|
| 20 |
+
"Hindi (India)": "hi",
|
| 21 |
+
"Spanish (Spain)": "es",
|
| 22 |
+
"French (France)": "fr",
|
| 23 |
+
"German (Germany)": "de",
|
| 24 |
+
"Arabic (Saudi Arabia)": "ar"
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
@app.route('/')
|
| 28 |
+
def index():
|
| 29 |
+
return render_template("index.html")
|
| 30 |
+
|
| 31 |
+
@app.route('/api/upload_document', methods=['POST'])
|
| 32 |
+
def upload_document():
|
| 33 |
+
try:
|
| 34 |
+
if 'file' not in request.files:
|
| 35 |
+
return jsonify({"error": "No file uploaded"}), 400
|
| 36 |
+
|
| 37 |
+
file = request.files['file']
|
| 38 |
+
if file.filename == '':
|
| 39 |
+
return jsonify({"error": "No file selected"}), 400
|
| 40 |
+
|
| 41 |
+
# Process file without saving locally
|
| 42 |
+
file_stream = io.BytesIO(file.read())
|
| 43 |
+
documents = process_uploaded_file(file_stream, file.filename)
|
| 44 |
+
|
| 45 |
+
# Index documents in Pinecone
|
| 46 |
+
vector_store = index_documents(documents)
|
| 47 |
+
|
| 48 |
+
return jsonify({"message": f"Successfully processed and indexed {len(documents)} chunks from {file.filename}"})
|
| 49 |
+
|
| 50 |
+
except Exception as e:
|
| 51 |
+
logger.error(f"Error in upload_document: {str(e)}")
|
| 52 |
+
return jsonify({"error": str(e)}), 500
|
| 53 |
+
|
| 54 |
+
@app.route('/api/process_text', methods=['POST'])
|
| 55 |
+
def process_text():
|
| 56 |
+
# Get JSON payload
|
| 57 |
+
data = request.get_json()
|
| 58 |
+
try:
|
| 59 |
+
original_text = data['text']
|
| 60 |
+
language_name = data['language']
|
| 61 |
+
except (KeyError, TypeError):
|
| 62 |
+
return jsonify({"error": "Missing 'text' or 'language' in JSON payload"}), 400
|
| 63 |
+
|
| 64 |
+
# Map language name to language code
|
| 65 |
+
if language_name not in LANGUAGE_MAP:
|
| 66 |
+
return jsonify({"error": f"Unsupported language: {language_name}"}), 400
|
| 67 |
+
original_lang_code = LANGUAGE_MAP[language_name]
|
| 68 |
+
|
| 69 |
+
logger.info(f"Original Text: {original_text}")
|
| 70 |
+
logger.info(f"Original Language: {language_name} ({original_lang_code})")
|
| 71 |
+
|
| 72 |
+
# Define an async function for translation
|
| 73 |
+
async def translate_async(text, dest_lang):
|
| 74 |
+
translator = Translator()
|
| 75 |
+
translated = translator.translate(text, dest=dest_lang)
|
| 76 |
+
return translated.text
|
| 77 |
+
|
| 78 |
+
# Translate to English
|
| 79 |
+
if original_lang_code != "en":
|
| 80 |
+
translated_text = asyncio.run(translate_async(original_text, dest_lang="en"))
|
| 81 |
+
else:
|
| 82 |
+
translated_text = original_text
|
| 83 |
+
|
| 84 |
+
logger.info(f"Translated to English: {translated_text}")
|
| 85 |
+
|
| 86 |
+
# Process with RAG
|
| 87 |
+
response = rag_chatbot(translated_text)
|
| 88 |
+
logger.info(f"English Response: {response}")
|
| 89 |
+
|
| 90 |
+
# Translate response back to original language
|
| 91 |
+
if original_lang_code != "en":
|
| 92 |
+
final_response = asyncio.run(translate_async(response, dest_lang=original_lang_code))
|
| 93 |
+
else:
|
| 94 |
+
final_response = response
|
| 95 |
+
|
| 96 |
+
logger.info(f"Final Response (in original language): {final_response}")
|
| 97 |
+
|
| 98 |
+
# Return the final response
|
| 99 |
+
return jsonify({"response": final_response, "language": language_name})
|
| 100 |
+
|
| 101 |
+
if __name__ == '__main__':
|
| 102 |
+
app.run(host='0.0.0.0', port=5000)
|
chatbot.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import google.generativeai as genai
|
| 2 |
+
from pinecone import Pinecone, ServerlessSpec
|
| 3 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 4 |
+
from langchain_pinecone import PineconeVectorStore
|
| 5 |
+
from langchain_google_genai import GoogleGenerativeAIEmbeddings
|
| 6 |
+
from langchain_core.documents import Document
|
| 7 |
+
import io
|
| 8 |
+
import PyPDF2
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import logging
|
| 11 |
+
import asyncio
|
| 12 |
+
from dotenv import load_dotenv
|
| 13 |
+
import os
|
| 14 |
+
import uuid
|
| 15 |
+
|
| 16 |
+
# Set up logging
|
| 17 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
# Load environment variables
|
| 21 |
+
load_dotenv()
|
| 22 |
+
|
| 23 |
+
# Configure Gemini API
|
| 24 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
| 25 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 26 |
+
|
| 27 |
+
# Initialize Pinecone
|
| 28 |
+
PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
|
| 29 |
+
pc = Pinecone(api_key=PINECONE_API_KEY)
|
| 30 |
+
cloud = os.environ.get('PINECONE_CLOUD', 'aws')
|
| 31 |
+
region = os.environ.get('PINECONE_REGION', 'us-east-1')
|
| 32 |
+
spec = ServerlessSpec(cloud=cloud, region=region)
|
| 33 |
+
|
| 34 |
+
# Define index name and embedding dimension
|
| 35 |
+
index_name = "rag-donor-index"
|
| 36 |
+
embedding_dimension = 768 # For text-embedding-004
|
| 37 |
+
|
| 38 |
+
# Check if index exists, create if not
|
| 39 |
+
if index_name not in pc.list_indexes().names():
|
| 40 |
+
logger.info(f"Creating Pinecone index: {index_name}")
|
| 41 |
+
pc.create_index(
|
| 42 |
+
name=index_name,
|
| 43 |
+
dimension=embedding_dimension,
|
| 44 |
+
metric="cosine",
|
| 45 |
+
spec=spec
|
| 46 |
+
)
|
| 47 |
+
# Wait for index to be ready
|
| 48 |
+
while not pc.describe_index(index_name).status['ready']:
|
| 49 |
+
asyncio.sleep(1)
|
| 50 |
+
|
| 51 |
+
logger.info(f"Pinecone index {index_name} is ready.")
|
| 52 |
+
|
| 53 |
+
# Initialize embeddings
|
| 54 |
+
embeddings = GoogleGenerativeAIEmbeddings(model="models/text-embedding-004", google_api_key=GEMINI_API_KEY)
|
| 55 |
+
|
| 56 |
+
# Function to process uploaded file (PDF, text, CSV, or XLSX) without saving locally
|
| 57 |
+
def process_uploaded_file(file_stream, filename):
|
| 58 |
+
logger.info(f"Processing uploaded file: {filename}")
|
| 59 |
+
try:
|
| 60 |
+
if filename.lower().endswith('.pdf'):
|
| 61 |
+
logger.info("Processing as PDF file.")
|
| 62 |
+
pdf_reader = PyPDF2.PdfReader(file_stream)
|
| 63 |
+
text = ""
|
| 64 |
+
for page in pdf_reader.pages:
|
| 65 |
+
text += page.extract_text() or ""
|
| 66 |
+
|
| 67 |
+
# Split PDF content into chunks
|
| 68 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
| 69 |
+
chunk_size=500,
|
| 70 |
+
chunk_overlap=100
|
| 71 |
+
)
|
| 72 |
+
chunks = text_splitter.split_text(text)
|
| 73 |
+
documents = [Document(page_content=chunk, metadata={"source": filename, "chunk_id": str(uuid.uuid4())}) for chunk in chunks]
|
| 74 |
+
logger.info(f"Extracted {len(documents)} chunks from PDF.")
|
| 75 |
+
return documents
|
| 76 |
+
|
| 77 |
+
elif filename.lower().endswith(('.txt', '.md')):
|
| 78 |
+
logger.info("Processing as text file.")
|
| 79 |
+
content = file_stream.read().decode('utf-8', errors='replace')
|
| 80 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
| 81 |
+
chunk_size=500,
|
| 82 |
+
chunk_overlap=100
|
| 83 |
+
)
|
| 84 |
+
chunks = text_splitter.split_text(content)
|
| 85 |
+
documents = [Document(page_content=chunk, metadata={"source": filename, "chunk_id": str(uuid.uuid4())}) for chunk in chunks]
|
| 86 |
+
logger.info(f"Extracted {len(documents)} chunks from text file.")
|
| 87 |
+
return documents
|
| 88 |
+
|
| 89 |
+
elif filename.lower().endswith('.csv'):
|
| 90 |
+
logger.info("Processing as CSV file.")
|
| 91 |
+
df = pd.read_csv(file_stream)
|
| 92 |
+
# Convert DataFrame to string representation
|
| 93 |
+
text = df.to_string()
|
| 94 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
| 95 |
+
chunk_size=500,
|
| 96 |
+
chunk_overlap=100
|
| 97 |
+
)
|
| 98 |
+
chunks = text_splitter.split_text(text)
|
| 99 |
+
documents = [Document(page_content=chunk, metadata={"source": filename, "chunk_id": str(uuid.uuid4())}) for chunk in chunks]
|
| 100 |
+
logger.info(f"Extracted {len(documents)} chunks from CSV.")
|
| 101 |
+
return documents
|
| 102 |
+
|
| 103 |
+
elif filename.lower().endswith('.xlsx'):
|
| 104 |
+
logger.info("Processing as XLSX file.")
|
| 105 |
+
df = pd.read_excel(file_stream, engine='openpyxl')
|
| 106 |
+
# Convert DataFrame to string representation
|
| 107 |
+
text = df.to_string()
|
| 108 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
| 109 |
+
chunk_size=500,
|
| 110 |
+
chunk_overlap=100
|
| 111 |
+
)
|
| 112 |
+
chunks = text_splitter.split_text(text)
|
| 113 |
+
documents = [Document(page_content=chunk, metadata={"source": filename, "chunk_id": str(uuid.uuid4())}) for chunk in chunks]
|
| 114 |
+
logger.info(f"Extracted {len(documents)} chunks from XLSX.")
|
| 115 |
+
return documents
|
| 116 |
+
|
| 117 |
+
else:
|
| 118 |
+
raise ValueError("Unsupported file type. Only PDF, text, CSV, and XLSX files are supported.")
|
| 119 |
+
|
| 120 |
+
except Exception as e:
|
| 121 |
+
logger.error(f"Error processing file {filename}: {str(e)}")
|
| 122 |
+
raise Exception(f"Error processing file: {str(e)}")
|
| 123 |
+
|
| 124 |
+
# Function to index documents in Pinecone
|
| 125 |
+
def index_documents(documents, namespace="chatbot-knowledge", batch_size=50):
|
| 126 |
+
logger.info(f"Indexing {len(documents)} documents in Pinecone.")
|
| 127 |
+
try:
|
| 128 |
+
vector_store = PineconeVectorStore(
|
| 129 |
+
index_name=index_name,
|
| 130 |
+
embedding=embeddings,
|
| 131 |
+
namespace=namespace
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# Batch documents to avoid Pinecone size limits
|
| 135 |
+
for i in range(0, len(documents), batch_size):
|
| 136 |
+
batch = documents[i:i + batch_size]
|
| 137 |
+
batch_size_bytes = sum(len(doc.page_content.encode('utf-8')) for doc in batch)
|
| 138 |
+
if batch_size_bytes > 4_000_000:
|
| 139 |
+
logger.warning(f"Batch size {batch_size_bytes} bytes exceeds Pinecone limit. Reducing batch size.")
|
| 140 |
+
smaller_batch_size = batch_size // 2
|
| 141 |
+
for j in range(0, len(batch), smaller_batch_size):
|
| 142 |
+
smaller_batch = batch[j:j + smaller_batch_size]
|
| 143 |
+
vector_store.add_documents(smaller_batch)
|
| 144 |
+
logger.info(f"Indexed batch {j // smaller_batch_size + 1} of {len(batch) // smaller_batch_size + 1}")
|
| 145 |
+
else:
|
| 146 |
+
vector_store.add_documents(batch)
|
| 147 |
+
logger.info(f"Indexed batch {i // batch_size + 1} of {len(documents) // batch_size + 1}")
|
| 148 |
+
|
| 149 |
+
logger.info("Document indexing completed.")
|
| 150 |
+
return vector_store
|
| 151 |
+
|
| 152 |
+
except Exception as e:
|
| 153 |
+
logger.error(f"Error indexing documents: {e}")
|
| 154 |
+
raise Exception(f"Error indexing documents: {e}")
|
| 155 |
+
|
| 156 |
+
# RAG chatbot function
|
| 157 |
+
def rag_chatbot(query, namespace="chatbot-knowledge"):
|
| 158 |
+
logger.info(f"Processing query: {query}")
|
| 159 |
+
try:
|
| 160 |
+
# Initialize vector store
|
| 161 |
+
vector_store = PineconeVectorStore(
|
| 162 |
+
index_name=index_name,
|
| 163 |
+
embedding=embeddings,
|
| 164 |
+
namespace=namespace
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
# Retrieve relevant documents
|
| 168 |
+
relevant_docs_with_scores = vector_store.similarity_search_with_score(query, k=3)
|
| 169 |
+
for doc, score in relevant_docs_with_scores:
|
| 170 |
+
logger.info(f"Score: {score:.4f} | Document: {doc.page_content}")
|
| 171 |
+
|
| 172 |
+
# Combine context from retrieved documents
|
| 173 |
+
context = "\n".join([doc.page_content for doc, score in relevant_docs_with_scores])
|
| 174 |
+
|
| 175 |
+
# Create prompt for Gemini
|
| 176 |
+
prompt = f"""You are a helpful chatbot that answers questions based on provided context.
|
| 177 |
+
Context:
|
| 178 |
+
{context}
|
| 179 |
+
|
| 180 |
+
User Query: {query}
|
| 181 |
+
|
| 182 |
+
Provide a concise and accurate answer based on the context. If the context doesn't contain relevant information, say so and provide a general response if applicable.
|
| 183 |
+
"""
|
| 184 |
+
|
| 185 |
+
# Initialize Gemini model
|
| 186 |
+
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 187 |
+
|
| 188 |
+
# Generate response
|
| 189 |
+
response = model.generate_content(prompt)
|
| 190 |
+
logger.info("Generated response successfully.")
|
| 191 |
+
return response.text
|
| 192 |
+
|
| 193 |
+
except Exception as e:
|
| 194 |
+
logger.error(f"Error processing query: {e}")
|
| 195 |
+
return f"Error processing query: {e}"
|
requirements.txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask
|
| 2 |
+
#openai
|
| 3 |
+
python-dotenv
|
| 4 |
+
googletrans
|
| 5 |
+
google-generativeai
|
| 6 |
+
pinecone-client
|
| 7 |
+
langchain
|
| 8 |
+
langchain-pinecone
|
| 9 |
+
langchain-google-genai
|
| 10 |
+
charset-normalizer
|
| 11 |
+
PyPDF2
|
| 12 |
+
pdfplumber
|
| 13 |
+
langchain-community
|
| 14 |
+
flask-cors
|
| 15 |
+
sentence-transformers
|
| 16 |
+
nltk
|
| 17 |
+
pandas
|
| 18 |
+
openpyxl
|
templates/index.html
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8" />
|
| 5 |
+
<title>Voice Command</title>
|
| 6 |
+
<style>
|
| 7 |
+
body {
|
| 8 |
+
font-family: Arial, sans-serif;
|
| 9 |
+
}
|
| 10 |
+
.chat-container {
|
| 11 |
+
max-width: 400px;
|
| 12 |
+
margin: 20px auto;
|
| 13 |
+
padding: 10px;
|
| 14 |
+
border: 1px solid #ccc;
|
| 15 |
+
border-radius: 5px;
|
| 16 |
+
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
|
| 17 |
+
}
|
| 18 |
+
.user-message {
|
| 19 |
+
background-color: #f0f0f0;
|
| 20 |
+
border-radius: 5px;
|
| 21 |
+
padding: 5px 10px;
|
| 22 |
+
margin: 5px 0;
|
| 23 |
+
text-align: right;
|
| 24 |
+
}
|
| 25 |
+
.bot-message {
|
| 26 |
+
background-color: #d3e9ff;
|
| 27 |
+
border-radius: 5px;
|
| 28 |
+
padding: 5px 10px;
|
| 29 |
+
margin: 5px 0;
|
| 30 |
+
}
|
| 31 |
+
#languageSelector {
|
| 32 |
+
width: 100%;
|
| 33 |
+
margin-top: 10px;
|
| 34 |
+
padding: 5px;
|
| 35 |
+
border-radius: 5px;
|
| 36 |
+
border: 1px solid #ccc;
|
| 37 |
+
}
|
| 38 |
+
#status {
|
| 39 |
+
color: grey;
|
| 40 |
+
font-weight: 600;
|
| 41 |
+
margin-top: 10px;
|
| 42 |
+
text-align: center;
|
| 43 |
+
}
|
| 44 |
+
#testSpeakerButton {
|
| 45 |
+
display: block;
|
| 46 |
+
margin: 10px auto;
|
| 47 |
+
padding: 10px 20px;
|
| 48 |
+
border: none;
|
| 49 |
+
border-radius: 5px;
|
| 50 |
+
background: #28a745;
|
| 51 |
+
color: white;
|
| 52 |
+
cursor: pointer;
|
| 53 |
+
font-weight: 600;
|
| 54 |
+
}
|
| 55 |
+
#uploadButton {
|
| 56 |
+
display: block;
|
| 57 |
+
margin: 10px auto;
|
| 58 |
+
padding: 10px 20px;
|
| 59 |
+
border: none;
|
| 60 |
+
border-radius: 5px;
|
| 61 |
+
background: #2196F3;
|
| 62 |
+
color: white;
|
| 63 |
+
cursor: pointer;
|
| 64 |
+
font-weight: 600;
|
| 65 |
+
}
|
| 66 |
+
.speaker {
|
| 67 |
+
display: flex;
|
| 68 |
+
justify-content: space-between;
|
| 69 |
+
align-items: center;
|
| 70 |
+
width: 100%;
|
| 71 |
+
margin-top: 10px;
|
| 72 |
+
padding: 5px;
|
| 73 |
+
box-shadow: 0 0 13px #0000003d;
|
| 74 |
+
border-radius: 5px;
|
| 75 |
+
}
|
| 76 |
+
#textInput {
|
| 77 |
+
flex: 1;
|
| 78 |
+
padding: 8px;
|
| 79 |
+
border: none;
|
| 80 |
+
border-radius: 5px;
|
| 81 |
+
outline: none;
|
| 82 |
+
}
|
| 83 |
+
#speech, #sendText {
|
| 84 |
+
padding: 8px 10px;
|
| 85 |
+
border: none;
|
| 86 |
+
border-radius: 5px;
|
| 87 |
+
margin-left: 5px;
|
| 88 |
+
cursor: pointer;
|
| 89 |
+
}
|
| 90 |
+
#speech {
|
| 91 |
+
background-color: #007bff;
|
| 92 |
+
color: white;
|
| 93 |
+
}
|
| 94 |
+
#sendText {
|
| 95 |
+
background-color: #28a745;
|
| 96 |
+
color: white;
|
| 97 |
+
}
|
| 98 |
+
</style>
|
| 99 |
+
</head>
|
| 100 |
+
<body>
|
| 101 |
+
<button id="testSpeakerButton">Speaker Test</button>
|
| 102 |
+
<div class="chat-container">
|
| 103 |
+
<div id="chat-box"></div>
|
| 104 |
+
<select id="languageSelector">
|
| 105 |
+
<option value="English (US)">English (US)</option>
|
| 106 |
+
<option value="Hindi (India)">Hindi (India)</option>
|
| 107 |
+
<option value="Spanish (Spain)">Spanish (Spain)</option>
|
| 108 |
+
<option value="French (France)">French (France)</option>
|
| 109 |
+
<option value="German (Germany)">German (Germany)</option>
|
| 110 |
+
<option value="Arabic (Saudi Arabia)">Arabic (Saudi Arabia)</option>
|
| 111 |
+
</select>
|
| 112 |
+
<input type="file" id="fileUpload" accept=".pdf,.txt,.md,.csv,.xlsx" style="display: none;">
|
| 113 |
+
<button id="uploadButton" onclick="document.getElementById('fileUpload').click()">Upload Document</button>
|
| 114 |
+
|
| 115 |
+
<div class="speaker">
|
| 116 |
+
<input type="text" id="textInput" placeholder="Type your message...">
|
| 117 |
+
<button id="speech">Tap to Speak</button>
|
| 118 |
+
<button id="sendText">Enter</button>
|
| 119 |
+
</div>
|
| 120 |
+
<p id="status"></p>
|
| 121 |
+
</div>
|
| 122 |
+
|
| 123 |
+
<script>
|
| 124 |
+
const statusBar = document.getElementById('status');
|
| 125 |
+
|
| 126 |
+
const speechLangMap = {
|
| 127 |
+
'English (US)': 'en-US',
|
| 128 |
+
'Hindi (India)': 'hi-IN',
|
| 129 |
+
'Spanish (Spain)': 'es-ES',
|
| 130 |
+
'French (France)': 'fr-FR',
|
| 131 |
+
'German (Germany)': 'de-DE',
|
| 132 |
+
'Arabic (Saudi Arabia)': 'ar-SA'
|
| 133 |
+
};
|
| 134 |
+
|
| 135 |
+
const synth = window.speechSynthesis;
|
| 136 |
+
let voices = [];
|
| 137 |
+
|
| 138 |
+
function loadVoices() {
|
| 139 |
+
return new Promise((resolve) => {
|
| 140 |
+
voices = synth.getVoices();
|
| 141 |
+
if (voices.length > 0) {
|
| 142 |
+
resolve(voices);
|
| 143 |
+
} else {
|
| 144 |
+
synth.onvoiceschanged = () => {
|
| 145 |
+
voices = synth.getVoices();
|
| 146 |
+
resolve(voices);
|
| 147 |
+
};
|
| 148 |
+
}
|
| 149 |
+
});
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
async function speakResponse(text, language) {
|
| 153 |
+
const langCode = speechLangMap[language] || 'en-US';
|
| 154 |
+
await loadVoices();
|
| 155 |
+
const utterance = new SpeechSynthesisUtterance(text);
|
| 156 |
+
let selectedVoice = voices.find(voice => voice.lang === langCode);
|
| 157 |
+
if (!selectedVoice) selectedVoice = voices[0];
|
| 158 |
+
utterance.voice = selectedVoice;
|
| 159 |
+
synth.speak(utterance);
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
function runSpeechRecog() {
|
| 163 |
+
const selectedLang = document.getElementById('languageSelector').value;
|
| 164 |
+
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
|
| 165 |
+
recognition.lang = speechLangMap[selectedLang] || 'en-US';
|
| 166 |
+
recognition.onstart = () => statusBar.textContent = 'Listening...';
|
| 167 |
+
recognition.onresult = (event) => {
|
| 168 |
+
const transcript = event.results[0][0].transcript;
|
| 169 |
+
sendMessage(transcript, selectedLang);
|
| 170 |
+
};
|
| 171 |
+
recognition.onerror = (event) => statusBar.textContent = `Error: ${event.error}`;
|
| 172 |
+
recognition.onend = () => statusBar.textContent = '';
|
| 173 |
+
recognition.start();
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
async function sendMessage(message, language) {
|
| 177 |
+
showUserMessage(message);
|
| 178 |
+
try {
|
| 179 |
+
const response = await fetch('/api/process_text', {
|
| 180 |
+
method: 'POST',
|
| 181 |
+
headers: { 'Content-Type': 'application/json' },
|
| 182 |
+
body: JSON.stringify({ text: message, language })
|
| 183 |
+
});
|
| 184 |
+
const data = await response.json();
|
| 185 |
+
showBotMessage(data.response);
|
| 186 |
+
speakResponse(data.response, language);
|
| 187 |
+
} catch (error) {
|
| 188 |
+
console.error('Error:', error);
|
| 189 |
+
showBotMessage('Error: Unable to process request.');
|
| 190 |
+
}
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
function showUserMessage(message) {
|
| 194 |
+
const chatBox = document.getElementById('chat-box');
|
| 195 |
+
chatBox.innerHTML += `<div class="user-message">${message}</div>`;
|
| 196 |
+
chatBox.scrollTop = chatBox.scrollHeight;
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
function showBotMessage(message) {
|
| 200 |
+
const chatBox = document.getElementById('chat-box');
|
| 201 |
+
chatBox.innerHTML += `<div class="bot-message">${message}</div>`;
|
| 202 |
+
chatBox.scrollTop = chatBox.scrollHeight;
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
document.getElementById('speech').addEventListener('click', runSpeechRecog);
|
| 206 |
+
|
| 207 |
+
document.getElementById('sendText').addEventListener('click', () => {
|
| 208 |
+
const text = document.getElementById('textInput').value.trim();
|
| 209 |
+
const language = document.getElementById('languageSelector').value;
|
| 210 |
+
if (text !== '') {
|
| 211 |
+
sendMessage(text, language);
|
| 212 |
+
document.getElementById('textInput').value = '';
|
| 213 |
+
}
|
| 214 |
+
});
|
| 215 |
+
|
| 216 |
+
document.getElementById('textInput').addEventListener('keydown', (e) => {
|
| 217 |
+
if (e.key === 'Enter') {
|
| 218 |
+
e.preventDefault();
|
| 219 |
+
document.getElementById('sendText').click();
|
| 220 |
+
}
|
| 221 |
+
});
|
| 222 |
+
|
| 223 |
+
document.getElementById('testSpeakerButton').addEventListener('click', async () => {
|
| 224 |
+
await loadVoices();
|
| 225 |
+
speakResponse("Speaker works fine", "English (US)");
|
| 226 |
+
});
|
| 227 |
+
|
| 228 |
+
document.getElementById('fileUpload').addEventListener('change', async (event) => {
|
| 229 |
+
const file = event.target.files[0];
|
| 230 |
+
if (!file) return;
|
| 231 |
+
|
| 232 |
+
statusBar.textContent = 'Uploading document...';
|
| 233 |
+
const formData = new FormData();
|
| 234 |
+
formData.append('file', file);
|
| 235 |
+
|
| 236 |
+
try {
|
| 237 |
+
const response = await fetch('/api/upload_document', {
|
| 238 |
+
method: 'POST',
|
| 239 |
+
body: formData
|
| 240 |
+
});
|
| 241 |
+
const data = await response.json();
|
| 242 |
+
statusBar.textContent = data.message || data.error;
|
| 243 |
+
} catch (err) {
|
| 244 |
+
statusBar.textContent = 'Error uploading document: ' + err.message;
|
| 245 |
+
console.error('File upload error:', err);
|
| 246 |
+
}
|
| 247 |
+
});
|
| 248 |
+
|
| 249 |
+
window.onload = loadVoices;
|
| 250 |
+
</script>
|
| 251 |
+
</body>
|
| 252 |
+
</html>
|