A Simple Python Interface to ChatGPT for a PDF Interrogator - Hufsa Haq
Introduction
The goal of my project is to leverage the power of ChatGPT, a language model developed by OpenAI, to create an interface for extracting information from PDF files. By combining the capabilities of ChatGPT with Python and the PyPDF2 library, we can build an application that enables users to ask questions and obtain answers based on the text extracted from the PDF.
Prerequisites
Before we dive into the implementation details, make sure you have the following prerequisites:
- Python installed on your machine (version 3.6 or higher)
- Flask web framework (install using
pip install flask) - PyPDF2 library (install using
pip install PyPDF2) - An OpenAI API key for accessing ChatGPT (sign up at OpenAI and retrieve your API key)
Project Structure
Go to this link to view the code at Github : https://github.com/HufsaHaq/A-Simple-Python-Interface-to-ChatGPT
To keep things organized, let's outline the structure of the project:
- app.py: This is the main Python file that contains the Flask application and handles the routing.
- templates: This folder will contain the HTML templates for our web interface.
- static: This folder will hold any static files such as CSS stylesheets.
Now that we have our project structure in place, let's proceed with the implementation.
app.py :
import PyPDF2
import openai
openai.api_key = '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'
app = Flask(__name__)
file_uploaded = False
text = ""
conversation_history = []
@app.route('/', methods=['GET', 'POST'])
def upload():
global file_uploaded
global text
if request.method == 'POST':
file = request.files['file']
if file:
# Save the uploaded file to the current directory
file.save(file.filename)
# Extract text from the PDF file
text = extract_text_from_pdf(file.filename)
file_uploaded = True
return render_template('upload.html', file_uploaded=file_uploaded, conversation=conversation_history)
def extract_text_from_pdf(filename):
with open(filename, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
text = ''
for page in pdf_reader.pages:
text += page.extract_text()
return text
@app.route('/ask', methods=['POST'])
def ask_question():
global conversation_history
if request.method == 'POST':
question = request.form['question']
# Get a response from ChatGPT
response = chat_with_gpt(text, question)
# Append the user's question and AI response to the conversation history
conversation_history.append({'user': question, 'ai': response})
return redirect(url_for('upload'))
@app.route('/back', methods=['POST'])
def go_back():
global file_uploaded
global conversation_history
file_uploaded = False
conversation_history = []
return redirect(url_for('upload'))
def chat_with_gpt(text, question):
global conversation_history
# Prepare the prompt with conversation history
prompt = ""
for item in conversation_history:
prompt += f"User: {item['user']}\nAI: {item['ai']}\n"
# Send the prompt and the user's current question to ChatGPT for a response
prompt += f"User: {question}\nAI:"
# Send the prompt to ChatGPT for a response
response = openai.Completion.create(
engine='text-davinci-003',
prompt=prompt,
max_tokens=100,
n=1,
stop=None,
temperature=0.7
)
# Extract the AI response from the API response
answer = response.choices[0].text.strip()
# Update the conversation history
conversation_history.append({'user': question, 'ai': answer})
return answer
########################################################################
if __name__ == '__main__':
app.run(debug=True)
templates/upload.html:
<!DOCTYPE html>
<html>
<head>
<title>PDF Interrogation Using CHATGPT by Hufsa Haq</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<div class="container">
<h1>PDF Interrogation Using CHATGPT by Hufsa Haq</h1>
<h1>Upload a File</h1>
</div>
{% if file_uploaded %}
<h2>File Uploaded Successfully</h2>
<div id="conversation">
{% for item in conversation %}
<p>User: {{ item['user'] }}</p>
<p>AI: {{ item['ai'] }}</p>
{% endfor %}
</div>
<form action="/ask" method="POST">
<label for="question">Question:</label>
<input type="text" name="question" id="question" required>
<br><br>
<input type="submit" value="Ask">
</form>
<form action="/back" method="POST">
<input type="hidden" name="back" value="true">
<input type="submit" value="Back">
</form>
{% else %}
<form action="/" method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<br><br>
<input type="submit" value="Upload">
</form>
{% endif %}
</body>
</html>
static/style.css:
/* Set the global font family and font size */
body {
font-family: Arial, sans-serif;
font-size: 16px;
}
/* Set the background color */
body {
background-color: #add8d9;
}
/* Style the heading */
h1 {
color: #333;
font-size: 32px;
margin-bottom: 20px;
}
/* Style the paragraph */
p {
color: #000000;
line-height: 1.5;
}
/* Style the navigation menu */
.navbar {
background-color: #333;
color: #fff;
}
.navbar a {
color: #fff;
text-decoration: none;
padding: 10px;
}
.navbar a:hover {
background-color: #666;
}
/* Style buttons */
.button {
display: inline-block;
padding: 10px 20px;
background-color: #333;
color: #fff;
text-decoration: none;
border-radius: 4px;
}
.button:hover {
background-color: #666;
}
/* Style form inputs */
.form-input {
display: block;
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
/* Style form submit button */
.form-submit {
display: inline-block;
padding: 10px 20px;
background-color: #333;
color: #fff;
text-decoration: none;
border-radius: 4px;
}
.form-submit:hover {
background-color: #666;
}
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 30vh;
text-align: center;
}
Results:
Comments
Post a Comment