Spaces:
Build error
Build error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466import streamlit as stimport osimport timeimport tempfileimport subprocessimport reimport PyPDF2import docxfrom fpdf import FPDFfrom pathlib import Pathimport threadingimport queueimport loggingfrom datetime import datetimeimport io# Set up logginglogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',handlers=[logging.FileHandler("streamlit_app.log"),logging.StreamHandler()])logger = logging.getLogger(__name__)# Set page configurationst.set_page_config(page_title="B.Tech Assignment Solution Generator",page_icon="🎓",layout="wide",initial_sidebar_state="expanded",menu_items={'About': "# B.Tech Assignment Solution Generator\nThis app processes B.Tech assignments and generates comprehensive solutions."})# Apply dark themest.markdown("""<style>.main {background-color: #0E1117;color: white;}.stButton>button {background-color: #4CAF50;color: white;border-radius: 8px;padding: 10px 24px;font-weight: bold;border: none;transition-duration: 0.4s;}.stButton>button:hover {background-color: #45a049;}.stTextInput>div>div>input {background-color: #1E2126;color: white;}.stMarkdown {color: white;}.css-1cpxqw2 {background-color: #262730;border-radius: 10px;padding: 20px;margin-bottom: 20px;}.css-1v3fvcr {background-color: #0E1117;}.css-18e3th9 {padding-top: 2rem;}.css-1kyxreq {justify-content: center;align-items: center;}.stProgress > div > div > div > div {background-color: #4CAF50;}.log-container {background-color: #1E2126;color: #B0B0B0;padding: 15px;border-radius: 8px;height: 300px;overflow-y: auto;font-family: monospace;margin-bottom: 20px;}.success-message {color: #4CAF50;font-weight: bold;}.error-message {color: #FF5252;font-weight: bold;}.info-message {color: #2196F3;}.warning-message {color: #FFC107;}.pdf-container {background-color: #262730;padding: 20px;border-radius: 10px;margin-top: 20px;}.download-button {background-color: #2196F3;color: white;padding: 10px 15px;border-radius: 5px;text-decoration: none;display: inline-block;margin-top: 10px;}</style>""", unsafe_allow_html=True)def extract_text_from_pdf(file):"""Extract text from a PDF file."""try:pdf_reader = PyPDF2.PdfReader(file)text = ""for page in pdf_reader.pages:text += page.extract_text() + "\n"return textexcept Exception as e:logger.error(f"Error extracting text from PDF: {e}")st.error(f"Error extracting text from PDF: {e}")return Nonedef extract_text_from_docx(file):"""Extract text from a DOCX file."""try:doc = docx.Document(file)text = ""for para in doc.paragraphs:text += para.text + "\n"return textexcept Exception as e:logger.error(f"Error extracting text from DOCX: {e}")st.error(f"Error extracting text from DOCX: {e}")return Nonedef create_pdf(content, filename="solution.pdf"):"""Create a PDF file from the solution content."""try:pdf = FPDF()pdf.add_page()pdf.set_auto_page_break(auto=True, margin=15)# Set font for titlepdf.set_font("Arial", "B", 16)pdf.cell(0, 10, "B.Tech Assignment Solution", ln=True, align="C")pdf.ln(5)# Set font for contentpdf.set_font("Arial", "", 12)# Process content by paragraphsparagraphs = content.split('\n')for para in paragraphs:# Check if this is a heading (simple heuristic)if para.strip() and len(para.strip()) < 100 and para.strip().isupper():pdf.set_font("Arial", "B", 14)pdf.cell(0, 10, para, ln=True)pdf.set_font("Arial", "", 12)else:# Handle regular paragraphpdf.multi_cell(0, 10, para)pdf.ln(2)# Save PDF to a bytes bufferpdf_buffer = io.BytesIO()pdf.output(pdf_buffer)pdf_buffer.seek(0)return pdf_bufferexcept Exception as e:logger.error(f"Error creating PDF: {e}")st.error(f"Error creating PDF: {e}")return Nonedef process_log_line(line):"""Process a log line to determine its type and format it for display."""line = line.strip()if not line:return None, None# Determine message typeif "ERROR" in line or "error" in line.lower():msg_type = "error"elif "WARNING" in line or "warning" in line.lower():msg_type = "warning"elif "INFO" in line or "info" in line.lower():msg_type = "info"else:msg_type = "info"# Extract the important part of the message# Remove timestamp and log level if presentmatch = re.search(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3} - \w+ - \w+ - (.*)', line)if match:message = match.group(1)else:message = linereturn msg_type, messagedef monitor_log_file(log_file, message_queue, stop_event):"""Monitor the log file for new content and put it in the queue."""try:with open(log_file, 'r') as f:# Move to the end of the filef.seek(0, 2)while not stop_event.is_set():line = f.readline()if line:msg_type, message = process_log_line(line)if msg_type and message:message_queue.put((msg_type, message))else:# No new line, wait a bittime.sleep(0.1)except Exception as e:logger.error(f"Error monitoring log file: {e}")message_queue.put(("error", f"Error monitoring log file: {e}"))def run_assignment_processor(input_file_path, message_queue):"""Run the assignment processor and capture its output."""try:# Get the directory of the current scriptscript_dir = os.path.dirname(os.path.abspath(__file__))# Construct the path to streamlit_main.pymain_script = os.path.join(script_dir, "streamlit_main.py")# Activate virtual environment if availablevenv_python = os.path.join(script_dir, "venv", "bin", "python")if os.path.exists(venv_python):python_cmd = venv_pythonelse:python_cmd = "python3"# Run the assignment processorcmd = [python_cmd, main_script, input_file_path]# Add log messagemessage_queue.put(("info", "Starting assignment processing..."))# Execute the commandprocess = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)# Capture and process outputfor line in process.stdout:msg_type, message = process_log_line(line)if msg_type and message:message_queue.put((msg_type, message))# Wait for process to completereturn_code = process.wait()if return_code != 0:# Capture error output if process failederror_output = process.stderr.read()message_queue.put(("error", f"Process failed with return code {return_code}: {error_output}"))return False# Add completion messagemessage_queue.put(("success", "COMPLETED B.TECH ASSIGNMENT SOLUTION PIPELINE"))return Trueexcept Exception as e:logger.error(f"Error running assignment processor: {e}")message_queue.put(("error", f"Error running assignment processor: {e}"))return Falsedef main():# Headerst.title("B.Tech Assignment Solution Generator")st.markdown("Upload your assignment file (PDF or DOCX) and get comprehensive solutions.")# File uploaderuploaded_file = st.file_uploader("Choose an assignment file", type=["pdf", "docx"])if uploaded_file is not None:st.success(f"File uploaded: {uploaded_file.name}")# Extract text from the uploaded fileif uploaded_file.name.endswith('.pdf'):text = extract_text_from_pdf(uploaded_file)elif uploaded_file.name.endswith('.docx'):text = extract_text_from_docx(uploaded_file)else:st.error("Unsupported file format. Please upload a PDF or DOCX file.")returnif text is None:st.error("Failed to extract text from the file.")return# Preview the extracted textwith st.expander("Preview Extracted Text", expanded=False):st.text_area("Extracted Text", text, height=200)# Process buttonif st.button("Generate Solution"):# Create a temporary file to save the extracted textwith tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as temp_file:temp_file.write(text)temp_file_path = temp_file.nametry:# Set up progress trackingprogress_bar = st.progress(0)status_text = st.empty()# Create a container for log messagesst.subheader("Processing Status")log_container = st.empty()log_messages = []# Create a queue for messagesmessage_queue = queue.Queue()# Create an event to signal thread to stopstop_event = threading.Event()# Start a thread to monitor the log filelog_file = "btech_solution_system.log"log_thread = threading.Thread(target=monitor_log_file,args=(log_file, message_queue, stop_event))log_thread.daemon = Truelog_thread.start()# Start processing in a separate threadprocessing_thread = threading.Thread(target=run_assignment_processor,args=(temp_file_path, message_queue))processing_thread.daemon = Trueprocessing_thread.start()# Update progress and display log messagesstart_time = time.time()solution_content = None# Define key stages and their progress valuesstages = {"ANALYZING QUESTIONS": 10,"RESEARCHING INFORMATION": 30,"DEVELOPING INITIAL SOLUTIONS": 50,"VERIFYING SOLUTIONS": 70,"REVISING SOLUTIONS": 85,"FORMATTING FINAL REPORT": 95,"COMPLETED": 100}current_progress = 0# Update status until processing is completewhile processing_thread.is_alive() or not message_queue.empty():# Check for new messagestry:while not message_queue.empty():msg_type, message = message_queue.get(block=False)# Update progress based on message contentfor stage, progress_value in stages.items():if stage in message:current_progress = progress_valuebreak# Format message based on typeformatted_msg = f"<div class='{msg_type}-message'>{message}</div>"log_messages.append(formatted_msg)# Keep only the last 20 messages to avoid clutteringif len(log_messages) > 20:log_messages = log_messages[-20:]# Update log displaylog_container.markdown(f"<div class='log-container'>{''.join(log_messages)}</div>",unsafe_allow_html=True)# Check if solution is readyif "COMPLETED B.TECH ASSIGNMENT SOLUTION PIPELINE" in message:# Try to read the solution filetry:solution_file = "solution.txt"if os.path.exists(solution_file):with open(solution_file, 'r') as f:solution_content = f.read()except Exception as e:logger.error(f"Error reading solution file: {e}")log_messages.append(f"<div class='error-message'>Error reading solution file: {e}</div>")except queue.Empty:pass# Update progress barprogress_bar.progress(current_progress)status_text.text(f"Processing... ({current_progress}%)")# Check if processing is completeif current_progress >= 100:break# Check timeout (30 minutes)if time.time() - start_time > 1800:status_text.error("Processing timed out after 30 minutes.")breaktime.sleep(0.5)# Stop the log monitoring threadstop_event.set()# Check if solution was foundif solution_content:# Update progress to 100%progress_bar.progress(100)status_text.success("Solution generated successfully!")# Display the solutionst.subheader("Generated Solution")st.markdown(solution_content)# Create PDFpdf_buffer = create_pdf(solution_content)if pdf_buffer:# Provide download button for PDFst.download_button(label="Download Solution as PDF",data=pdf_buffer,file_name="btech_assignment_solution.pdf",mime="application/pdf",key="solution-pdf",help="Click to download the solution as a PDF file")else:status_text.error("Failed to generate solution.")finally:# Clean up temporary fileif os.path.exists(temp_file_path):os.unlink(temp_file_path)if __name__ == "__main__":main()
app.py+466