import streamlit as st import os import requests from bs4 import BeautifulSoup from transformers import pipeline from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.chains.combine_documents import create_stuff_documents_chain from langchain_core.prompts import ChatPromptTemplate from langchain.chains import create_retrieval_chain from langchain_community.vectorstores import FAISS from dotenv import load_dotenv load_dotenv() # Ensure API token is set up for gated access HF_API_TOKEN = os.getenv("HF_API_TOKEN") if not HF_API_TOKEN: st.error("Hugging Face API token not found. Please set it in the environment variables.") # Load the Hugging Face model using pipeline with token for gated repo access pipe = pipeline( "text-generation", model="meta-llama/Llama-3.2-1B", use_auth_token=HF_API_TOKEN ) # Prompt for competitive programming questions prompt = ChatPromptTemplate.from_template(""" The user will provide a link to a competitive programming question. Your task is to read the problem from the given link and provide an optimized solution in Python. Your response should include: - The Python code solving the problem in the most optimized way. - A brief explanation of the approach used to solve the problem, including any optimizations. - Ensure that the code is correct, adheres to the constraints, and passes all edge cases mentioned in the problem description. Guidelines: - Prioritize correctness first, ensuring the solution satisfies the problem's constraints and expected input/output formats. - Optimize the code for efficiency, minimizing time and space complexity as much as possible. - If multiple approaches exist, choose the most efficient one and explain why it was chosen. - Ensure the solution works for large input sizes and extreme cases, as competitive programming problems often require optimized solutions. Problem URL: {input} """ ) # Function to scrape website content def scrape_website_content(url): try: response = requests.get(url) response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') # Extract text from paragraphs and combine paragraphs = soup.find_all('p') text_content = ' '.join([para.get_text() for para in paragraphs]) return text_content except requests.exceptions.RequestException as e: st.error(f"Error fetching website content: {e}") return None # Create vector embeddings from website content def create_vector_embedding_from_url(url): if "vectors" not in st.session_state: st.session_state.embeddings = HuggingFaceEmbeddings( model_name="all-MiniLM-L6-v2", use_auth_token=HF_API_TOKEN # Ensure gated access if needed ) # Scrape website and get the text website_content = scrape_website_content(url) if website_content: # Split the content into documents (chunks) st.session_state.text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) st.session_state.final_documents = st.session_state.text_splitter.create_documents([website_content]) # Create vector store st.session_state.vectors = FAISS.from_documents(st.session_state.final_documents, st.session_state.embeddings) else: st.error("Failed to retrieve content from the website") st.title("🌐 Competitive Programming Solver") st.write("**Get your optimized Python solution in just a few seconds!**") url_input = st.text_input("Enter a website URL containing the programming question", value="https://example.com") user_prompt = st.text_area("Enter your query from the website content", placeholder="Provide the question details...") if st.button("Website Embedding"): create_vector_embedding_from_url(url_input) st.write("Vector Database is ready") if user_prompt: # Ensure vectors are initialized before using them if "vectors" not in st.session_state: st.error("Please create vector embeddings first by clicking 'Website Embedding'.") else: document_chain = create_stuff_documents_chain(pipe, prompt) retriever = st.session_state.vectors.as_retriever() retrieval_chain = create_retrieval_chain(retriever, document_chain) response = retrieval_chain.invoke({'input': user_prompt}) if 'answer' in response: st.write("Generated Solution:") st.code(response['answer'], language='python') # Handle context safely if 'context' in response: with st.expander("Website similarity Search"): for i, doc in enumerate(response['context']): st.write(doc.page_content) st.write('------------------------') # Feedback Section feedback = st.text_input("Provide feedback on the solution (correct/incorrect):") if feedback: st.write("Thank you for your feedback!") # You can implement further handling of the feedback if required