diff --git a/examples/ai_soulmate/README.md b/examples/ai_soulmate/README.md new file mode 100644 index 00000000..130aafe8 --- /dev/null +++ b/examples/ai_soulmate/README.md @@ -0,0 +1,66 @@ +## NexaAI SDK Demo: AI Soulmate + +### Introduction: + +This project is an AI chatbot that interacts with users via text and voice. The project offers two options for voice output: using the **Bark** model for on-device text-to-speech or the **OpenAI TTS API** for cloud-based text-to-speech. **Bark** will be slow to generate speech without using GPU, but it's on device. The **OpenAI TTS API** has the advantage in terms of speed, but it is cloud-based and requires you to have an OPENAI API KEY. Each option is designed to provide flexibility based on the user's resources and preferences.You can also choose other options according to your preference. + +- Key features: + + - On-device Character AI + - No privacy concerns + +- File structure: + + - `bark_voice_out/app.py`: main Streamlit app using Bark for voice output + - `bark_voice_out/utils/initialize.py`: initializes chat and load model + - `bark_voice_out/utils/gen_avatar.py`: generates avatar for AI Soulmate + - `bark_voice_out/utils/transcribe.py`: handles voice input to text transcription + - `bark_voice_out/utils/gen_response.py`: handles text and voice output + + - `openai_voice_out/app.py`: main Streamlit app using OpenAI TTS API for voice output + - `openai_voice_out/utils/initialize.py`: initializes chat and load model + - `openai_voice_out/utils/gen_avatar.py`: generates avatar for AI Soulmate + - `openai_voice_out/utils/transcribe.py`: handles voice input to text transcription + - `openai_voice_out/utils/gen_response.py`: handles text and voice output + +### Technical Architecture + +
+ +
+ +### Setup: + +#### Bark Voice Output + +1. Install required packages: + +``` +pip install -r bark_requirements.txt +``` + +2. Usage: + +- Run the Streamlit app: `streamlit run bark_voice_out/app.py` +- Start a chat with text or voice as you like + +#### OpenAI Voice Output + +1. Install required packages: + +``` +pip install -r openai_requirements.txt +``` + +2. Usage: + +- Add your openai key in utils/gen_response.py line 8 +- Run the Streamlit app: `streamlit run openai_voice_out/app.py` +- Start a chat with text or voice as you like + +### Resources: + +- [NexaAI | Model Hub](https://nexaai.com/models) +- [NexaAI | Inference with GGUF models](https://docs.nexaai.com/sdk/inference/gguf) +- [GitHub | BARK](https://github.com/suno-ai/bark) +- [Text to speech - OpenAI API](https://platform.openai.com/docs/guides/text-to-speech) diff --git a/examples/ai_soulmate/bark_requirements.txt b/examples/ai_soulmate/bark_requirements.txt new file mode 100644 index 00000000..5d159df2 --- /dev/null +++ b/examples/ai_soulmate/bark_requirements.txt @@ -0,0 +1,9 @@ +nexaai +sounddevice + +# Bark support +numpy==1.26 +git+https://github.com/suno-ai/bark.git + +# To use GPU: +torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu117 \ No newline at end of file diff --git a/examples/ai_soulmate/bark_voice_out/app.py b/examples/ai_soulmate/bark_voice_out/app.py new file mode 100644 index 00000000..6d23a8b0 --- /dev/null +++ b/examples/ai_soulmate/bark_voice_out/app.py @@ -0,0 +1,120 @@ +import streamlit as st +from utils.initialize import initialize_chat, load_model +from utils.gen_avatar import generate_ai_avatar +from utils.transcribe import record_and_transcribe +from utils.gen_response import generate_chat_response, generate_and_play_response + +ai_avatar = generate_ai_avatar() +default_model = "llama3-uncensored" + +def main(): + col1, col2 = st.columns([5,5], vertical_alignment = "center") + with col1: + st.title("AI Soulmate") + with col2: + st.image(ai_avatar, width=150) + st.caption("Powered by Nexa AI") + + st.sidebar.header("Model Configuration") + model_path = st.sidebar.text_input("Model path", default_model) + + if not model_path: + st.warning( + "Please enter a valid path or identifier for the model in Nexa Model Hub to proceed." + ) + st.stop() + + if ( + "current_model_path" not in st.session_state + or st.session_state.current_model_path != model_path + ): + st.session_state.current_model_path = model_path + st.session_state.nexa_model = load_model(model_path) + if st.session_state.nexa_model is None: + st.stop() + + st.sidebar.header("Generation Parameters") + temperature = st.sidebar.slider( + "Temperature", 0.0, 1.0, st.session_state.nexa_model.params["temperature"] + ) + max_new_tokens = st.sidebar.slider( + "Max New Tokens", 1, 1000, st.session_state.nexa_model.params["max_new_tokens"] + ) + top_k = st.sidebar.slider("Top K", 1, 100, st.session_state.nexa_model.params["top_k"]) + top_p = st.sidebar.slider( + "Top P", 0.0, 1.0, st.session_state.nexa_model.params["top_p"] + ) + + st.session_state.nexa_model.params.update( + { + "temperature": temperature, + "max_new_tokens": max_new_tokens, + "top_k": top_k, + "top_p": top_p, + } + ) + + initialize_chat() + for message in st.session_state.messages: + if message["role"] != "system": + if message["role"] == "user": + with st.chat_message(message["role"]): + st.markdown(message["content"]) + else: + with st.chat_message(message["role"], avatar=ai_avatar): + st.markdown(message["content"]) + + if st.button("🎙️ Start Voice Chat"): + transcribed_text = record_and_transcribe() + if transcribed_text: + st.session_state.messages.append({"role": "user", "content": transcribed_text}) + with st.chat_message("user"): + st.markdown(transcribed_text) + + with st.chat_message("assistant", avatar=ai_avatar): + response_placeholder = st.empty() + full_response = "" + for chunk in generate_chat_response(st.session_state.nexa_model): + choice = chunk["choices"][0] + if "delta" in choice: + delta = choice["delta"] + content = delta.get("content", "") + elif "text" in choice: + delta = choice["text"] + content = delta + + full_response += content + response_placeholder.markdown(full_response, unsafe_allow_html=True) + response_placeholder.markdown(full_response) + + generate_and_play_response(full_response) + + st.session_state.messages.append({"role": "assistant", "content": full_response}) + + if prompt := st.chat_input("Say something..."): + st.session_state.messages.append({"role": "user", "content": prompt}) + with st.chat_message("user"): + st.markdown(prompt) + + with st.chat_message("assistant", avatar=ai_avatar): + response_placeholder = st.empty() + full_response = "" + for chunk in generate_chat_response(st.session_state.nexa_model): + choice = chunk["choices"][0] + if "delta" in choice: + delta = choice["delta"] + content = delta.get("content", "") + elif "text" in choice: + delta = choice["text"] + content = delta + + full_response += content + response_placeholder.markdown(full_response, unsafe_allow_html=True) + response_placeholder.markdown(full_response) + + generate_and_play_response(full_response) + + st.session_state.messages.append({"role": "assistant", "content": full_response}) + +if __name__ == "__main__": + main() diff --git a/examples/ai_soulmate/bark_voice_out/utils/gen_avatar.py b/examples/ai_soulmate/bark_voice_out/utils/gen_avatar.py new file mode 100644 index 00000000..a6819cde --- /dev/null +++ b/examples/ai_soulmate/bark_voice_out/utils/gen_avatar.py @@ -0,0 +1,27 @@ +import streamlit as st +from nexa.gguf import NexaImageInference + +@st.cache_resource +def generate_ai_avatar(): + try: + image_model = NexaImageInference(model_path="lcm-dreamshaper", local_path=None) + + images = image_model.txt2img( + prompt="A girlfriend with long black hair", + cfg_scale=image_model.params["guidance_scale"], + width=image_model.params["width"], + height=image_model.params["height"], + sample_steps=image_model.params["num_inference_steps"], + seed=image_model.params["random_seed"], + ) + + if images and len(images) > 0: + avatar_path = "ai_avatar.png" + images[0].save(avatar_path) + return avatar_path + else: + st.error("No image was generated.") + return None + except Exception as e: + st.error(f"Error generating AI avatar: {str(e)}") + return None diff --git a/examples/ai_soulmate/bark_voice_out/utils/gen_response.py b/examples/ai_soulmate/bark_voice_out/utils/gen_response.py new file mode 100644 index 00000000..4e44473e --- /dev/null +++ b/examples/ai_soulmate/bark_voice_out/utils/gen_response.py @@ -0,0 +1,62 @@ +from typing import List, Iterator +import numpy as np +from nexa.gguf import NexaTextInference +from bark import SAMPLE_RATE, generate_audio, preload_models +from bark.api import semantic_to_waveform, generate_text_semantic +import streamlit as st +import sounddevice as sd + +def split_text(text: str, max_length: int = 200) -> List[str]: + words = text.split() + chunks = [] + chunk = [] + + for word in words: + if len(" ".join(chunk + [word])) > max_length: + chunks.append(" ".join(chunk)) + chunk = [word] + else: + chunk.append(word) + + if chunk: + chunks.append(" ".join(chunk)) + + return chunks + +def generate_and_play_response(response_text: str): + text_chunks = split_text(response_text) + + silence = np.zeros(int(0.25 * SAMPLE_RATE)) + GEN_TEMP = 0.6 + SPEAKER = "v2/en_speaker_9" + + pieces = [] + for sentence in text_chunks: + semantic_tokens = generate_text_semantic( + sentence, + history_prompt=SPEAKER, + temp=GEN_TEMP, + min_eos_p=0.05 + ) + audio_array = semantic_to_waveform(semantic_tokens, history_prompt=SPEAKER) + pieces.append(audio_array) + pieces.append(silence.copy()) + + combined_audio = np.concatenate(pieces) + play_audio(SAMPLE_RATE, combined_audio) + +def play_audio(sample_rate, audio_array): + sd.play(audio_array, sample_rate) + sd.wait() + +def generate_chat_response(nexa_model: NexaTextInference) -> Iterator: + messages = st.session_state.messages + response = nexa_model.create_chat_completion( + messages=messages, + temperature=nexa_model.params["temperature"], + max_tokens=nexa_model.params["max_new_tokens"], + top_k=nexa_model.params["top_k"], + top_p=nexa_model.params["top_p"], + stream=True + ) + return response diff --git a/examples/ai_soulmate/bark_voice_out/utils/initialize.py b/examples/ai_soulmate/bark_voice_out/utils/initialize.py new file mode 100644 index 00000000..ad215158 --- /dev/null +++ b/examples/ai_soulmate/bark_voice_out/utils/initialize.py @@ -0,0 +1,23 @@ +import streamlit as st +from nexa.gguf import NexaTextInference + +initial_prompt = """ +# You are Claudia, my perfect soul mate. You're empathetic, kind, and a great listener. Start by introuducing yourself briefly. You can't say more than 35 words in a sentence. +""" + +def initialize_chat(): + if "messages" not in st.session_state or not st.session_state.messages: + st.session_state.messages = [{"role": "system", "content": initial_prompt}] + +@st.cache_resource +def load_model(model_path): + st.session_state.messages = [] + nexa_model = NexaTextInference( + model_path=model_path, + local_path=None, + temperature=0.9, + max_new_tokens=256, + top_k=50, + top_p=1.0, + ) + return nexa_model \ No newline at end of file diff --git a/examples/ai_soulmate/bark_voice_out/utils/transcribe.py b/examples/ai_soulmate/bark_voice_out/utils/transcribe.py new file mode 100644 index 00000000..3a53a0b0 --- /dev/null +++ b/examples/ai_soulmate/bark_voice_out/utils/transcribe.py @@ -0,0 +1,31 @@ +import streamlit as st +import sounddevice as sd +from scipy.io.wavfile import write +from tempfile import NamedTemporaryFile +from nexa.gguf import NexaVoiceInference + +voice_model = NexaVoiceInference( + model_path="faster-whisper-base", + local_path=None, + beam_size=5, + task="transcribe", + temperature=0.0, + compute_type="default", +) + +def record_and_transcribe(duration=5, fs=16000): + info_placeholder = st.empty() + info_placeholder.info("Recording...") + + recording = sd.rec(int(duration * fs), samplerate=fs, channels=1) + sd.wait() + + info_placeholder.empty() + + with NamedTemporaryFile(delete=False, suffix=".wav") as f: + write(f.name, fs, recording) + audio_path = f.name + + segments, _ = voice_model.model.transcribe(audio_path) + transcription = "".join(segment.text for segment in segments) + return transcription diff --git a/examples/ai_soulmate/openai_requirements.txt b/examples/ai_soulmate/openai_requirements.txt new file mode 100644 index 00000000..4c909357 --- /dev/null +++ b/examples/ai_soulmate/openai_requirements.txt @@ -0,0 +1,5 @@ +nexaai +sounddevice + +# OpenAI API support +openai \ No newline at end of file diff --git a/examples/ai_soulmate/openai_voice_out/app.py b/examples/ai_soulmate/openai_voice_out/app.py new file mode 100644 index 00000000..fdb2d03f --- /dev/null +++ b/examples/ai_soulmate/openai_voice_out/app.py @@ -0,0 +1,139 @@ +import streamlit as st +import base64 +from utils.initialize import initialize_chat, load_model +from utils.gen_avatar import generate_ai_avatar +from utils.transcribe import record_and_transcribe +from utils.gen_response import generate_chat_response, generate_and_play_response + +ai_avatar = generate_ai_avatar() +default_model = "llama3-uncensored" + +def main(): + col1, col2 = st.columns([5,5], vertical_alignment = "center") + with col1: + st.title("AI Soulmate") + with col2: + st.image(ai_avatar, width=150) + st.caption("Powered by Nexa AI") + + st.sidebar.header("Model Configuration") + model_path = st.sidebar.text_input("Model path", default_model) + + if not model_path: + st.warning( + "Please enter a valid path or identifier for the model in Nexa Model Hub to proceed." + ) + st.stop() + + if ( + "current_model_path" not in st.session_state + or st.session_state.current_model_path != model_path + ): + st.session_state.current_model_path = model_path + st.session_state.nexa_model = load_model(model_path) + if st.session_state.nexa_model is None: + st.stop() + + st.sidebar.header("Generation Parameters") + temperature = st.sidebar.slider( + "Temperature", 0.0, 1.0, st.session_state.nexa_model.params["temperature"] + ) + max_new_tokens = st.sidebar.slider( + "Max New Tokens", 1, 1000, st.session_state.nexa_model.params["max_new_tokens"] + ) + top_k = st.sidebar.slider("Top K", 1, 100, st.session_state.nexa_model.params["top_k"]) + top_p = st.sidebar.slider( + "Top P", 0.0, 1.0, st.session_state.nexa_model.params["top_p"] + ) + + st.session_state.nexa_model.params.update( + { + "temperature": temperature, + "max_new_tokens": max_new_tokens, + "top_k": top_k, + "top_p": top_p, + } + ) + + initialize_chat() + for message in st.session_state.messages: + if message["role"] != "system": + if message["role"] == "user": + with st.chat_message(message["role"]): + st.markdown(message["content"]) + else: + with st.chat_message(message["role"], avatar=ai_avatar): + st.markdown(message["content"]) + + if st.button("🎙️ Start Voice Chat"): + transcribed_text = record_and_transcribe() + if transcribed_text: + st.session_state.messages.append({"role": "user", "content": transcribed_text}) + with st.chat_message("user"): + st.markdown(transcribed_text) + + with st.chat_message("assistant", avatar=ai_avatar): + response_placeholder = st.empty() + full_response = "" + for chunk in generate_chat_response(st.session_state.nexa_model): + choice = chunk["choices"][0] + if "delta" in choice: + delta = choice["delta"] + content = delta.get("content", "") + elif "text" in choice: + delta = choice["text"] + content = delta + + full_response += content + response_placeholder.markdown(full_response, unsafe_allow_html=True) + response_placeholder.markdown(full_response) + + audio_path = generate_and_play_response(full_response) + + with open(audio_path, "rb") as audio_file: + audio_bytes = audio_file.read() + audio_base64 = base64.b64encode(audio_bytes).decode("utf-8") + st.markdown(f""" + + """, unsafe_allow_html=True) + + st.session_state.messages.append({"role": "assistant", "content": full_response}) + + if prompt := st.chat_input("Say something..."): + st.session_state.messages.append({"role": "user", "content": prompt}) + with st.chat_message("user"): + st.markdown(prompt) + + with st.chat_message("assistant", avatar=ai_avatar): + response_placeholder = st.empty() + full_response = "" + for chunk in generate_chat_response(st.session_state.nexa_model): + choice = chunk["choices"][0] + if "delta" in choice: + delta = choice["delta"] + content = delta.get("content", "") + elif "text" in choice: + delta = choice["text"] + content = delta + + full_response += content + response_placeholder.markdown(full_response, unsafe_allow_html=True) + response_placeholder.markdown(full_response) + + audio_path = generate_and_play_response(full_response) + + with open(audio_path, "rb") as audio_file: + audio_bytes = audio_file.read() + audio_base64 = base64.b64encode(audio_bytes).decode("utf-8") + st.markdown(f""" + + """, unsafe_allow_html=True) + + st.session_state.messages.append({"role": "assistant", "content": full_response}) + +if __name__ == "__main__": + main() diff --git a/examples/ai_soulmate/openai_voice_out/utils/gen_avatar.py b/examples/ai_soulmate/openai_voice_out/utils/gen_avatar.py new file mode 100644 index 00000000..a6819cde --- /dev/null +++ b/examples/ai_soulmate/openai_voice_out/utils/gen_avatar.py @@ -0,0 +1,27 @@ +import streamlit as st +from nexa.gguf import NexaImageInference + +@st.cache_resource +def generate_ai_avatar(): + try: + image_model = NexaImageInference(model_path="lcm-dreamshaper", local_path=None) + + images = image_model.txt2img( + prompt="A girlfriend with long black hair", + cfg_scale=image_model.params["guidance_scale"], + width=image_model.params["width"], + height=image_model.params["height"], + sample_steps=image_model.params["num_inference_steps"], + seed=image_model.params["random_seed"], + ) + + if images and len(images) > 0: + avatar_path = "ai_avatar.png" + images[0].save(avatar_path) + return avatar_path + else: + st.error("No image was generated.") + return None + except Exception as e: + st.error(f"Error generating AI avatar: {str(e)}") + return None diff --git a/examples/ai_soulmate/openai_voice_out/utils/gen_response.py b/examples/ai_soulmate/openai_voice_out/utils/gen_response.py new file mode 100644 index 00000000..cfdd9fbd --- /dev/null +++ b/examples/ai_soulmate/openai_voice_out/utils/gen_response.py @@ -0,0 +1,32 @@ +import streamlit as st +from typing import Iterator +from typing import Iterator +from nexa.gguf import NexaTextInference +from pathlib import Path +from openai import OpenAI + +client = OpenAI(api_key="YOUR_OPENAI_API_KEY") + + +def generate_and_play_response(response_text: str): + speech_file_path = Path(__file__).parent / "speech.mp3" + response = client.audio.speech.create( + model="tts-1", + voice="shimmer", + input=response_text + ) + + response.stream_to_file(speech_file_path) + return str(speech_file_path) # Return the path as a string + +def generate_chat_response(nexa_model: NexaTextInference) -> Iterator: + messages = st.session_state.messages + response = nexa_model.create_chat_completion( + messages=messages, + temperature=nexa_model.params["temperature"], + max_tokens=nexa_model.params["max_new_tokens"], + top_k=nexa_model.params["top_k"], + top_p=nexa_model.params["top_p"], + stream=True + ) + return response diff --git a/examples/ai_soulmate/openai_voice_out/utils/initialize.py b/examples/ai_soulmate/openai_voice_out/utils/initialize.py new file mode 100644 index 00000000..e50314da --- /dev/null +++ b/examples/ai_soulmate/openai_voice_out/utils/initialize.py @@ -0,0 +1,23 @@ +import streamlit as st +from nexa.gguf import NexaTextInference + +initial_prompt = """ +# You are Claudia, my perfect soul mate. You're empathetic, kind, and a great listener. Start by introuducing yourself briefly. +""" + +def initialize_chat(): + if "messages" not in st.session_state or not st.session_state.messages: + st.session_state.messages = [{"role": "system", "content": initial_prompt}] + +@st.cache_resource +def load_model(model_path): + st.session_state.messages = [] + nexa_model = NexaTextInference( + model_path=model_path, + local_path=None, + temperature=0.9, + max_new_tokens=256, + top_k=50, + top_p=1.0, + ) + return nexa_model \ No newline at end of file diff --git a/examples/ai_soulmate/openai_voice_out/utils/transcribe.py b/examples/ai_soulmate/openai_voice_out/utils/transcribe.py new file mode 100644 index 00000000..f27c8b7c --- /dev/null +++ b/examples/ai_soulmate/openai_voice_out/utils/transcribe.py @@ -0,0 +1,31 @@ +import streamlit as st +import sounddevice as sd +from scipy.io.wavfile import write +from tempfile import NamedTemporaryFile +from nexa.gguf import NexaVoiceInference + +voice_model = NexaVoiceInference( + model_path="faster-whisper-tiny", + local_path=None, + beam_size=5, + task="transcribe", + temperature=0.0, + compute_type="default", +) + +def record_and_transcribe(duration=5, fs=16000): + info_placeholder = st.empty() + info_placeholder.info("Recording...") + + recording = sd.rec(int(duration * fs), samplerate=fs, channels=1) + sd.wait() + + info_placeholder.empty() + + with NamedTemporaryFile(delete=False, suffix=".wav") as f: + write(f.name, fs, recording) + audio_path = f.name + + segments, _ = voice_model.model.transcribe(audio_path) + transcription = "".join(segment.text for segment in segments) + return transcription diff --git a/examples/financial-advisor/README.md b/examples/financial-advisor/README.md new file mode 100644 index 00000000..1b222b87 --- /dev/null +++ b/examples/financial-advisor/README.md @@ -0,0 +1,37 @@ +## NexaAI SDK Demo: On-device Personal Finance advisor + +### Introduction: + +- Key features: + + - On-device processing for data privacy + - Adjustable parameters (model, temperature, max tokens, top-k, top-p, etc.) + - FAISS index for efficient similarity search + - Interactive chat interface for financial queries + +- File structure: + + - `app.py`: main Streamlit application + - `utils/text_generator.py`: handles similarity search and text generation + - `assets/fake_bank_statements`: fake bank statement for testing purpose + +### Setup: + +1. Install required packages: + +``` +pip install -r requirements.txt +``` + +2. Usage: + +- Run the Streamlit app: `streamlit run app.py` +- Upload PDF financial docs (bank statements, SEC filings, etc.) and process them +- Use the chat interface to query your financial data + +### Resources: + +- [NexaAI | Model Hub](https://nexaai.com/models) +- [NexaAI | Inference with GGUF models](https://docs.nexaai.com/sdk/inference/gguf) +- [GitHub | FAISS](https://github.com/facebookresearch/faiss) +- [Local RAG with Unstructured, Ollama, FAISS and LangChain](https://medium.com/@dirakx/local-rag-with-unstructured-ollama-faiss-and-langchain-35e9dfeb56f1) diff --git a/examples/financial-advisor/app.py b/examples/financial-advisor/app.py new file mode 100644 index 00000000..0043633b --- /dev/null +++ b/examples/financial-advisor/app.py @@ -0,0 +1,278 @@ +import sys +import os +import streamlit as st +import shutil +import pdfplumber +from sentence_transformers import SentenceTransformer +import faiss +import numpy as np +import re +import traceback +import logging +from utils.financial_analyzer import FinancialAnalyzer + +# set up logging: +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# set a default model path & allow override from command line: +default_model = "gemma" +if len(sys.argv) > 1: + default_model = sys.argv[1] + +@st.cache_resource +def load_model(model_path): + return FinancialAnalyzer(model_path) + +def generate_response(query: str) -> str: + result = st.session_state.nexa_model.financial_analysis(query) + if isinstance(result, dict) and "error" in result: + return f"An error occurred: {result['error']}" + return result + +def extract_text_from_pdf(pdf_path): + try: + with pdfplumber.open(pdf_path) as pdf: + text = '' + for page in pdf.pages: + text += page.extract_text() + '\n' + return text + except Exception as e: + logger.error(f"Error extracting text from PDF {pdf_path}: {str(e)}") + return None + +def chunk_text(text, model, max_tokens=256, overlap=20): + try: + if not text: + logger.warning("Empty text provided to chunk_text function") + return [] + + sentences = re.split(r'(?<=[.!?])\s+', text) + chunks = [] + current_chunk = [] + current_tokens = 0 + + for sentence in sentences: + sentence_tokens = len(model.tokenize(sentence)) + if current_tokens + sentence_tokens > max_tokens: + if current_chunk: + chunks.append(' '.join(current_chunk)) + current_chunk = [sentence] + current_tokens = sentence_tokens + else: + current_chunk.append(sentence) + current_tokens += sentence_tokens + + if current_chunk: + chunks.append(' '.join(current_chunk)) + + logger.info(f"Created {len(chunks)} chunks from text") + return chunks + except Exception as e: + logger.error(f"Error chunking text: {str(e)}") + logger.error(traceback.format_exc()) + return [] + +def create_embeddings(chunks, model): + try: + if not chunks: + logger.warning("No chunks provided for embedding creation") + return None + embeddings = model.encode(chunks) + logger.info(f"Created embeddings of shape: {embeddings.shape}") + return embeddings + except Exception as e: + logger.error(f"Error creating embeddings: {str(e)}") + logger.error(traceback.format_exc()) + return None + +def build_faiss_index(embeddings): + try: + if embeddings is None or embeddings.shape[0] == 0: + logger.warning("No valid embeddings provided for FAISS index creation") + return None + dimension = embeddings.shape[1] + index = faiss.IndexFlatL2(dimension) + index.add(embeddings.astype('float32')) + logger.info(f"Built FAISS index with {index.ntotal} vectors") + return index + except Exception as e: + logger.error(f"Error building FAISS index: {str(e)}") + logger.error(traceback.format_exc()) + return None + +def process_pdfs(uploaded_files): + if not uploaded_files: + st.warning("Please upload PDF files first.") + return False + + input_dir = "./assets/input" + output_dir = "./assets/output/processed_data" + + # clear existing files in the input directory: + if os.path.exists(input_dir): + shutil.rmtree(input_dir) + os.makedirs(input_dir, exist_ok=True) + + # save uploaded files to the input directory: + for uploaded_file in uploaded_files: + with open(os.path.join(input_dir, uploaded_file.name), "wb") as f: + f.write(uploaded_file.getbuffer()) + + # process PDFs: + try: + model = SentenceTransformer('all-MiniLM-L6-v2') + all_chunks = [] + + for filename in os.listdir(input_dir): + if filename.endswith('.pdf'): + pdf_path = os.path.join(input_dir, filename) + text = extract_text_from_pdf(pdf_path) + if text is None: + logger.warning(f"Skipping {filename} due to extraction error") + continue + file_chunks = chunk_text(text, model) + if file_chunks: + all_chunks.extend(file_chunks) + st.write(f"Processed {filename}: {len(file_chunks)} chunks") + else: + logger.warning(f"No chunks created for {filename}") + + if not all_chunks: + st.warning("No valid content found in the uploaded PDFs.") + return False + + embeddings = create_embeddings(all_chunks, model) + if embeddings is None: + st.error("Failed to create embeddings.") + return False + + index = build_faiss_index(embeddings) + if index is None: + st.error("Failed to build FAISS index.") + return False + + # save the index and chunks: + os.makedirs(output_dir, exist_ok=True) + faiss.write_index(index, os.path.join(output_dir, 'pdf_index.faiss')) + np.save(os.path.join(output_dir, 'pdf_chunks.npy'), all_chunks) + + # verify files were saved & reload the FAISS index: + if os.path.exists(os.path.join(output_dir, 'pdf_index.faiss')) and \ + os.path.exists(os.path.join(output_dir, 'pdf_chunks.npy')): + # Reload the FAISS index + st.session_state.nexa_model.load_faiss_index() + st.success("PDFs processed and FAISS index reloaded successfully!") + return True + else: + st.error("Error: Processed files not found after saving.") + return False + + except Exception as e: + st.error(f"Error processing PDFs: {str(e)}") + logger.error(f"Error processing PDFs: {str(e)}") + logger.error(traceback.format_exc()) + return False + +def check_faiss_index(): + if "nexa_model" not in st.session_state: + return False + return (st.session_state.nexa_model.embeddings_model is not None and + st.session_state.nexa_model.index is not None and + st.session_state.nexa_model.stored_docs is not None) + +# Streamlit app: +def main(): + st.markdown("