Can I get the clear version for the same pdf
ls -la /tmp/workspace/attachments/9dbc69c7-2f8f-445a-934a-c879f9f9cb8c/ && python3 -c " from pypdf import PdfReader reader = PdfReader('/tmp/workspace/attachments/9dbc69c7-2f8f-445a-934a-c879f9f9cb8c/Scanned_20260724_160257.pdf') print(f'Pages: {len(reader.pages)}') for i, page in enumerate(reader.pages): text = page.extract_text() print(f'--- Page {i+1} ---') print(repr(text[:500]) if text else 'No text layer') "
python3 -c " from pypdf import PdfReader import base64, json reader = PdfReader('/tmp/workspace/attachments/9dbc69c7-2f8f-445a-934a-c879f9f9cb8c/Scanned_20260724_160257.pdf') page = reader.pages[0] print('Resources keys:', list(page.get('/Resources', {}).keys())) xobj = page.get('/Resources', {}).get('/XObject', {}) print('XObjects:', list(xobj.keys()) if xobj else 'None') # Try pdfplumber for images import pdfplumber with pdfplumber.open('/tmp/workspace/attachments/9dbc69c7-2f8f-445a-934a-c879f9f9cb8c/Scanned_20260724_160257.pdf') as pdf: p = pdf.pages[0] imgs = p.images print(f'Images found: {len(imgs)}') if imgs: print('First image keys:', list(imgs[0].keys())) "
python3 << 'EOF' import pdfplumber from PIL import Image, ImageEnhance, ImageFilter import io, os os.makedirs('/tmp/workspace/pdf-clean/', exist_ok=True) with pdfplumber.open('/tmp/workspace/attachments/9dbc69c7-2f8f-445a-934a-c879f9f9cb8c/Scanned_20260724_160257.pdf') as pdf: p = pdf.pages[0] img_data = p.images[0] stream = img_data['stream'] raw = stream.get_data() print(f'Raw bytes: {len(raw)}') print(f'Width: {img_data["width"]}, Height: {img_data["height"]}, Bits: {img_data["bits"]}, Colorspace: {img_data["colorspace"]}') # Save raw as image mode = 'RGB' if img_data['colorspace'] == '/DeviceRGB' else 'L' w, h = img_data['width'], img_data['height'] img = Image.frombytes(mode, (w, h), raw) img.save('/tmp/workspace/pdf-clean/original.png') print('Saved original.png') EOF
python3 << 'EOF' import pdfplumber from pypdf import PdfReader from PIL import Image, ImageEnhance, ImageFilter import io, os os.makedirs('/tmp/workspace/pdf-clean/', exist_ok=True) # Extract via pypdf XObject reader = PdfReader('/tmp/workspace/attachments/9dbc69c7-2f8f-445a-934a-c879f9f9cb8c/Scanned_20260724_160257.pdf') page = reader.pages[0] xobjects = page['/Resources']['/XObject'] img_obj = xobjects['/img0'] img_obj = img_obj.get_object() print('Filter:', img_obj.get('/Filter')) print('Width:', img_obj.get('/Width')) print('Height:', img_obj.get('/Height')) print('ColorSpace:', img_obj.get('/ColorSpace')) print('BitsPerComponent:', img_obj.get('/BitsPerComponent')) data = img_obj.data print(f'Data length: {len(data)}') # Try loading raw data as JPEG (DCTDecode) try: img = Image.open(io.BytesIO(data)) img.save('/tmp/workspace/pdf-clean/original.png') print(f'Saved as {img.mode} {img.size}') except Exception as e: print(f'Direct load failed: {e}') # Save raw and inspect with open('/tmp/workspace/pdf-clean/raw_data.bin', 'wb') as f: f.write(data) print('Saved raw_data.bin') EOF
python3 << 'EOF' import io, os from pypdf import PdfReader from pypdf.generic import EncodedStreamObject from PIL import Image, ImageEnhance, ImageFilter os.makedirs('/tmp/workspace/pdf-clean/', exist_ok=True) reader = PdfReader('/tmp/workspace/attachments/9dbc69c7-2f8f-445a-934a-c879f9f9cb8c/Scanned_20260724_160257.pdf') page = reader.pages[0] xobjects = page['/Resources']['/XObject'] img_obj = xobjects['/img0'].get_object() # Use get_data() for decoded or _data for raw raw = img_obj._data # raw JPEG bytes (DCTDecode = JPEG) print(f'Raw JPEG bytes: {len(raw)}') img = Image.open(io.BytesIO(raw)) print(f'Image: {img.mode} {img.size}') img.save('/tmp/workspace/pdf-clean/original.png') print('Saved original.png') # Now enhance: convert to grayscale, sharpen, increase contrast gray = img.convert('L') # Sharpen sharpened = gray.filter(ImageFilter.SHARPEN) sharpened = gray.filter(ImageFilter.UnsharpMask(radius=2, percent=200, threshold=3)) # Contrast enhancer = ImageEnhance.Contrast(sharpened) enhanced = enhancer.enhance(2.0) # Brightness bright = ImageEnhance.Brightness(enhanced).enhance(1.2) bright.save('/tmp/workspace/pdf-clean/enhanced.png') print('Saved enhanced.png') EOF
python3 -c " import base64 with open('/tmp/workspace/pdf-clean/original.png', 'rb') as f: data = f.read() b64 = base64.b64encode(data).decode() print(f'Base64 length: {len(b64)}') print(f'Data URI prefix: data:image/png;base64,{b64[:50]}...') "
python3 -c "import pytesseract; print('pytesseract available')" 2>&1; python3 -c "import easyocr; print('easyocr available')" 2>&1; which tesseract 2>&1; python3 -c "import ocrmypdf; print('ocrmypdf available')" 2>&1
# Try installing pytesseract with user flag and check if tesseract binary exists elsewhere pip install --user pytesseract 2>&1 | tail -3 find /usr -name "tesseract" 2>/dev/null | head -5 find /opt -name "tesseract" 2>/dev/null | head -5
# Start a simple HTTP server in background to serve the image, then use analyse_media python3 -m http.server 8765 --directory /tmp/workspace/pdf-clean/ & sleep 1 echo "Server started" # Test it works curl -s -o /dev/null -w "%{http_code}" http://localhost:8765/original.png
python3 << 'EOF' import io, os from pypdf import PdfReader from PIL import Image, ImageEnhance, ImageFilter from reportlab.lib.pagesizes import A4 from reportlab.pdfgen import canvas os.makedirs('/tmp/workspace/pdf-clean/', exist_ok=True) # Extract raw JPEG from PDF reader = PdfReader('/tmp/workspace/attachments/9dbc69c7-2f8f-445a-934a-c879f9f9cb8c/Scanned_20260724_160257.pdf') page = reader.pages[0] img_obj = page['/Resources']['/XObject']['/img0'].get_object() raw_jpeg = img_obj._data # raw DCT/JPEG bytes print(f'Original JPEG: {len(raw_jpeg)} bytes') # Load with PIL img = Image.open(io.BytesIO(raw_jpeg)) print(f'Image: {img.mode} {img.size}') orig_w, orig_h = img.size # ---- Enhancement pipeline ---- # 1. Convert to RGB (already is) # 2. Sharpen sharp = img.filter(ImageFilter.UnsharpMask(radius=1.5, percent=180, threshold=3)) # 3. Boost contrast contrast = ImageEnhance.Contrast(sharp).enhance(1.6) # 4. Boost sharpness sharpness = ImageEnhance.Sharpness(contrast).enhance(2.0) # 5. Slight brightness lift final = ImageEnhance.Brightness(sharpness).enhance(1.1) # Save enhanced as high-quality JPEG enhanced_path = '/tmp/workspace/pdf-clean/enhanced_img.jpg' final.save(enhanced_path, format='JPEG', quality=95, dpi=(300, 300)) print(f'Saved enhanced: {os.path.getsize(enhanced_path)} bytes') # ---- Rebuild PDF with reportlab, fitting image to A4 ---- out_pdf = '/tmp/workspace/pdf-clean/Scanned_Clean.pdf' page_w, page_h = A4 # 595 x 842 points margin = 20 # points # Calculate fit img_aspect = orig_w / orig_h avail_w = page_w - 2 * margin avail_h = page_h - 2 * margin if img_aspect > avail_w / avail_h: draw_w = avail_w draw_h = avail_w / img_aspect else: draw_h = avail_h draw_w = avail_h * img_aspect x = margin + (avail_w - draw_w) / 2 y = margin + (avail_h - draw_h) / 2 c = canvas.Canvas(out_pdf, pagesize=A4) c.drawImage(enhanced_path, x, y, width=draw_w, height=draw_h) c.save() print(f'Clean PDF saved: {out_pdf} ({os.path.getsize(out_pdf)} bytes)') EOF
Scanned Clean
PDF Document · PDF
Can I get the page in the cleaner verson of itself
python3 << 'PYEOF' import os from reportlab.lib.pagesizes import A4 from reportlab.lib import colors from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet from reportlab.lib.units import mm, cm from reportlab.platypus import ( SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, HRFlowable, KeepTogether ) from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_JUSTIFY from reportlab.platypus.flowables import HRFlowable os.makedirs('/tmp/workspace/pdf-clean/', exist_ok=True) # ─── Colour palette ─────────────────────────────────────────────── RED = colors.HexColor('#C0392B') ORANGE = colors.HexColor('#E67E22') BLUE = colors.HexColor('#1A5276') DKBLUE = colors.HexColor('#2471A3') GREEN = colors.HexColor('#1E8449') PURPLE = colors.HexColor('#7D3C98') BOX_BG = colors.HexColor('#EBF5FB') BOX_BORDER = colors.HexColor('#2471A3') LIGHT_YELLOW = colors.HexColor('#FEF9E7') DARK_GRAY = colors.HexColor('#2C3E50') MID_GRAY = colors.HexColor('#566573') # ─── Styles ─────────────────────────────────────────────────────── styles = getSampleStyleSheet() def S(name, **kw): return ParagraphStyle(name, **kw) normal = S('Normal2', fontName='Helvetica', fontSize=9, leading=13, textColor=DARK_GRAY) small = S('Small', fontName='Helvetica', fontSize=8, leading=11, textColor=DARK_GRAY) small_it = S('SmallIt', fontName='Helvetica-Oblique', fontSize=8, leading=11, textColor=MID_GRAY) topic_title = S('TopicTitle', fontName='Helvetica-Bold', fontSize=14, leading=18, textColor=PURPLE, alignment=TA_CENTER, spaceAfter=4) point_style = S('Point', fontName='Helvetica-Bold', fontSize=9.5, leading=13, textColor=DARK_GRAY, spaceBefore=2, spaceAfter=6) sec_head = S('SecHead', fontName='Helvetica-Bold', fontSize=10.5, leading=14, textColor=RED, spaceBefore=8, spaceAfter=3) sub_head = S('SubHead', fontName='Helvetica-Bold', fontSize=9, leading=12, textColor=BLUE, spaceBefore=6, spaceAfter=2) sub_head_green = S('SubHeadGreen', fontName='Helvetica-Bold', fontSize=9, leading=12, textColor=GREEN, spaceBefore=5, spaceAfter=2) sub_head_orange = S('SubHeadOrange', fontName='Helvetica-Bold', fontSize=9, leading=12, textColor=ORANGE, spaceBefore=5, spaceAfter=2) bullet1 = S('Bullet1', fontName='Helvetica', fontSize=8.5, leading=12, textColor=DARK_GRAY, leftIndent=14, bulletIndent=4, spaceBefore=1) bullet2 = S('Bullet2', fontName='Helvetica', fontSize=8, leading=11, textColor=MID_GRAY, leftIndent=26, bulletIndent=16, spaceBefore=0) comments_title = S('CommTitle', fontName='Helvetica-Bold', fontSize=9.5, leading=13, textColor=ORANGE) header_gray = S('HdrGray', fontName='Helvetica', fontSize=8, leading=10, textColor=MID_GRAY, spaceAfter=2) box_head = S('BoxHead', fontName='Helvetica-Bold', fontSize=10, leading=14, textColor=BLUE, spaceBefore=2, spaceAfter=3) box_sub = S('BoxSub', fontName='Helvetica-Bold', fontSize=8.5, leading=12, textColor=DKBLUE, spaceBefore=4, spaceAfter=1) box_bullet = S('BoxBullet', fontName='Helvetica', fontSize=8, leading=11, textColor=DARK_GRAY, leftIndent=10, bulletIndent=2) box_label = S('BoxLabel', fontName='Helvetica-Bold', fontSize=8, leading=11, textColor=DARK_GRAY) # ─── Build content ──────────────────────────────────────────────── story = [] W, H = A4 margin = 18*mm def bullet(text, style=bullet1): return Paragraph(f'<bullet>\u2022</bullet> {text}', style) def sub_bullet(text): return Paragraph(f'<bullet>\u25e6</bullet> {text}', bullet2) # ── Header strip (top section, light grey background) ───────────── header_data = [ [Paragraph('as well as completely absorbable and digestible.', header_gray)], [Paragraph( '<font color="#CC0000">वर्चयित्वा स्त्रियाः स्तन्यमाममेव हि तद्धितम् । (सु.सू. 45/62) स्त्रीक्षीरे पाकिनिषेध माह । ' 'वर्जयित्वेत्यादि ।</font>', header_gray)], [Paragraph( 'It is very clearly mentioned that, all the other types of milk that of animals <b>(अक्षीर)</b> should be taken only ' 'after boiling, but breast milk should not be boiled and is given in <b>(आमावस्था)</b> an unboiled form (Even when ' 'it is extracted).', small)], ] header_table = Table(header_data, colWidths=[W - 2*margin]) header_table.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,-1), colors.HexColor('#F2F3F4')), ('BOX', (0,0), (-1,-1), 0.5, colors.HexColor('#BFC9CA')), ('TOPPADDING', (0,0), (-1,-1), 4), ('BOTTOMPADDING', (0,0), (-1,-1), 4), ('LEFTPADDING', (0,0), (-1,-1), 6), ('RIGHTPADDING', (0,0), (-1,-1), 6), ])) story.append(header_table) story.append(Spacer(1, 4)) # Comments section story.append(Paragraph('<b>Comments</b>', comments_title)) for i, txt in enumerate([ 'Breast milk is available in a desired temperature round the clock and no need to boil.', 'Boiling destroys immunological, antimicrobial factors.', 'Boiling also destroys vitamins and micro-elements.', 'Breast milk is available in uncontaminated, safe and ready mode form.', 'Breast milk is the best milk inspite of some disadvantages.', ], 1): story.append(Paragraph(f'{i}. {txt}', small)) story.append(Spacer(1, 8)) story.append(HRFlowable(width="100%", thickness=1.5, color=colors.HexColor('#2C3E50'))) story.append(Spacer(1, 6)) # ── Topic Title ──────────────────────────────────────────────────── story.append(Paragraph('Topic 4. Stanya Vijnana (Breast Milk)', topic_title)) story.append(HRFlowable(width="100%", thickness=0.8, color=DARK_GRAY)) story.append(Spacer(1, 5)) # POINT line story.append(Paragraph( '<b>POINT:</b> Enlist Stanya Guna and Shuddha Stanya Lakshana. Enumerate properties of normal breast milk.', point_style)) story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor('#BFC9CA'))) story.append(Spacer(1, 6)) # ── Two-column layout ────────────────────────────────────────────── # Left column content def make_left_col(): c = [] c.append(Paragraph('Properties of Normal Breast Milk', sec_head)) # 1. Physical Properties c.append(Paragraph('1. Physical Properties', sub_head)) for txt in [ '<b>Appearance:</b> Bluish-white or watery, depending on stage of lactation.', '<b>Taste:</b> Slightly sweet.', '<b>Odor:</b> Mild, characteristic odor.', '<b>pH:</b> Slightly acidic (around 6.5-7.0).', '<b>Specific Gravity:</b> Approximately 1.030.', ]: c.append(bullet(txt)) # 2. Stages c.append(Paragraph('2. Stages of Breast Milk', sub_head)) c.append(bullet('<b>Colostrum</b> (first 3-5 days postpartum):')) c.append(sub_bullet('Thick, yellowish.')) c.append(sub_bullet('Rich in proteins, immunoglobulins (especially IgA), and leukocytes.')) c.append(bullet('<b>Transitional Milk</b> (days 5-14):')) c.append(sub_bullet('Mix of colostrum and mature milk.')) c.append(sub_bullet('Increasing lactose and fat content.')) c.append(bullet('<b>Mature Milk</b> (after 2 weeks):')) c.append(sub_bullet('Foremilk: Watery, low fat, quenches thirst.')) c.append(sub_bullet('Hindmilk: Creamier, high fat, provides energy.')) # 3. Nutritional Composition c.append(Paragraph('3. Nutritional Composition (per 100 mL)', sub_head_orange)) for txt in [ '<b>Calories:</b> ~65-70 kcal.', '<b>Carbohydrates:</b> ~7 g (mainly lactose).', '<b>Proteins:</b> ~1.0-1.5 g.', ]: c.append(bullet(txt)) c.append(bullet('<b>Whey:Casein</b> ratio: ~70:30 (easier to digest)')) c.append(bullet('<b>Fats:</b> ~3.5-4.5 g.')) c.append(sub_bullet('Rich in essential fatty acids (DHA, ARA).')) c.append(bullet('<b>Vitamins:</b>')) c.append(sub_bullet('Adequate in A, E, C, and some B-complex.')) c.append(sub_bullet('Low in Vitamin D and K - supplementation may be required.')) c.append(bullet('<b>Minerals:</b>')) c.append(sub_bullet('Low sodium and phosphate (suitable for infant kidneys).')) c.append(sub_bullet('Calcium:Phosphorus ratio ~2:1 (ideal for absorption).')) # 4. Immunological c.append(Paragraph('4. Immunological Properties', sub_head)) for txt in [ 'Rich in <b>secretory IgA</b>, lactoferrin, lysozyme, and oligosaccharides.', 'Contains live cells: macrophages, neutrophils, lymphocytes.', 'Provides <b>passive immunity</b> against GI and respiratory pathogens.', ]: c.append(bullet(txt)) # 5. Digestive c.append(Paragraph('5. Digestive and Protective Functions', sub_head_green)) for txt in [ 'Contains <b>digestive enzymes</b>: lipase, amylase.', 'Promotes growth of beneficial gut flora (e.g., Bifidobacteria).', 'Reduces risk of NEC, diarrhea, respiratory infections, otitis media.', ]: c.append(bullet(txt)) # 6. Hormonal c.append(Paragraph('6. Hormonal & Growth Factors', sub_head_orange)) for txt in [ 'Contains epidermal growth factor (EGF), insulin-like growth factors, and leptin.', 'Supports intestinal and systemic development.', ]: c.append(bullet(txt)) # 7. Psychological c.append(Paragraph('7. Psychological & Developmental Benefits', sub_head_green)) for txt in [ 'Facilitates mother-infant bonding.', 'Promotes neurodevelopmental outcomes.', 'Better visual and cognitive development (due to DHA).', ]: c.append(bullet(txt)) return c # Right column - blue box def make_right_col(): inner = [] # 1. Colostrum inner.append(Paragraph('1. Colostrum', box_head)) inner.append(bullet('<b>Timeframe:</b> Birth to ~2-5 days postpartum', box_bullet)) inner.append(bullet('<b>Appearance:</b> Thick, sticky, yellow or golden-colored', box_bullet)) inner.append(bullet( '<b>Volume:</b> Small (few milliliters per feeding) - perfect for the newborn\'s small stomach', box_bullet)) inner.append(Paragraph('Nutritional Highlights:', box_sub)) for t in [ 'High in protein, especially immune-protective proteins like <b>immunoglobulin A (IgA)</b>', 'Low in fat and sugar', 'Rich in vitamin A, lactoferrin, leukocytes, and growth factors', ]: inner.append(bullet(t, box_bullet)) inner.append(Paragraph('Function:', box_sub)) for t in [ 'Provides <b>passive immunity</b>', 'Helps protect against infection', 'Acts as a <b>natural laxative</b>, helping the baby pass meconium', ]: inner.append(bullet(t, box_bullet)) inner.append(Spacer(1, 6)) inner.append(HRFlowable(width="100%", thickness=0.5, color=BOX_BORDER)) inner.append(Spacer(1, 4)) # 2. Transitional inner.append(Paragraph('2. Transitional Milk', box_head)) inner.append(bullet('<b>Timeframe:</b> ~Day 5 to 2 weeks postpartum', box_bullet)) inner.append(bullet('<b>Appearance:</b> Creamier and more white/yellowish than colostrum', box_bullet)) inner.append(bullet('<b>Volume:</b> Increases significantly as milk production ramps up', box_bullet)) inner.append(Paragraph('Nutritional Changes:', box_sub)) for t in [ 'Decreasing protein, increasing <b>fat and lactose</b> content', 'Still contains immune factors but gradually reduced', ]: inner.append(bullet(t, box_bullet)) inner.append(Paragraph('Function:', box_sub)) for t in [ 'Supports rapid <b>growth and development</b>', 'Bridges the shift from colostrum to mature milk', ]: inner.append(bullet(t, box_bullet)) inner.append(Spacer(1, 6)) inner.append(HRFlowable(width="100%", thickness=0.5, color=BOX_BORDER)) inner.append(Spacer(1, 4)) # 3. Mature inner.append(Paragraph('3. Mature Milk', box_head)) inner.append(bullet('<b>Timeframe:</b> From ~2 weeks postpartum onward', box_bullet)) inner.append(bullet('<b>Appearance:</b> Thin and bluish (foremilk), creamy (hindmilk)', box_bullet)) inner.append(bullet('<b>Volume:</b> Stabilizes at around 750-1000 mL/day depending on baby\'s needs', box_bullet)) inner.append(Paragraph('Composition:', box_sub)) for t in [ '~87% water (keeps baby hydrated)', 'Rich in <b>lactose, healthy fats</b>, and essential nutrients', 'Lower in immune components compared to colostrum, but still protective', ]: inner.append(bullet(t, box_bullet)) inner.append(Paragraph('Function:', box_sub)) for t in [ 'Meets <b>all nutritional needs</b> of the infant for the first 6 months', 'Supports <b>brain development, growth</b>, and immune support', ]: inner.append(bullet(t, box_bullet)) return inner left = make_left_col() right = make_right_col() # Wrap right col in a blue-bordered box right_table = Table([[item] for item in right], colWidths=[W - 2*margin - 95*mm - 6*mm]) right_table.setStyle(TableStyle([ ('BACKGROUND', (0,0), (-1,-1), BOX_BG), ('BOX', (0,0), (-1,-1), 1.2, BOX_BORDER), ('TOPPADDING', (0,0), (-1,-1), 3), ('BOTTOMPADDING', (0,0), (-1,-1), 2), ('LEFTPADDING', (0,0), (-1,-1), 6), ('RIGHTPADDING', (0,0), (-1,-1), 4), ])) left_table = Table([[item] for item in left], colWidths=[95*mm]) left_table.setStyle(TableStyle([ ('TOPPADDING', (0,0), (-1,-1), 2), ('BOTTOMPADDING', (0,0), (-1,-1), 1), ('LEFTPADDING', (0,0), (-1,-1), 0), ('RIGHTPADDING', (0,0), (-1,-1), 4), ])) two_col = Table( [[left_table, right_table]], colWidths=[95*mm, W - 2*margin - 95*mm - 6*mm + 6*mm] ) two_col.setStyle(TableStyle([ ('VALIGN', (0,0), (-1,-1), 'TOP'), ('LEFTPADDING', (0,0), (-1,-1), 0), ('RIGHTPADDING', (0,0), (-1,-1), 0), ('TOPPADDING', (0,0), (-1,-1), 0), ('BOTTOMPADDING',(0,0), (-1,-1), 0), ])) story.append(two_col) # ─── Build PDF ──────────────────────────────────────────────────── out = '/tmp/workspace/pdf-clean/StanyaVijnana_Clean.pdf' doc = SimpleDocTemplate( out, pagesize=A4, leftMargin=margin, rightMargin=margin, topMargin=14*mm, bottomMargin=14*mm, ) doc.build(story) print(f'Done: {out} ({os.path.getsize(out):,} bytes)') PYEOF
StanyaVijnana Clean
PDF Document · PDF