|
import streamlit as st |
|
import PyPDF2 |
|
import openai |
|
import faiss |
|
import os |
|
import numpy as np |
|
from sklearn.feature_extraction.text import TfidfVectorizer |
|
from sklearn.metrics.pairwise import cosine_similarity |
|
from io import StringIO |
|
|
|
|
|
def extract_text_from_pdf(pdf_file): |
|
reader = PyPDF2.PdfReader(pdf_file) |
|
text = "" |
|
for page in reader.pages: |
|
text += page.extract_text() |
|
return text |
|
|
|
|
|
def get_embeddings(text, model="text-embedding-ada-002"): |
|
response = openai.Embedding.create(input=[text], model=model) |
|
return response['data'][0]['embedding'] |
|
|
|
|
|
def search_similar(query_embedding, index, stored_texts, top_k=3): |
|
distances, indices = index.search(np.array([query_embedding]), top_k) |
|
results = [(stored_texts[i], distances[0][idx]) for idx, i in enumerate(indices[0])] |
|
return results |
|
|
|
|
|
def generate_code_from_prompt(prompt, model="gpt-4o-mini"): |
|
response = openai.ChatCompletion.create( |
|
model=model, |
|
messages=[{"role": "user", "content": prompt}] |
|
) |
|
return response['choices'][0]['message']['content'] |
|
|
|
|
|
def save_code_to_file(code, filename="generated_code.txt"): |
|
with open(filename, "w") as f: |
|
f.write(code) |
|
|
|
|
|
def generate_summary(text): |
|
prompt = f"Summarize the following text into key points:\n\n{text}" |
|
response = openai.ChatCompletion.create( |
|
model="gpt-4o-mini", |
|
messages=[{"role": "user", "content": prompt}] |
|
) |
|
return response['choices'][0]['message']['content'] |
|
|
|
|
|
def fix_code_bugs(buggy_code, model="gpt-4o-mini"): |
|
prompt = f"The following code has bugs or issues. Please identify and fix the problems. If possible, provide explanations for the changes made.\n\nBuggy Code:\n{buggy_code}\n\nFixed Code:" |
|
response = openai.ChatCompletion.create( |
|
model=model, |
|
messages=[{"role": "user", "content": prompt}] |
|
) |
|
return response['choices'][0]['message']['content'] |
|
|
|
from PIL import Image |
|
|
|
|
|
st.set_page_config(page_title="AI Assistance", page_icon=":robot:", layout="wide") |
|
|
|
|
|
image = Image.open("14313824.png") |
|
st.image(image, width=200) |
|
|
|
|
|
st.title("AI Assistance") |
|
|
|
|
|
openai_api_key = st.text_input("Enter your OpenAI API key:", type="password") |
|
|
|
if openai_api_key: |
|
openai.api_key = openai_api_key |
|
|
|
|
|
st.sidebar.title("Select Mode") |
|
mode = st.sidebar.radio("Choose an option", ( |
|
"Course Query Assistant", |
|
"Code Generator", |
|
"AI Chatbot Tutor", |
|
"AI Study Notes & Summaries", |
|
"Code Bug Fixer" |
|
)) |
|
|
|
if mode == "Course Query Assistant": |
|
st.header("Course Query Assistant") |
|
|
|
|
|
course_query_image = Image.open("Capture.PNG") |
|
st.image(course_query_image, width=150) |
|
|
|
|
|
uploaded_files = st.file_uploader("Upload Course Materials (PDFs)", type=["pdf"], accept_multiple_files=True) |
|
|
|
if uploaded_files: |
|
st.write("Processing uploaded course materials...") |
|
|
|
|
|
course_texts = [] |
|
for uploaded_file in uploaded_files: |
|
text = extract_text_from_pdf(uploaded_file) |
|
course_texts.append(text) |
|
|
|
|
|
combined_text = " ".join(course_texts) |
|
|
|
|
|
chunks = [combined_text[i:i+1000] for i in range(0, len(combined_text), 1000)] |
|
|
|
|
|
embeddings = [get_embeddings(chunk) for chunk in chunks] |
|
|
|
|
|
embeddings_np = np.array(embeddings).astype("float32") |
|
|
|
|
|
index = faiss.IndexFlatL2(len(embeddings_np[0])) |
|
index.add(embeddings_np) |
|
|
|
st.write("Course materials have been processed and indexed.") |
|
|
|
|
|
query = st.text_input("Enter your question about the course materials:") |
|
|
|
if query: |
|
|
|
query_embedding = get_embeddings(query) |
|
|
|
|
|
results = search_similar(query_embedding, index, chunks) |
|
|
|
|
|
context = "\n".join([result[0] for result in results]) |
|
modified_prompt = f"Context: {context}\n\nQuestion: {query}\n\nProvide a detailed answer based on the context." |
|
|
|
|
|
response = openai.ChatCompletion.create( |
|
model="gpt-4o-mini", |
|
messages=[{"role": "user", "content": modified_prompt}] |
|
) |
|
|
|
|
|
response_content = response['choices'][0]['message']['content'] |
|
|
|
|
|
st.write("### Intelligent Reply:") |
|
st.write(response_content) |
|
|
|
elif mode == "Code Generator": |
|
st.header("Code Generator") |
|
|
|
|
|
codegen = Image.open("9802381.png") |
|
st.image(codegen, width=150) |
|
|
|
|
|
code_prompt = st.text_area("Describe the code you want to generate:", |
|
"e.g., Write a Python program that generates Fibonacci numbers.") |
|
|
|
if st.button("Generate Code"): |
|
if code_prompt: |
|
with st.spinner("Generating code..."): |
|
|
|
generated_code = generate_code_from_prompt(code_prompt) |
|
|
|
|
|
clean_code = "\n".join([line for line in generated_code.splitlines() if not line.strip().startswith("#")]) |
|
|
|
|
|
save_code_to_file(clean_code) |
|
|
|
|
|
st.write("### Generated Code:") |
|
st.code(clean_code, language="python") |
|
|
|
|
|
with open("generated_code.txt", "w") as f: |
|
f.write(clean_code) |
|
|
|
st.download_button( |
|
label="Download Generated Code", |
|
data=open("generated_code.txt", "rb").read(), |
|
file_name="generated_code.txt", |
|
mime="text/plain" |
|
) |
|
else: |
|
st.error("Please provide a prompt to generate the code.") |
|
|
|
elif mode == "AI Chatbot Tutor": |
|
st.header("AI Chatbot Tutor") |
|
|
|
|
|
aitut = Image.open("910372.png") |
|
st.image(aitut, width=150) |
|
|
|
|
|
chat_history = [] |
|
|
|
def chat_with_bot(query): |
|
chat_history.append({"role": "user", "content": query}) |
|
response = openai.ChatCompletion.create( |
|
model="gpt-4o-mini", |
|
messages=chat_history |
|
) |
|
chat_history.append({"role": "assistant", "content": response['choices'][0]['message']['content']}) |
|
return response['choices'][0]['message']['content'] |
|
|
|
user_query = st.text_input("Ask a question:") |
|
|
|
if user_query: |
|
with st.spinner("Getting answer..."): |
|
bot_response = chat_with_bot(user_query) |
|
st.write(f"### AI Response: {bot_response}") |
|
|
|
elif mode == "AI Study Notes & Summaries": |
|
st.header("AI Study Notes & Summaries") |
|
|
|
|
|
uploaded_files_for_summary = st.file_uploader("Upload Course Materials (PDFs) for Summarization", type=["pdf"], accept_multiple_files=True) |
|
|
|
if uploaded_files_for_summary: |
|
st.write("Generating study notes and summaries...") |
|
|
|
|
|
all_text = "" |
|
for uploaded_file in uploaded_files_for_summary: |
|
text = extract_text_from_pdf(uploaded_file) |
|
all_text += text |
|
|
|
|
|
summary = generate_summary(all_text) |
|
|
|
|
|
st.write("### AI-Generated Summary:") |
|
st.write(summary) |
|
|
|
elif mode == "Code Bug Fixer": |
|
st.header("Code Bug Fixer") |
|
|
|
|
|
aibug = Image.open("bug.png") |
|
st.image(aibug, width=150) |
|
|
|
|
|
buggy_code = st.text_area("Enter your buggy code here:") |
|
|
|
if st.button("Fix Code"): |
|
if buggy_code: |
|
with st.spinner("Fixing code..."): |
|
|
|
fixed_code = fix_code_bugs(buggy_code) |
|
|
|
|
|
st.write("### Fixed Code:") |
|
st.code(fixed_code, language="python") |
|
|
|
|
|
with open("fixed_code.txt", "w") as f: |
|
f.write(fixed_code) |
|
|
|
st.download_button( |
|
label="Download Fixed Code", |
|
data=open("fixed_code.txt", "rb").read(), |
|
file_name="fixed_code.txt", |
|
mime="text/plain" |
|
) |
|
else: |
|
st.error("Please enter some buggy code to fix.") |
|
|