Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Enhance Talk to PDF app with improved UI and modular design #20

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .refactory.tags.cache.v3/cache.db
Binary file not shown.
Binary file added .refactory.tags.cache.v3/cache.db-shm
Binary file not shown.
Binary file added .refactory.tags.cache.v3/cache.db-wal
Binary file not shown.
144 changes: 109 additions & 35 deletions 0_🔌API_KEY.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,109 @@
import streamlit as st
from streamlit_extras.switch_page_button import switch_page
import os
import time
import tempfile
import openai
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, ServiceContext, set_global_service_context
from llama_index.llms.openai import OpenAI
from functions import sidebar_stuff1


st.set_page_config(page_title="Talk to PDF", page_icon=":robot_face:", layout="wide")
st.title("Talk to your PDF 🤖 📑️")


st.write("#### Enter your OpenAI api key below :")
api_key = st.text_input("Enter your OpenAI API key (https://platform.openai.com/account/api-keys)", type="password")
st.session_state['api_key'] = api_key

if not api_key :
st.sidebar.warning("⚠️ Please enter OpenAI API key")
else:
openai.api_key = api_key

submit = st.button("Submit",use_container_width=True)
if submit:
st.sidebar.success("✅ API key entered successfully")
time.sleep(1.5)
switch_page('upload pdf')
sidebar_stuff1()





"""
API Key Configuration Module for Talk to PDF Application

This module handles the OpenAI API key configuration and validation for the Talk to PDF application.
It provides a user interface for API key input and manages the transition to the PDF upload page.
"""

import os
import time
from typing import Optional

import openai
import streamlit as st
from streamlit_extras.switch_page_button import switch_page
from llama_index.core import (
VectorStoreIndex,
SimpleDirectoryReader,
ServiceContext,
set_global_service_context
)
from llama_index.llms.openai import OpenAI

from functions import sidebar_stuff1

# Constants
TITLE = "Talk to your PDF 🤖 📑️"
PAGE_ICON = ":robot_face:"
API_KEY_PLACEHOLDER = "Enter your OpenAI API key (https://platform.openai.com/account/api-keys)"
SUCCESS_MESSAGE = "✅ API key entered successfully"
WARNING_MESSAGE = "⚠️ Please enter OpenAI API key"
NEXT_PAGE = "upload pdf"
TRANSITION_DELAY = 1.5

def initialize_page_config() -> None:
"""Initialize Streamlit page configuration with title and layout settings."""
st.set_page_config(
page_title="Talk to PDF",
page_icon=PAGE_ICON,
layout="wide"
)
st.title(TITLE)

def validate_api_key(api_key: str) -> bool:
"""
Validate the provided OpenAI API key.

Args:
api_key (str): The API key to validate

Returns:
bool: True if the API key is valid, False otherwise
"""
if not api_key:
return False

# TODO: Add actual API key validation by making a test request to OpenAI
return True

def handle_api_key_submission() -> None:
"""Handle the API key input and submission process."""
st.write("#### Enter your OpenAI api key below :")

# API key input with password protection
api_key = st.text_input(
API_KEY_PLACEHOLDER,
type="password",
key="api_key_input"
)

# Store API key in session state
st.session_state['api_key'] = api_key

# Display warning if API key is missing
if not api_key:
st.sidebar.warning(WARNING_MESSAGE)
else:
try:
openai.api_key = api_key
except Exception as e:
st.error(f"Error setting API key: {str(e)}")
return

# Handle submit button
if st.button("Submit", use_container_width=True):
if validate_api_key(api_key):
st.sidebar.success(SUCCESS_MESSAGE)
time.sleep(TRANSITION_DELAY)
switch_page(NEXT_PAGE)
else:
st.error("Invalid API key. Please check and try again.")

def main():
"""Main function to run the API key configuration interface."""
try:
# Initialize page configuration
initialize_page_config()

# Handle API key submission
handle_api_key_submission()

# Display sidebar content
sidebar_stuff1()

except Exception as e:
st.error(f"An error occurred: {str(e)}")
# TODO: Add proper error logging

if __name__ == "__main__":
main()
126 changes: 106 additions & 20 deletions LEARN.md
Original file line number Diff line number Diff line change
@@ -1,29 +1,115 @@
# Talk to PDF 🤖 📑️

This is the README file for the "Talk to PDF" code. The code is written in Python and uses the Streamlit library to create an interactive web application. The application allows users to ask questions about the content of a PDF file using natural language and receive instant answers powered by an AI question-answering system.
[![Python 3.11](https://img.shields.io/badge/python-3.11-blue.svg)](https://www.python.org/downloads/)
[![Streamlit](https://img.shields.io/badge/Streamlit-1.38.0-FF4B4B.svg)](https://streamlit.io)
[![OpenAI](https://img.shields.io/badge/OpenAI-1.43.0-412991.svg)](https://openai.com)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Usage
An intelligent document interaction system that enables natural language conversations with PDF documents. Powered by OpenAI's language models and built with Streamlit, this application allows users to extract information and insights from PDFs through simple questions and answers.

1. **Step 1: Enter your OpenAI API key**
- Open the application and find the "Step 1: Enter your OpenAI API key" section.
- Obtain an OpenAI API key from the OpenAI platform if you don't have one.
- Enter your API key in the text input field.
- Click the "Submit" button to set the OpenAI API key.
## Features

2. **Step 2: Upload your PDF**
- In the "Step 2: Upload your PDF" section, click the "Browse Files" button.
- Select a PDF file from your device to upload.
- Wait for the PDF to finish uploading.
- 📚 Natural language interaction with PDF documents
- 🔍 Context-aware question answering
- 🚀 Real-time response streaming
- 🎯 Customizable AI model parameters
- 🔒 Secure API key management
- 📱 Responsive web interface

3. **Ask a question**
- Once the PDF is uploaded, you will see an input box labeled "Ask a question."
- Enter your question about the PDF content in the input box.
## Installation

4. **Get the answer**
- Click the "Ask" button to submit your question.
- The application will use the uploaded PDF and the question to generate a response using the AI question-answering system.
- The response will be displayed on the screen.
```bash
# Clone the repository
git clone https://github.com/yourusername/talk-to-pdf.git
cd talk-to-pdf

Feel free to reach out to the author, [@Obelisk_1531](https://twitter.com/Obelisk_1531), for any questions or feedback.
# Install dependencies
pip install -r requirements.txt
```

Enjoy interacting with your PDFs using natural language! 🚀📄
## Requirements

- Python 3.11 or higher
- OpenAI API key
- Dependencies listed in `requirements.txt`

## Usage Guide

### 1. API Key Configuration

- Launch the application
- Navigate to the API key configuration section
- Obtain an OpenAI API key from [OpenAI Platform](https://platform.openai.com/account/api-keys)
- Enter your API key in the secure input field
- Click "Submit" to save your configuration

### 2. Document Upload

- Go to the PDF upload section
- Click "Browse Files" to select your PDF
- Support for multiple PDF uploads
- Wait for document processing to complete

### 3. Interactive Chat

- Type your questions in the chat input box
- Get AI-powered responses based on document content
- Maintain context throughout the conversation
- Adjust model parameters for different response styles

### 4. Advanced Options

- Choose between different OpenAI models (GPT-3.5-Turbo or GPT-4)
- Adjust temperature settings for response creativity
- Configure chunk size for document processing
- Customize response formatting

## Configuration

The application supports various configuration options:

```python
# Model Configuration
model_name = "gpt-3.5-turbo" # or "gpt-4"
temperature = 0.5 # Range: 0.1 - 1.0
```

## Architecture

- Built on Streamlit framework
- Uses LlamaIndex for document processing
- OpenAI API integration for natural language understanding
- Vector-based document indexing for efficient retrieval
- Stream-based response generation

## Contributing

Contributions are welcome! Please feel free to submit pull requests or create issues for bugs and feature requests.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

## Support

For support and questions, please reach out to:
- Author: [Kaushal](https://twitter.com/holy_kau)
- GitHub Issues: [Project Issues](https://github.com/yourusername/talk-to-pdf/issues)

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Acknowledgments

- OpenAI for providing the language models
- Streamlit team for the excellent web framework
- LlamaIndex for document processing capabilities

---

Made with ❤️ by [Kaushal](https://twitter.com/holy_kau)

Enjoy interacting with your PDFs using natural language! 🚀📄
Loading