import PyPDF2 import pandas as pd from werkzeug.utils import securefilename import json…
- User
import PyPDF2 import pandas as pd from werkzeug.utils import secure_filename import json import logging import azure.functions as func
ALLOWED_EXTENSION={'txt', 'pdf', 'csv', 'xls', 'xlsx'}
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10 MB
def allowed_file(filename): return ( '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSION )
def extract_text_from_file(file_stream, filename): try: # check file size file_stream.seek(0, 2) file_size = file_stream.tell() if file_size > MAX_FILE_SIZE: return {'error': 'File size exceeds MAX LIMIT!'} file_stream.seek(0)
extension = filename.rsplit('.', 1)[1].lower() text = '' if extension == 'txt': for chunk in iter(lambda: file_stream.read(4096), b""): text += chunk.decode('utf-8') elif extension == 'pdf': reader = PyPDF2.PdfReader(file_stream) for page in reader.pages: text += page.extract_text() elif extension in ['xls', 'xlsx']: df = pd.read_excel(file_stream) text += df.to_string() elif extension == 'csv': df = pd.read_csv(file_stream) text += df.to_string() else: raise ValueError('Unsupported file.') return {'text': text} except Exception as e: return {'error': f"Error while extracting text: {str(e)}"}def main(req: func.HttpRequest) -> func.HttpResponse: device_id = req.form.get('device_id') if not device_id: return func.HttpResponse(json.dumps({'error': 'Device ID not found'}), status_code=400, mimetype='application/json')
uploaded_file = req.files.get('file') if not uploaded_file: return func.HttpResponse(json.dumps({'error': 'File not found'}), status_code=400, mimetype="application/json") if allowed_file(uploaded_file.filename): filename = secure_filename(uploaded_file.filename) try: text = extract_text_from_file(uploaded_file.stream, filename) payload = { 'device_id': device_id, 'text': text['text'] } return func.HttpResponse(json.dumps({'text': text['text'], 'message': 'File processed successfully!'}), status_code=200, mimetype='application/json') except Exception as e: logging.error("Error while extracting text.") return func.HttpResponse(json.dumps({'error': f"Error while extracting text: {text['error']}"}), status_code=400, mimetype='application/json') else: logging.error("File type not allowed.") return func.HttpResponse(json.dumps({'error': "Unsupported file."}), status_code=400, mimetype='application/json')i need to remove non coherent text like headers, page numbers, etc and clean the data properly before I sent it to be upserted into pinecone database, how do I do that?
- Assistant
- User
also, the upsert function only needs a single line of string, i dont need any extra formatting (newlines, etc)
- Assistant
To ensure that the text being upserted into the Pinecone database is a single continuous line without newlines or excessive spacing, you can modify the
clean_textfunction to strip out all newlines and condense multiple spaces into a single space. Here's how you can do that:def clean_text(text): # Remove common header/footer patterns cleaned = re.sub(r'(?m)(^\s*Page\s*\d+\s*$)', '', text) cleaned = re.sub(r'(?m)^(.*)\n-{3,}\n', '', cleaned) # Remove underlined headings # Normalize whitespace and remove newlines cleaned = re.sub(r'\s+', ' ', cleaned).strip() return cleaned # Rest of the code remains unchangedExplanation:
- Whitespace Normalization: The
re.sub(r'\s+', ' ', cleaned)pattern replaces all sequences of whitespace (including newlines, tabs, etc.) with a single space.
- Whitespace Normalization: The
- User
how do these regex work
- Assistant
- User
are these the only extra details that need to be cleaned? aren't there any other things that need to be cleaned from documents like pdfs, xls, etc?
- Assistant
- User
can I do it better using a module like spaCy?
- Assistant