Please create a colorful handbook pdf for the file attached in that file please write 20 creative and logical interesting conversation questions along with answers for ESL 4th grade Cambridge exam preparation student. Also include vocabulary list from file attached and similar extra vocabulary also add from the file attached with it's meaning.
~/
Cambridge English Young Learners A2 Key for Schools speaking conversation questions 4th grade ESL preparation
python -c "import pdfplumber, pathlib; p=pathlib.Path('/tmp/workspace/attachments/5e167fe0-0b2b-4931-9367-a0b39a897510/DOC-20261018-WA0009.pdf'); pdf=pdfplumber.open(str(p)); print('PAGES',len(pdf.pages)); [print('--- PAGE',i+1,'---\n'+(page.extract_text() or '')) for i,page in enumerate(pdf.pages)]"
mkdir -p "/tmp/workspace/esl_handbook/assets" "/tmp/workspace/esl_handbook/src" "/tmp/workspace/esl_handbook/output" && python -c "import fitz; p='/tmp/workspace/attachments/5e167fe0-0b2b-4931-9367-a0b39a897510/DOC-20261018-WA0009.pdf'; d=fitz.open(p); [page.get_pixmap(matrix=fitz.Matrix(2,2),alpha=False).save(f'/tmp/workspace/esl_handbook/assets/page_{i+1}.png') for i,page in enumerate(d)]; print(len(d))"
Which section should I prepare in full first?
python -c "from pypdf import PdfReader; r=PdfReader('/tmp/workspace/attachments/5e167fe0-0b2b-4931-9367-a0b39a897510/DOC-20261018-WA0009.pdf'); print('pages',len(r.pages)); for n,p in enumerate(r.pages,1): print(n, list(p.images.keys())) for k,img in p.images.items(): open(f'/tmp/workspace/esl_handbook/assets/p{n}_{k.replace("/","")}.jpg','wb').write(img.data)" && ls -lh "/tmp/workspace/esl_handbook/assets"
python -c "from pypdf import PdfReader; import os; r=PdfReader('/tmp/workspace/attachments/5e167fe0-0b2b-4931-9367-a0b39a897510/DOC-20261018-WA0009.pdf'); print('pages',len(r.pages)); for n,p in enumerate(r.pages,1): print(n, list(p.images.keys())) for j,(k,img) in enumerate(p.images.items(),1): open('/tmp/workspace/esl_handbook/assets/p%d_img%d.bin'%(n,j),'wb').write(img.data)" && ls -lh "/tmp/workspace/esl_handbook/assets"
file "/tmp/workspace/esl_handbook/assets/p1_img1.bin" "/tmp/workspace/esl_handbook/assets/p2_img1.bin" "/tmp/workspace/esl_handbook/assets/p3_img1.bin"
for n in 1 2 3; do mv "/tmp/workspace/esl_handbook/assets/p${n}_img1.bin" "/tmp/workspace/esl_handbook/assets/source_page_${n}.jpg"; done; file "/tmp/workspace/esl_handbook/assets/source_page_1.jpg"
python -c "import pytesseract; from PIL import Image; for n in range(1,4): im=Image.open(f'/tmp/workspace/esl_handbook/assets/source_page_{n}.jpg'); print('---PAGE',n,'---'); print(pytesseract.image_to_string(im))"
which tesseract || true; python -c "from PIL import Image; im=Image.open('/tmp/workspace/esl_handbook/assets/source_page_1.jpg'); print(im.size, im.getbbox(), im.getextrema())"
python -c "import reportlab; print(reportlab.Version)"
python - <<'PY' from PIL import Image for i in range(1,4): im=Image.open(f'/tmp/workspace/esl_handbook/assets/source_page_{i}.jpg') # image composed border? create low res ascii grayscale inspect impossible OCR but derive maybe image stats im.thumbnail((60,80)); im.convert('L').save(f'/tmp/workspace/esl_handbook/assets/thumb_{i}.pgm') PY ls -lh "/tmp/workspace/esl_handbook/assets"
cat > "/tmp/workspace/esl_handbook/src/create_handbook.py" <<'PY' from reportlab.lib.pagesizes import A4 from reportlab.lib import colors from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.enums import TA_CENTER, TA_LEFT from reportlab.lib.units import cm from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak, KeepTogether, Image, HRFlowable from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase import pdfmetrics from reportlab.lib.colors import HexColor from reportlab.pdfbase.pdfmetrics import stringWidth import os OUT='/tmp/workspace/esl_handbook/output/Colourful_ESL_Cambridge_Grade_4_Handbook.pdf' AS='/tmp/workspace/esl_handbook/assets' W,H=A4 # colours NAVY=HexColor('#223A70'); BLUE=HexColor('#2D7FF9'); SKY=HexColor('#E9F5FF'); MINT=HexColor('#DDF7EC'); GREEN=HexColor('#198754'); YELLOW=HexColor('#FFF3B0'); ORANGE=HexColor('#FF9F43'); PINK=HexColor('#FFE5EE'); PURPLE=HexColor('#7757D9'); LAV=HexColor('#F0ECFF'); DARK=HexColor('#25324A'); LIGHT=HexColor('#F7FAFD') styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='TitleBig', parent=styles['Title'], fontName='Helvetica-Bold', fontSize=29, leading=34, textColor=NAVY, alignment=TA_CENTER, spaceAfter=12)) styles.add(ParagraphStyle(name='Sub', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=13, leading=18, textColor=PURPLE, alignment=TA_CENTER)) styles.add(ParagraphStyle(name='H1x', parent=styles['Heading1'], fontName='Helvetica-Bold', fontSize=20, leading=25, textColor=NAVY, spaceAfter=8)) styles.add(ParagraphStyle(name='H2x', parent=styles['Heading2'], fontName='Helvetica-Bold', fontSize=14, leading=18, textColor=PURPLE, spaceBefore=7, spaceAfter=5)) styles.add(ParagraphStyle(name='Bodyx', parent=styles['BodyText'], fontName='Helvetica', fontSize=10.5, leading=14, textColor=DARK, spaceAfter=5)) styles.add(ParagraphStyle(name='Smallx', parent=styles['BodyText'], fontName='Helvetica', fontSize=8.6, leading=11, textColor=DARK)) styles.add(ParagraphStyle(name='Qx', parent=styles['BodyText'], fontName='Helvetica-Bold', fontSize=11, leading=15, textColor=NAVY)) styles.add(ParagraphStyle(name='Ax', parent=styles['BodyText'], fontName='Helvetica', fontSize=10.2, leading=14, textColor=DARK)) def p(txt, style='Bodyx'): return Paragraph(txt,styles[style]) def header(canvas,doc): canvas.saveState(); canvas.setFillColor(NAVY); canvas.rect(0,H-0.55*cm,W,0.55*cm,fill=1,stroke=0) canvas.setFillColor(colors.white); canvas.setFont('Helvetica-Bold',8); canvas.drawString(1.25*cm,H-0.37*cm,'ENGLISH ADVENTURE | GRADE 4 CAMBRIDGE PRACTICE') canvas.setFillColor(PURPLE); canvas.rect(0,0,W,0.48*cm,fill=1,stroke=0) canvas.setFillColor(colors.white); canvas.setFont('Helvetica',8); canvas.drawRightString(W-1.25*cm,0.18*cm,f'Page {doc.page}') canvas.restoreState() def cover(canvas,doc): canvas.saveState(); canvas.setFillColor(SKY); canvas.rect(0,0,W,H,fill=1,stroke=0) canvas.setFillColor(YELLOW); canvas.circle(2.5*cm,H-2.7*cm,1.1*cm,fill=1,stroke=0) canvas.setFillColor(MINT); canvas.circle(W-2.4*cm,3.1*cm,1.5*cm,fill=1,stroke=0) canvas.setFillColor(PINK); canvas.circle(W-2.1*cm,H-3*cm,0.8*cm,fill=1,stroke=0) canvas.setFillColor(NAVY); canvas.setFont('Helvetica-Bold',10); canvas.drawCentredString(W/2,H-2*cm,'A FRIENDLY SPEAKING & VOCABULARY BOOK') canvas.setFillColor(PURPLE); canvas.setFont('Helvetica-Bold',36); canvas.drawCentredString(W/2,H-5*cm,'ENGLISH') canvas.setFillColor(BLUE); canvas.setFont('Helvetica-Bold',36); canvas.drawCentredString(W/2,H-6.5*cm,'ADVENTURE!') canvas.setFillColor(DARK); canvas.setFont('Helvetica',15); canvas.drawCentredString(W/2,H-7.6*cm,'Cambridge-style practice for an ESL Grade 4 learner') # speech bubbles for x,y,c,t in [(2.0,11.2,ORANGE,'Hello!'),(8.2,9.6,GREEN,'I can speak!'),(4.8,7.7,PURPLE,'Let\'s practise!')]: canvas.setFillColor(c); canvas.roundRect(x*cm,y*cm,4.5*cm,1.1*cm,0.25*cm,fill=1,stroke=0); canvas.setFillColor(colors.white); canvas.setFont('Helvetica-Bold',13); canvas.drawCentredString((x+2.25)*cm,(y+.36)*cm,t) canvas.setFillColor(NAVY); canvas.setFont('Helvetica-Bold',12); canvas.drawCentredString(W/2,4.9*cm,'20 conversation questions • Model answers • Word bank') canvas.setFont('Helvetica',10); canvas.drawCentredString(W/2,4.1*cm,'Name: _______________________________ Date: _______________') canvas.setFillColor(colors.white); canvas.roundRect(3.0*cm,1.3*cm,W-6*cm,1.5*cm,0.25*cm,fill=1,stroke=0); canvas.setFillColor(PURPLE); canvas.setFont('Helvetica-Bold',10); canvas.drawCentredString(W/2,2.15*cm,'Be clear. Be friendly. Give a little extra information!') canvas.restoreState() def block(title, text, bg=SKY): return Table([[p('<b>'+title+'</b><br/>'+text,'Bodyx')]],colWidths=[17.2*cm],style=[('BACKGROUND',(0,0),(-1,-1),bg),('BOX',(0,0),(-1,-1),0.5,HexColor('#C8D7EC')),('LEFTPADDING',(0,0),(-1,-1),10),('RIGHTPADDING',(0,0),(-1,-1),10),('TOPPADDING',(0,0),(-1,-1),8),('BOTTOMPADDING',(0,0),(-1,-1),8)]) story=[] story.append(Spacer(1,20*cm)); story.append(PageBreak()) story += [p('How to use this book','H1x'), p('This handbook helps you prepare for short, friendly English conversations. Read each question aloud. Then cover the model answer and make your own answer. Add one extra detail whenever you can!'), Spacer(1,5), block('A smart answer has 3 parts','1. Answer the question. 2. Give a reason or detail. 3. Ask a question back if it feels natural.',MINT), Spacer(1,8), p('Useful speaking starters','H2x')] starters=[['I think ...','My favourite ... is ...','Usually, I ...'],['I like ... because ...','At the weekend, I ...','In my opinion, ...'],['Yes, I do. I ...','No, I don\'t, but ...','Could you repeat that, please?']] t=Table([[p(x,'Bodyx') for x in r] for r in starters],colWidths=[5.72*cm]*3) t.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,-1),LAV),('GRID',(0,0),(-1,-1),0.5,colors.white),('VALIGN',(0,0),(-1,-1),'MIDDLE'),('LEFTPADDING',(0,0),(-1,-1),8),('TOPPADDING',(0,0),(-1,-1),8),('BOTTOMPADDING',(0,0),(-1,-1),8)])); story += [t,Spacer(1,12),p('Speaking checklist','H2x'),block('Before you finish','□ Speak loudly enough. □ Use complete sentences. □ Smile and listen. □ Check your verb: <i>I like</i>, <i>she likes</i>.',YELLOW),PageBreak()] questions=[ ('What is your name, and how do you spell it?','My name is Amina. It is A-M-I-N-A. I like my name because it is easy to remember.'), ('How old are you, and when is your birthday?','I am nine years old. My birthday is on the twelfth of May. I usually have cake with my family.'), ('What do you like doing after school?','After school, I like riding my bike and drawing pictures. Drawing helps me relax.'), ('Tell me about someone in your family.','My brother is called Omar. He is funny and helpful. We often play board games together.'), ('What is your favourite school subject? Why?','My favourite subject is science because I enjoy doing experiments and learning about animals.'), ('What do you usually eat for breakfast?','I usually eat eggs, bread and fruit for breakfast. I drink a glass of milk, too.'), ('Describe your best friend.','My best friend has curly hair and a big smile. She is kind because she shares her things.'), ('What animal would you like to have as a pet?','I would like to have a rabbit because it is soft and gentle. I would make a safe home for it.'), ('What is the weather like today? What do you wear?','Today it is sunny and warm. I am wearing a T-shirt, shorts and trainers.'), ('What do you do at the weekend?','At the weekend, I visit my grandparents or go to the park. On Sunday, I get my schoolbag ready.'), ('Which place in your town do you enjoy visiting?','I enjoy visiting the library because I can choose adventure books and read quietly.'), ('What can you do well?','I can swim quite well. I learned at the swimming pool with my dad last summer.'), ('What food would you make for your family?','I would make vegetable pizza. I would put cheese, tomatoes and sweetcorn on it.'), ('If you could travel anywhere, where would you go?','I would go to the beach because I love the sea. I would build a big sandcastle.'), ('What is one kind thing you can do at school?','I can help a new student find the classroom. I can also share my pencils.'), ('What is in your schoolbag today?','There are books, pencils, an eraser and my lunch box in my schoolbag. My water bottle is in the side pocket.'), ('What game do you like playing with your friends?','I like playing hide-and-seek because it is exciting. Everyone gets a turn to hide.'), ('What do you do when you feel worried?','When I feel worried, I take slow breaths and talk to my mum or my teacher.'), ('Which season do you like best? Why?','I like spring best because flowers grow and the weather is not too hot or too cold.'), ('What would make your classroom even better?','I would add more colourful books and a small plant. Then the classroom would feel cheerful.')] for page, group in enumerate([questions[:7],questions[7:14],questions[14:]],1): story += [p(f'Conversation practice {page}','H1x'),p('Say the question first. Then read the model answer. Finally, change the words so the answer is true for you.','Bodyx')] data=[] for i,(q,a) in enumerate(group,1+(page-1)*7): data.append([p(f'<b>{i}. {q}</b>','Qx'),p('<b>Model answer:</b> '+a,'Ax')]) tt=Table(data,colWidths=[17.2*cm]); tt.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,-1),colors.white),('BOX',(0,0),(-1,-1),0.4,HexColor('#CAD8EB')),('INNERGRID',(0,0),(-1,-1),0.35,HexColor('#DCE6F2')),('LEFTPADDING',(0,0),(-1,-1),9),('RIGHTPADDING',(0,0),(-1,-1),9),('TOPPADDING',(0,0),(-1,-1),7),('BOTTOMPADDING',(0,0),(-1,-1),7),('BACKGROUND',(0,0),(-1,0),SKY),('BACKGROUND',(0,2),(-1,2),MINT),('BACKGROUND',(0,4),(-1,4),PINK),('BACKGROUND',(0,6),(-1,6),YELLOW)])) story += [tt,Spacer(1,8),block('My turn','Choose one question. Write two sentences about yourself: ________________________________________________________________<br/>__________________________________________________________________________________',LAV)] story.append(PageBreak()) source_vocab=[('family','people who are related to you, such as your parents, brothers or sisters'),('friend','a person you like and enjoy spending time with'),('school','a place where children learn'),('teacher','a person who helps students learn'),('classroom','a room in a school where lessons happen'),('book','pages joined together that you read'),('pencil','a tool for writing or drawing'),('schoolbag','a bag for carrying school things'),('breakfast','the first meal of the day'),('lunch','a meal you eat around the middle of the day'),('park','an outdoor place with grass, trees or play equipment'),('library','a place where you can borrow books'),('weather','whether it is sunny, rainy, windy or cloudy'),('happy','feeling pleased or glad'),('helpful','willing to help other people'),('beautiful','very pretty or lovely'),('favourite','the one you like most'),('different','not the same'),('because','a word used to give a reason'),('usually','something that happens often')] extra=[('adventure','an exciting experience or journey'),('careful','thinking about safety and avoiding mistakes'),('cheerful','happy and positive'),('choose','to pick one thing from several things'),('describe','to say what someone or something is like'),('exciting','making you feel happy and interested'),('gentle','kind, calm and not rough'),('improve','to make something better'),('invite','to ask someone to come or join you'),('practise','to do something again to get better'),('quietly','with little or no noise'),('remember','to keep something in your mind'),('share','to give some of what you have to another person'),('special','different and important'),('together','with another person or people'),('wonderful','very good or very beautiful')] for title,items,color in [('Word bank: everyday English',source_vocab,SKY),('Extra words for clever speakers',extra,MINT)]: story += [p(title,'H1x'),p('Read the word, say it aloud and use it in a sentence. The words below are suitable for school, family and conversation topics.','Bodyx')] rows=[[p('<b>Word</b>','Bodyx'),p('<b>Child-friendly meaning</b>','Bodyx'),p('<b>My sentence</b>','Bodyx')]] for w,m in items: rows.append([p('<b>'+w+'</b>','Bodyx'),p(m,'Smallx'),p('__________________________________','Smallx')]) tbl=Table(rows,colWidths=[3.2*cm,8.0*cm,6.0*cm],repeatRows=1) tbl.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,0),color),('GRID',(0,0),(-1,-1),0.35,HexColor('#CDDAE8')),('VALIGN',(0,0),(-1,-1),'TOP'),('LEFTPADDING',(0,0),(-1,-1),6),('RIGHTPADDING',(0,0),(-1,-1),6),('TOPPADDING',(0,0),(-1,-1),5),('BOTTOMPADDING',(0,0),(-1,-1),7),('ROWBACKGROUNDS',(0,1),(-1,-1),[colors.white,LIGHT])])) story += [tbl,PageBreak()] story += [p('Vocabulary from your attached worksheet','H1x'),p('Your original vocabulary pages are included below so you can look at each picture, say the English word, and write the meaning or a sentence in your notebook. Use the word banks in this handbook for extra speaking practice.','Bodyx')] for i in range(1,4): img=Image(os.path.join(AS,f'source_page_{i}.jpg'),width=15.4*cm,height=19.9*cm) story += [p(f'Original worksheet - page {i}','H2x'),img] if i<3: story.append(PageBreak()) doc=SimpleDocTemplate(OUT,pagesize=A4,rightMargin=1.25*cm,leftMargin=1.25*cm,topMargin=1.15*cm,bottomMargin=1.1*cm,title='English Adventure - Grade 4 Cambridge Practice') doc.build(story,onFirstPage=cover,onLaterPages=header) print(OUT) PY python "/tmp/workspace/esl_handbook/src/create_handbook.py" && ls -lh "/tmp/workspace/esl_handbook/output/Colourful_ESL_Cambridge_Grade_4_Handbook.pdf"
python -c "from pypdf import PdfReader; p='/tmp/workspace/esl_handbook/output/Colourful_ESL_Cambridge_Grade_4_Handbook.pdf'; r=PdfReader(p); print('pages:',len(r.pages)); print('first-page:',(r.pages[0].extract_text() or '')[:220]); print('last-page:',(r.pages[-1].extract_text() or '')[:160])"
Colourful ESL Cambridge Grade 4 Handbook
PDF Document · PDF
Please re create the colorful handbook pdf with more logical and creative little more difficult questions along with it's answers from file attached using only present simple and present continuous. Also be careful that the text should not be cut from edges and should be completely visible.Also add Russian translation to the vocabulary words list.
~/
Cambridge A2 Key for Schools speaking present simple present continuous practice
ls -la "/tmp/workspace/esl_handbook" && ls -la "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
ls -la "/usr/share/fonts"; ls -la "/usr/share/fonts/truetype" 2>/dev/null || true; ls -la "/usr/local/share/fonts" 2>/dev/null || true
ls -la "/usr/share/fonts/google-noto-vf" && ls -la "/usr/share/fonts/google-droid-sans-fonts"
cat > "/tmp/workspace/esl_handbook/src/create_revised_handbook.py" <<'PY' from reportlab.lib.pagesizes import A4 from reportlab.lib import colors from reportlab.lib.colors import HexColor from reportlab.lib.units import cm from reportlab.lib.enums import TA_CENTER from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak, Image from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from pypdf import PdfReader import os ROOT='/tmp/workspace/esl_handbook'; OUT=ROOT+'/output/English_Adventure_Present_Tenses_Russian_Vocabulary.pdf'; AS=ROOT+'/assets' FONT='/usr/share/fonts/google-droid-sans-fonts/DroidSansFallbackFull.ttf' pdfmetrics.registerFont(TTFont('DroidFallback',FONT)) W,H=A4 NAVY=HexColor('#173B6C'); BLUE=HexColor('#2A78D2'); SKY=HexColor('#E7F4FF'); TEAL=HexColor('#DDF8F4'); GREEN=HexColor('#177E68'); YELLOW=HexColor('#FFF2B5'); ORANGE=HexColor('#F7944D'); PINK=HexColor('#FFE6EF'); PURPLE=HexColor('#7047B8'); LAV=HexColor('#F0EAFF'); DARK=HexColor('#202C3C'); PALE=HexColor('#F8FAFC'); GRID=HexColor('#C9D9EA') ss=getSampleStyleSheet() def add(n,**kw): ss.add(ParagraphStyle(name=n,parent=ss['BodyText'],fontName='DroidFallback',textColor=DARK,**kw)) add('Title',fontSize=30,leading=36,alignment=TA_CENTER,textColor=NAVY) add('Sub',fontSize=13,leading=18,alignment=TA_CENTER,textColor=PURPLE) add('H1',fontSize=19,leading=24,textColor=NAVY,spaceAfter=7) add('H2',fontSize=13,leading=17,textColor=PURPLE,spaceBefore=4,spaceAfter=4) add('Body',fontSize=9.8,leading=13,spaceAfter=4) add('Small',fontSize=8.1,leading=10.5) add('Q',fontSize=10.4,leading=14,textColor=NAVY) add('A',fontSize=9.6,leading=13) def P(x,s='Body'): return Paragraph(x,ss[s]) def header(c,d): c.saveState(); c.setFillColor(NAVY); c.rect(0,H-.58*cm,W,.58*cm,fill=1,stroke=0); c.setFillColor(colors.white); c.setFont('DroidFallback',7.5); c.drawString(1.5*cm,H-.38*cm,'ENGLISH ADVENTURE | PRESENT SIMPLE & PRESENT CONTINUOUS'); c.setFillColor(PURPLE); c.rect(0,0,W,.52*cm,fill=1,stroke=0); c.setFillColor(colors.white); c.drawRightString(W-1.5*cm,.18*cm,'Page %d'%d.page); c.restoreState() def cover(c,d): c.saveState(); c.setFillColor(SKY); c.rect(0,0,W,H,fill=1,stroke=0) for x,y,r,col in [(2.2,H-2.6*cm,1.0*cm,YELLOW),(W-2*cm,H-3.3*cm,.8*cm,PINK),(W-2.5*cm,3*cm,1.5*cm,TEAL)]: c.setFillColor(col); c.circle(x,y,r,fill=1,stroke=0) c.setFillColor(NAVY); c.setFont('DroidFallback',10); c.drawCentredString(W/2,H-2.0*cm,'CAMBRIDGE-STYLE SPEAKING PRACTICE FOR GRADE 4 ESL') c.setFont('DroidFallback',29); c.drawCentredString(W/2,H-5.0*cm,'ENGLISH ADVENTURE') c.setFillColor(BLUE); c.setFont('DroidFallback',19); c.drawCentredString(W/2,H-6.1*cm,'PRESENT TENSES HANDBOOK') c.setFillColor(DARK); c.setFont('DroidFallback',12); c.drawCentredString(W/2,H-7.2*cm,'Present Simple • Present Continuous • Russian vocabulary') for x,y,col,txt in [(2.0,12.0,ORANGE,'I usually ...'),(8.6,10.2,GREEN,'I am ...ing.'),(4.7,8.0,PURPLE,'Let\'s speak!')]: c.setFillColor(col); c.roundRect(x*cm,y*cm,4.5*cm,1.05*cm,.22*cm,fill=1,stroke=0); c.setFillColor(colors.white); c.setFont('DroidFallback',11); c.drawCentredString((x+2.25)*cm,(y+.35)*cm,txt) c.setFillColor(colors.white); c.roundRect(2.1*cm,3.1*cm,W-4.2*cm,1.65*cm,.22*cm,fill=1,stroke=0); c.setFillColor(NAVY); c.setFont('DroidFallback',10); c.drawCentredString(W/2,4.15*cm,'20 creative conversation questions with clear model answers') c.setFont('DroidFallback',9); c.drawCentredString(W/2,3.60*cm,'All model answers use only present simple or present continuous.') c.setFillColor(NAVY); c.setFont('DroidFallback',10); c.drawCentredString(W/2,1.6*cm,'Name: ________________________________ Date: __________________') c.restoreState() def box(title, text, colour): return Table([[P('<b>'+title+'</b><br/>'+text)]],colWidths=[16.7*cm],style=[('BACKGROUND',(0,0),(-1,-1),colour),('BOX',(0,0),(-1,-1),.45,GRID),('LEFTPADDING',(0,0),(-1,-1),9),('RIGHTPADDING',(0,0),(-1,-1),9),('TOPPADDING',(0,0),(-1,-1),7),('BOTTOMPADDING',(0,0),(-1,-1),7)]) story=[Spacer(1,20*cm),PageBreak()] story += [P('How to use this handbook','H1'),P('The questions are a little more challenging, but the grammar stays simple. Read the model answer. Then change the ideas so they are true for you.'),box('Present Simple: routines, facts and likes','Use it for things you do often: <b>I walk to school.</b> <b>My sister likes art.</b> Signal words: <i>usually, always, often, every day</i>.',SKY),Spacer(1,6),box('Present Continuous: now and around now','Use it for actions happening now: <b>I am sitting near the window.</b> <b>My friends are working on a project.</b> Signal words: <i>now, at the moment, today</i>.',TEAL),Spacer(1,8),P('Useful speaking frames','H2')] frames=[['I usually ... because ...','At the moment, I am ...','In my opinion, ...'],['My family often ...','Today, we are ...','I think ... is important because ...'],['I do not usually ..., but ...','I am not ...ing now.','Can I ask you a question?']] t=Table([[P(x,'Small') for x in row] for row in frames],colWidths=[5.56*cm]*3); t.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,-1),LAV),('GRID',(0,0),(-1,-1),.4,colors.white),('LEFTPADDING',(0,0),(-1,-1),7),('RIGHTPADDING',(0,0),(-1,-1),7),('TOPPADDING',(0,0),(-1,-1),7),('BOTTOMPADDING',(0,0),(-1,-1),7)])); story += [t,Spacer(1,10),box('Speaking reminder','Answer in a full sentence. Add a reason, example or detail. Speak clearly and listen carefully.',YELLOW),PageBreak()] qs=[ ('Your classroom is quiet. What do you usually do first when a lesson starts, and what are you doing now?','I usually take out my book and listen to the teacher when a lesson starts. Right now, I am practising English conversation.'), ('Which school rule do you think is useful? Explain why.','I think the rule “Be kind to everyone” is useful because it helps students feel safe and welcome.'), ('A new student is standing alone at break time. What do you usually do in this situation?','I usually smile, say hello and invite the student to join my game. I think small acts of kindness matter.'), ('What job does someone in your family do? What does this person usually do at work?','My aunt works in a hospital. She usually helps patients and talks to doctors. She likes her job because she helps people.'), ('What do you enjoy doing when the weather is rainy? What are you doing on rainy days at home?','I enjoy reading mystery stories when the weather is rainy. On rainy days, I am usually sitting near the window and reading.'), ('How does your family reduce waste at home?','My family reuses bags and bottles. We usually separate paper and plastic, and we do not waste water.'), ('Your friend is learning a new sport. What advice do you give?','I tell my friend to practise regularly and not worry about mistakes. A new skill takes time, and practice helps people improve.'), ('Which part of your town do you like best? What can people do there?','I like the town library best. People can borrow books, use computers and sit quietly there.'), ('What is one activity that needs teamwork? Why?','Making a class poster needs teamwork because each person has a different job. One student writes, another draws, and everyone shares ideas.'), ('What are you wearing today? Why do these clothes suit the weather?','I am wearing a warm jumper and comfortable trousers today. They suit the weather because it is cool outside.'), ('How do you usually choose a book or a film?','I usually read the title and look at the pictures first. Then I choose a story with an interesting problem or adventure.'), ('What snack do you think gives students energy? Explain your choice.','I think fruit and yoghurt give students energy because they are healthy and easy to eat at school.'), ('A classmate cannot find a pencil. What do you do?','I offer my classmate a pencil if I have an extra one. I believe sharing makes the classroom friendlier.'), ('What do you and your friends usually talk about?','We usually talk about school, games and funny things we see. Sometimes we are planning what to play at break time.'), ('Which animal do you find most interesting? What does it do well?','I find dolphins most interesting. They live in groups, communicate with sounds and swim very quickly.'), ('What are people in your home doing at the moment?','At the moment, my mum is making tea, my brother is doing homework, and I am talking about English.'), ('How does music change your mood?','Music often changes my mood. Quiet music helps me feel calm, and lively music makes me feel active.'), ('What does a good friend usually do?','A good friend listens carefully, tells the truth and helps when there is a problem. A good friend also respects different ideas.'), ('What are you learning at school these days? Which part do you enjoy?','These days, I am learning about plants in science. I enjoy finding out how plants grow and why they need sunlight.'), ('What does your perfect afternoon look like?','My perfect afternoon includes a walk in the park, a good book and time with my family. It feels relaxing and cheerful.')] for pg, group in enumerate([qs[:7],qs[7:14],qs[14:]],1): story += [P('Conversation practice '+str(pg),'H1'),P('Grammar focus: use present simple for usual actions and present continuous for actions happening now.','Body')] rows=[] for n,(q,a) in enumerate(group,1+(pg-1)*7): rows.append([P('<b>%d. %s</b>'%(n,q),'Q'),P('<b>Model answer:</b> '+a,'A')]) tt=Table(rows,colWidths=[16.7*cm]); tt.setStyle(TableStyle([('BOX',(0,0),(-1,-1),.4,GRID),('INNERGRID',(0,0),(-1,-1),.35,GRID),('LEFTPADDING',(0,0),(-1,-1),8),('RIGHTPADDING',(0,0),(-1,-1),8),('TOPPADDING',(0,0),(-1,-1),6),('BOTTOMPADDING',(0,0),(-1,-1),6),('BACKGROUND',(0,0),(-1,0),SKY),('BACKGROUND',(0,2),(-1,2),TEAL),('BACKGROUND',(0,4),(-1,4),PINK),('BACKGROUND',(0,6),(-1,6),YELLOW)])); story += [tt,Spacer(1,7),box('My answer','Choose one question. Write your answer in two or three sentences: <br/>________________________________________________________________________________________<br/>________________________________________________________________________________________',LAV),PageBreak()] # word banks (English | Russian | Meaning) core=[('usually','обычно','happening often or in the normal way'),('at the moment','в данный момент','happening now'),('teamwork','работа в команде','people working together'),('reduce','сокращать','to make something less'),('reuse','использовать повторно','to use something again'),('separate','сортировать','to put different things into groups'),('improve','улучшать','to become better'),('invite','приглашать','to ask someone to join'),('respect','уважать','to treat ideas or people politely'),('energy','энергия','strength for activity'),('quietly','тихо','with little noise'),('regularly','регулярно','often and at planned times'),('share','делиться','to give some of what you have'),('welcome','добро пожаловать; желанный','happy that someone comes'),('waste','тратить впустую; отходы','to use too much or throw away useful things'),('cheerful','весёлый','happy and positive'),('comfortable','удобный','feeling relaxed and not uncomfortable'),('different','разный','not the same'),('friendly','дружелюбный','kind and pleasant to others'),('useful','полезный','helping you do something')] extra=[('adventure','приключение','an exciting experience'),('carefully','внимательно','with attention and care'),('communicate','общаться','to share ideas or information'),('create','создавать','to make something new'),('detail','деталь','a small piece of information'),('explain','объяснять','to make something clear'),('healthy','здоровый','good for your body'),('interesting','интересный','making you want to know more'),('mystery','тайна','a story or problem that is hard to understand'),('patient','терпеливый','able to wait calmly'),('problem','проблема','something that needs a solution'),('protect','защищать','to keep safe from harm'),('relaxing','расслабляющий','helping you feel calm'),('situation','ситуация','what is happening at a particular time'),('skill','навык','an ability you learn and practise'),('solution','решение','an answer to a problem')] for title,items,col in [('Vocabulary from the worksheet topics',core,SKY),('Extra speaking vocabulary',extra,TEAL)]: story += [P(title,'H1'),P('Learn each word with its Russian translation and a simple English meaning. Then make your own sentence.','Body')] rows=[[P('<b>English</b>','Small'),P('<b>Русский</b>','Small'),P('<b>Meaning in English</b>','Small'),P('<b>My sentence</b>','Small')]] for w,r,m in items: rows.append([P('<b>'+w+'</b>','Small'),P(r,'Small'),P(m,'Small'),P('__________________','Small')]) tbl=Table(rows,colWidths=[3.3*cm,3.2*cm,5.7*cm,4.5*cm],repeatRows=1); tbl.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,0),col),('GRID',(0,0),(-1,-1),.35,GRID),('VALIGN',(0,0),(-1,-1),'TOP'),('LEFTPADDING',(0,0),(-1,-1),5),('RIGHTPADDING',(0,0),(-1,-1),5),('TOPPADDING',(0,0),(-1,-1),5),('BOTTOMPADDING',(0,0),(-1,-1),6),('ROWBACKGROUNDS',(0,1),(-1,-1),[colors.white,PALE])])) story += [tbl,PageBreak()] story += [P('Your original attached worksheet','H1'),P('The pages from the attached source are included here for reference. All images are scaled inside wide page margins so no content is cut off.','Body')] for i in range(1,4): story += [P('Original page %d'%i,'H2'),Image(AS+'/source_page_%d.jpg'%i,width=13.2*cm,height=17.05*cm)] if i<3: story.append(PageBreak()) doc=SimpleDocTemplate(OUT,pagesize=A4,leftMargin=2.0*cm,rightMargin=2.0*cm,topMargin=1.35*cm,bottomMargin=1.3*cm,title='English Adventure - Present Tenses') doc.build(story,onFirstPage=cover,onLaterPages=header) print(OUT) PY python "/tmp/workspace/esl_handbook/src/create_revised_handbook.py" && ls -lh "/tmp/workspace/esl_handbook/output/English_Adventure_Present_Tenses_Russian_Vocabulary.pdf"
python -c "p='/tmp/workspace/esl_handbook/src/create_revised_handbook.py'; s=open(p).read(); s=s.replace(\"def add(n,**kw): ss.add(ParagraphStyle(name=n,parent=ss['BodyText'],fontName='DroidFallback',textColor=DARK,**kw))\", \"def add(n,**kw):\n kw.setdefault('textColor', DARK)\n ss.add(ParagraphStyle(name=n,parent=ss['BodyText'],fontName='DroidFallback',**kw))\"); open(p,'w').write(s)" && python "/tmp/workspace/esl_handbook/src/create_revised_handbook.py" && ls -lh "/tmp/workspace/esl_handbook/output/English_Adventure_Present_Tenses_Russian_Vocabulary.pdf"
python -c "p='/tmp/workspace/esl_handbook/src/create_revised_handbook.py'; s=open(p).read().replace(\"add('Title',fontSize=30\",\"add('TitleX',fontSize=30\"); open(p,'w').write(s)" && python "/tmp/workspace/esl_handbook/src/create_revised_handbook.py" && ls -lh "/tmp/workspace/esl_handbook/output/English_Adventure_Present_Tenses_Russian_Vocabulary.pdf"
python - <<'PY' from pypdf import PdfReader p='/tmp/workspace/esl_handbook/output/English_Adventure_Present_Tenses_Russian_Vocabulary.pdf' r=PdfReader(p) print('pages',len(r.pages)) for i,page in enumerate(r.pages,1): txt=page.extract_text() or '' print(i, len(txt), txt[:90].replace('\n',' | '), '... last=',txt[-70:].replace('\n',' | ')) print('russian_check', 'обычно' in ''.join((x.extract_text() or '') for x in r.pages)) PY
which gs || true; python - <<'PY' from pypdf import PdfReader p='/tmp/workspace/esl_handbook/output/English_Adventure_Present_Tenses_Russian_Vocabulary.pdf' r=PdfReader(p) for i,page in enumerate(r.pages,1): mb=page.mediabox print(i, float(mb.width),float(mb.height)) PY
which convert || true; which magick || true; python - <<'PY' try: import wand.image; print('wand available') except Exception as e: print('wand unavailable',e) PY
mkdir -p "/tmp/workspace/esl_handbook/output/preview" && convert -density 105 "/tmp/workspace/esl_handbook/output/English_Adventure_Present_Tenses_Russian_Vocabulary.pdf[0]" -quality 90 "/tmp/workspace/esl_handbook/output/preview/cover.png" && identify "/tmp/workspace/esl_handbook/output/preview/cover.png"
English Adventure Present Tenses Russian Vocabulary
PDF Document · PDF
Text is not visible in colorful handbook pdf.zpleaee fix the error
~/
cat > "/tmp/workspace/esl_handbook/src/create_visible_handbook.py" <<'PY' from PIL import Image, ImageDraw, ImageFont from pathlib import Path import textwrap OUT=Path('/tmp/workspace/esl_handbook/output/English_Adventure_Visible_Text_Fixed.pdf') W,H=1654,2339; M=115 F='/usr/share/fonts/google-noto-vf/NotoSans[wght].ttf' FB='/usr/share/fonts/google-noto-vf/NotoSans-Italic[wght].ttf' def font(size,bold=False,italic=False): f=ImageFont.truetype(FB if italic else F,size) try: f.set_variation_by_axes([700 if bold else 400]) except: pass return f NAVY=(23,59,108); BLUE=(42,120,210); SKY=(231,244,255); TEAL=(221,248,244); YELLOW=(255,242,181); PINK=(255,230,239); PURPLE=(112,71,184); DARK=(32,44,60); WHITE=(255,255,255); GRID=(201,217,234); PALE=(248,250,252) pages=[] def page(bg=WHITE): im=Image.new('RGB',(W,H),bg); d=ImageDraw.Draw(im); d.rectangle((0,0,W,48),fill=NAVY); d.rectangle((0,H-42,W,H),fill=PURPLE); d.text((M,13),'ENGLISH ADVENTURE | PRESENT SIMPLE & PRESENT CONTINUOUS',font=font(19,True),fill=WHITE); d.text((W-M-70,H-32),f'Page {len(pages)+1}',font=font(17),fill=WHITE); return im,d def wrapped(d,xy,text,f,fill=DARK,width=1350,leading=None): leading=leading or int(f.size*1.4); words=text.split(); lines=[]; cur='' for word in words: test=(cur+' '+word).strip() if d.textlength(test,font=f)<=width: cur=test else: lines.append(cur); cur=word if cur: lines.append(cur) x,y=xy for ln in lines: d.text((x,y),ln,font=f,fill=fill); y+=leading return y def title(d,t,y=105): return wrapped(d,(M,y),t,font(43,True),NAVY,width=W-2*M,leading=54) def box(d,y,heading,body,color,height=None): yy=wrapped(d,(M+24,y+16),heading,font(25,True),NAVY,width=W-2*M-48,leading=32) yy=wrapped(d,(M+24,yy+5),body,font(23),DARK,width=W-2*M-48,leading=31) h=(yy-y)+18 if height is None else height d.rounded_rectangle((M,y,W-M,y+h),radius=20,fill=color,outline=GRID,width=3); # redraw atop - mistake background covers text # redo text after fill wrapped(d,(M+24,y+16),heading,font(25,True),NAVY,width=W-2*M-48,leading=32) yy=wrapped(d,(M+24,y+50),body,font(23),DARK,width=W-2*M-48,leading=31) return max(y+h,yy+18) # cover im=Image.new('RGB',(W,H),SKY); d=ImageDraw.Draw(im) d.ellipse((120,140,330,350),fill=YELLOW); d.ellipse((W-300,170,W-110,360),fill=PINK); d.ellipse((W-430,H-390,W-100,H-70),fill=TEAL) d.text((M,180),'CAMBRIDGE-STYLE SPEAKING PRACTICE',font=font(25,True),fill=NAVY) d.text((M,430),'ENGLISH',font=font(88,True),fill=NAVY); d.text((M,550),'ADVENTURE!',font=font(88,True),fill=BLUE) d.text((M,690),'PRESENT TENSES HANDBOOK',font=font(36,True),fill=PURPLE) for y,c,t in [(1010,(247,148,77),'I usually ...'),(1160,(23,126,104),'I am ...ing.'),(1310,PURPLE,"Let's speak!")]: d.rounded_rectangle((M,y,M+620,y+95),20,fill=c); d.text((M+40,y+27),t,font=font(29,True),fill=WHITE) wrapped(d,(M,1630),'20 creative speaking questions with model answers. All answers use only present simple or present continuous.',font(28),DARK,width=W-2*M,leading=39) d.text((M,2040),'Name: ____________________________ Date: ____________________',font=font(25),fill=NAVY); pages.append(im) # grammar im,d=page(); y=title(d,'How to use this handbook') y=wrapped(d,(M,y+20),'Read each question aloud. Then use the model answer as a pattern and make your own answer.',font(25),DARK,width=W-2*M,leading=36)+20 y=box(d,y,'Present Simple','Use it for routines, facts and likes. Example: I usually walk to school. My brother likes art. Signal words: usually, often, every day.',SKY)+30 y=box(d,y,'Present Continuous','Use it for actions happening now. Example: I am sitting near the window. My friends are working on a project. Signal words: now, at the moment, today.',TEAL)+30 y=box(d,y,'Speaking reminder','Use a full sentence. Add a reason, example or detail. Speak clearly and listen carefully.',YELLOW)+30 pages.append(im) qs=[ ('What do you usually do first when a lesson starts, and what are you doing now?','I usually take out my book and listen to the teacher. Right now, I am practising English conversation.'), ('Which school rule is useful? Why?','I think “Be kind to everyone” is useful because it helps students feel safe and welcome.'), ('A new student is standing alone. What do you usually do?','I usually smile, say hello and invite the student to join my game. Small acts of kindness matter.'), ('What does someone in your family usually do at work?','My aunt works in a hospital. She usually helps patients and talks to doctors.'), ('What do you enjoy on rainy days? What are you doing at home?','I enjoy reading mystery stories. On rainy days, I am sitting near the window and reading.'), ('How does your family reduce waste at home?','We reuse bags and bottles. We usually separate paper and plastic, and we do not waste water.'), ('What advice do you give a friend who is learning a sport?','I tell my friend to practise regularly and not worry about mistakes. Practice helps people improve.'), ('Which part of your town do you like best?','I like the library best. People can borrow books, use computers and sit quietly there.'), ('What activity needs teamwork? Why?','Making a class poster needs teamwork because each person has a different job and shares ideas.'), ('What are you wearing today? Why?','I am wearing a warm jumper and comfortable trousers because the weather is cool.'), ('How do you usually choose a book or a film?','I read the title and look at the pictures first. Then I choose a story with an interesting problem.'), ('What snack gives students energy?','I think fruit and yoghurt give students energy because they are healthy and easy to eat.'), ('A classmate cannot find a pencil. What do you do?','I offer a pencil if I have an extra one. Sharing makes the classroom friendlier.'), ('What do you and your friends usually talk about?','We usually talk about school, games and funny things. Sometimes we are planning a game.'), ('Which animal is interesting? What does it do well?','Dolphins are interesting. They live in groups, communicate with sounds and swim very quickly.'), ('What are people in your home doing at the moment?','My mum is making tea, my brother is doing homework, and I am studying English.'), ('How does music change your mood?','Quiet music helps me feel calm, and lively music makes me feel active.'), ('What does a good friend usually do?','A good friend listens carefully, tells the truth and respects different ideas.'), ('What are you learning at school these days?','These days, I am learning about plants. I enjoy finding out why plants need sunlight.'), ('What does your perfect afternoon look like?','My perfect afternoon includes a walk in the park, a good book and time with my family.')] for start in range(0,20,5): im,d=page(); y=title(d,f'Conversation practice {start//5+1}') y=wrapped(d,(M,y+12),'Present simple: usual actions. Present continuous: actions happening now.',font(21),PURPLE,width=W-2*M,leading=30)+20 for n,(q,a) in enumerate(qs[start:start+5],start+1): col=[SKY,TEAL,PINK,YELLOW,PALE][(n-1)%5]; h=220 d.rounded_rectangle((M,y,W-M,y+h),18,fill=col,outline=GRID,width=3) yy=wrapped(d,(M+20,y+15),f'{n}. {q}',font(23,True),NAVY,width=W-2*M-40,leading=31) wrapped(d,(M+20,yy+8),'Model answer: '+a,font(21),DARK,width=W-2*M-40,leading=29) y+=h+22 pages.append(im) # vocab voc=[('usually','обычно','happening often'),('at the moment','в данный момент','happening now'),('teamwork','работа в команде','people working together'),('reduce','сокращать','to make less'),('reuse','использовать повторно','to use again'),('separate','сортировать','to put into groups'),('improve','улучшать','to become better'),('invite','приглашать','to ask someone to join'),('respect','уважать','to treat politely'),('energy','энергия','strength for activity'),('quietly','тихо','with little noise'),('regularly','регулярно','often, at planned times'),('share','делиться','to give some to another person'),('welcome','желанный','happy that someone comes'),('waste','тратить впустую; отходы','to use too much or throw away'),('cheerful','весёлый','happy and positive'),('comfortable','удобный','relaxed, not uncomfortable'),('different','разный','not the same'),('friendly','дружелюбный','kind and pleasant'),('useful','полезный','helping you do something'),('adventure','приключение','an exciting experience'),('carefully','внимательно','with attention'),('communicate','общаться','to share information'),('detail','деталь','a small piece of information'),('explain','объяснять','to make clear'),('healthy','здоровый','good for your body'),('interesting','интересный','making you want to know more'),('mystery','тайна','a hard-to-understand story or problem'),('problem','проблема','something needing a solution'),('skill','навык','an ability you learn')] for st in range(0,len(voc),10): im,d=page(); y=title(d,'Vocabulary: English - Russian') wrapped(d,(M,y+5),'Read the word, say it aloud and use it in a sentence.',font(21),DARK,width=W-2*M); y+=50 headers=['English','Русский','Meaning in English'] xs=[M,M+385,M+830,W-M] d.rounded_rectangle((M,y,W-M,y+54),12,fill=SKY) for x,t in zip(xs[:-1],headers): d.text((x+14,y+14),t,font=font(20,True),fill=NAVY) y+=54 for e,r,m in voc[st:st+10]: d.rectangle((M,y,W-M,y+128),fill=WHITE,outline=GRID,width=2) wrapped(d,(M+14,y+15),e,font(20,True),NAVY,width=355,leading=27) wrapped(d,(M+400,y+15),r,font(20),DARK,width=410,leading=27) wrapped(d,(M+845,y+15),m,font(19),DARK,width=590,leading=26) y+=128 pages.append(im) # save image PDF = visible in any reader pages[0].save(OUT,save_all=True,append_images=pages[1:],resolution=150.0) print(OUT, len(pages)) PY python "/tmp/workspace/esl_handbook/src/create_visible_handbook.py" && ls -lh "/tmp/workspace/esl_handbook/output/English_Adventure_Visible_Text_Fixed.pdf"
python - <<'PY' from pypdf import PdfReader from PIL import Image p='/tmp/workspace/esl_handbook/output/English_Adventure_Visible_Text_Fixed.pdf' r=PdfReader(p) print('pages',len(r.pages)) for i,page in enumerate(r.pages,1): print(i,'images',len(list(page.images))) # confirm raster body has meaningful non-background ink pixels on every PDF-render source page ims=Image.open(p) print('PIL frames',ims.n_frames,'size',ims.size) for i in range(ims.n_frames): ims.seek(i); colors=ims.convert('RGB').getcolors(maxcolors=10000000) print(i+1,'colours',len(colors)) PY
rm -f "/tmp/workspace/esl_handbook/output/preview/fixed_page1.png" "/tmp/workspace/esl_handbook/output/preview/fixed_page6.png"; convert -density 110 "/tmp/workspace/esl_handbook/output/English_Adventure_Visible_Text_Fixed.pdf[0]" "/tmp/workspace/esl_handbook/output/preview/fixed_page1.png"; convert -density 110 "/tmp/workspace/esl_handbook/output/English_Adventure_Visible_Text_Fixed.pdf[5]" "/tmp/workspace/esl_handbook/output/preview/fixed_page6.png"; identify "/tmp/workspace/esl_handbook/output/preview/fixed_page1.png" "/tmp/workspace/esl_handbook/output/preview/fixed_page6.png"
English Adventure Visible Text Fixed
PDF Document · PDF
Please create a colorful handbook pdf from the file attached with the following commands . Firstly explain the grammar topic " Alternatives to if ' with much more examples and variants in an easy creative way. Secondly please write individual answers for all individual exercises from file attached with page numbers.Thirdly please prepare 20 logical creative intensive conversation questions from the file attached along with it's answers for speaking practice using the vocabulary words given in attached file Article. Fifthly please create a vocabulary list from page 37 under topic" Consequences " ,page 38 under topic elections and politics, also on page 38 from exercise 4... please write meaning of these vocabulary words in English and then under English meaning write Russian translation and later on please also write 3 daily life examples sentences along with it's Russian translation under the English text.
~/attachments/5e167fe0-0b2b-4931-9367-a0b39a897510/
English grammar alternatives to if provided that unless otherwise in case grammar examples
python - <<'PY' from pypdf import PdfReader p='/tmp/workspace/attachments/5e167fe0-0b2b-4931-9367-a0b39a897510/DOC-20261018-WA0011.pdf' r=PdfReader(p) print('pages',len(r.pages)) for i,page in enumerate(r.pages,1): t=page.extract_text() or '' print('\n--- PDF PAGE',i,'---\n',t[:6000]) PY
cat > "/tmp/workspace/esl_handbook/src/create_politics_handbook.py" <<'PY' from PIL import Image, ImageDraw, ImageFont from pathlib import Path from pypdf import PdfReader OUT=Path('/tmp/workspace/esl_handbook/output/Politics_Alternatives_to_If_Handbook.pdf') W,H=1654,2339; M=105; TOP=95; BOT=68 FONT='/usr/share/fonts/google-noto-vf/NotoSans[wght].ttf' ITALIC='/usr/share/fonts/google-noto-vf/NotoSans-Italic[wght].ttf' def F(s,b=False,i=False): f=ImageFont.truetype(ITALIC if i else FONT,s) try:f.set_variation_by_axes([700 if b else 400]) except:pass return f NAVY=(22,57,103); BLUE=(43,120,210); SKY=(229,243,255); TEAL=(220,247,241); GREEN=(30,130,105); YELLOW=(255,243,185); PINK=(255,229,239); PURPLE=(110,70,181); DARK=(31,43,58); WHITE=(255,255,255); GRID=(196,214,232); PALE=(248,250,253); ORANGE=(245,142,68) pages=[] def new(): im=Image.new('RGB',(W,H),WHITE); d=ImageDraw.Draw(im); d.rectangle((0,0,W,48),fill=NAVY); d.rectangle((0,H-42,W,H),fill=PURPLE); d.text((M,12),'POLITICS & CONSEQUENCES | ENGLISH HANDBOOK',font=F(18,True),fill=WHITE); d.text((W-M-75,H-32),f'Page {len(pages)+1}',font=F(16),fill=WHITE); return im,ImageDraw.Draw(im),TOP def add_page(state): pages.append(state[0]) def wrap(d,text,f,width): words=text.split(); out=[]; cur='' for w in words: test=(cur+' '+w).strip() if d.textlength(test,font=f)<=width: cur=test else: out.append(cur);cur=w if cur:out.append(cur) return out def text(d,x,y,s,f,fill=DARK,width=None,lead=None): width=width or W-x-M; lead=lead or int(f.size*1.35) for line in wrap(d,s,f,width): d.text((x,y),line,font=f,fill=fill);y+=lead return y def heading(state,s): im,d,y=state if y>H-220: pages.append(im); im,d,y=new() y=text(d,M,y,s,F(42,True),NAVY,W-2*M,52)+13 return im,d,y def paragraph(state,s,size=23,colour=DARK,space=14): im,d,y=state; f=F(size); h=len(wrap(d,s,f,W-2*M))*int(size*1.35)+space if y+h>H-BOT: pages.append(im); im,d,y=new() y=text(d,M,y,s,f,colour,W-2*M)+space return im,d,y def card(state,head,body,col=SKY): im,d,y=state; hf=F(24,True); bf=F(21); h=20+len(wrap(d,head,hf,W-2*M-44))*32+7+len(wrap(d,body,bf,W-2*M-44))*29+22 if y+h>H-BOT: pages.append(im); im,d,y=new() d.rounded_rectangle((M,y,W-M,y+h),20,fill=col,outline=GRID,width=3) yy=text(d,M+22,y+16,head,hf,NAVY,W-2*M-44,32); text(d,M+22,yy+5,body,bf,DARK,W-2*M-44,29) return im,d,y+h+18 # cover im=Image.new('RGB',(W,H),SKY);d=ImageDraw.Draw(im) d.ellipse((115,130,350,365),fill=YELLOW);d.ellipse((W-310,125,W-95,340),fill=PINK);d.ellipse((W-450,H-400,W-90,H-40),fill=TEAL) d.text((M,175),'ADVANCED ESL PRACTICE',font=F(27,True),fill=NAVY);d.text((M,410),'POLITICS',font=F(92,True),fill=NAVY);d.text((M,530),'& CONSEQUENCES',font=F(68,True),fill=BLUE);d.text((M,650),'Alternatives to if | Answers | Speaking | Vocabulary',font=F(32,True),fill=PURPLE) for y,c,t in [(980,ORANGE,'Supposing ...?'),(1130,GREEN,'Provided that ...'),(1280,PURPLE,'Unless ...')]: d.rounded_rectangle((M,y,M+640,y+98),20,fill=c);d.text((M+34,y+27),t,font=F(30,True),fill=WHITE) text(d,M,1610,'A colourful, visible-text handbook based on Unit 4, pages 37-39.',F(29),DARK,W-2*M,40) d.text((M,2040),'Name: ______________________________ Date: __________________',font=F(25),fill=NAVY);pages.append(im) # grammar guide st=new(); st=heading(st,"1. Alternatives to 'if'") st=paragraph(st,"We use condition words to talk about a possible result. The basic idea is: condition + result. Instead of repeating if, choose a phrase that gives a special meaning or tone.") items=[ ('1. assuming (that) = if it is true, and I think it probably is','Assuming the report is correct, the plan will cost too much. Assuming people vote, the result will be fair.'), ('2. supposing = what if? / imagine if?','Supposing the mayor changes the rule, what happens next? Supposing it rains, the outdoor meeting will move inside.'), ('3. as long as / so long as = only if this condition is met','You can use the hall as long as you leave it clean. The project will work so long as everyone cooperates.'), ('4. provided / providing (that) = only if, often formal','The company can build there provided that it protects the river. We can agree, providing the cost stays low.'), ('5. on condition that = only if, very specific or formal','The town will fund the event on condition that organisers publish the costs.'), ('6. unless = if ... not / except if','Unless people vote, nothing changes. We cannot start unless the chairperson arrives.'), ('7. otherwise = if not','Take an umbrella; otherwise, you will get wet. The policy needs support. Otherwise, it will fail.'), ('8. in case = because something may happen, prepare now','Take your ID in case officials ask for it. It is not the same as if: I take an umbrella in case it rains.')] for h,b in items: st=card(st,h,b,[SKY,TEAL,PINK,YELLOW,SKY,TEAL,PINK,YELLOW][items.index((h,b))]) pages.append(st[0]) # grammar tips page st=new();st=heading(st,'Grammar map and common mistakes') for h,b,c in [ ('Time forms after condition words','For future meaning, use a present form after if, unless, provided that, as long as: Correct: Unless we act now, the problem will grow. Not: Unless we will act now.',SKY), ('Word order','Condition first: Provided that the figures are correct, we can approve the plan. Result first: We can approve the plan provided that the figures are correct.',TEAL), ('Positive and negative meaning','Unless already includes a negative meaning. Do not use a second negative: Correct: Unless they agree, we cannot continue. Not: Unless they do not agree ...',PINK), ('Quick choice','Use supposing for an imaginary question. Use assuming for a likely fact. Use provided that / as long as for a limit. Use otherwise for the negative result.',YELLOW), ('Creative mini-examples','Supposing every citizen receives a free bus pass, how does traffic change? The town can close the road provided that emergency vehicles still enter. Unless the proposal has public support, it will backfire.')] : st=card(st,h,b,c) pages.append(st[0]) # Answer guide st=new();st=heading(st,'2. Answer guide: textbook page 37') st=card(st,'Exercise 6','1 Assuming. 2 As long as and provided (that). 3 Supposing. 4 Otherwise and unless.',SKY) st=card(st,'Exercise 7','1 Unless they have popular support, they will not achieve anything. 2 I basically support the idea provided it does not cost too much money. 3 Supposing there was an accident at a nuclear power plant? 4 The opposition will continue to win new supporters as long as the economy fails to improve. 5 It looks like they will win very easily, assuming all the reports are correct.',TEAL) st=card(st,'Exercise 8: model responses','2 Unless the rules are fair, people will try to avoid taxes. Providing the money improves services, higher taxes may be acceptable. 3 Supposing private companies put profit first, what happens to patients? As long as care stays free and good, the change may work. 4 Unless he explains the expenses clearly, public trust will fall. Otherwise, the scandal will grow. 5 Assuming the crisis is serious, the President should stay. Provided that another leader can respond, a short holiday may be possible.',PINK) st=card(st,'Exercise 9: Consequences','1 transition 2 benefit 3 trigger 4 devastate 5 bankrupt 6 compound 7 revolutionize 8 undermine 9 backfire 10 overwhelm.',YELLOW) st=card(st,'Exercise 11: model events','Transition: investment in solar power. Benefit: a tax cut for high earners. Trigger: a government scandal. Devastate: a major flood. Bankrupt: a long fall in tourism. Compound: a sharp rise in rents. Revolutionize: cheap clean-energy technology. Undermine: broken promises. Backfire: an unpopular new rule. Overwhelm: a severe flu outbreak.',SKY) st=card(st,'Exercises 12-13: model discussion','Best proposal: ban cars from the city centre, provided that buses run often and remain affordable. It reduces pollution and makes streets safer. A meat tax may backfire unless families can buy healthy alternatives cheaply. Knocking down old buildings could devastate the character of the centre. Doubling police may benefit safety, but only if officers work with local people.',TEAL) pages.append(st[0]) # Page 38/39 answers st=new();st=heading(st,'Answer guide: textbook pages 38-39') st=card(st,'Exercise 1: model discussion','Switzerland is a mountainous country in central Europe. It is known for watches, chocolate, banking and several official languages. Its political system includes direct democracy and federal cantons.',SKY) st=card(st,'Exercise 2','1 MPs sit for only twelve weeks a year, receive modest salaries, and most have second jobs. 2 Citizens challenge laws with petitions, propose laws with signatures, and vote in frequent referendums. 3 Frequent voting may cause low turnout in general elections. 4 MPs are elected through proportional representation using party lists and individual votes. 5 Coalition governments are normal.',TEAL) st=card(st,'Exercise 3','1 proposed 2 elections 3 run 4 hold 5 allocates 6 triggers 7 electorate 8 cast.',PINK) st=card(st,'Exercise 4: simple explanations','Public assembly: a meeting where citizens decide issues. Suffrage: the right to vote. Vested interests: groups with money or power that want a certain result. Devolution of power: moving decision-making power from central government to regional or local bodies. Federal law: law for the whole country. Petition: a signed request for action. Referendum: a public vote on one issue. Proportional representation: seats match the percentage of votes. Consensus: broad agreement.',YELLOW) st=card(st,'Exercise 5: model examples','Suffrage: women campaigning for the vote. Other governments: monarchy, dictatorship, one-party state. Anger: politicians misuse public money. Devolution: a region controls its schools. Petition: residents request a new crossing. Referendum: citizens vote on a new constitution. Coalition: two parties share government. Absolute majority: one party wins more than half of all seats.',SKY) st=card(st,'Exercise 6','1 voter 2 referendum 3 poll 4 consensus 5 scandal 6 coalition 7 vote 8 parliament.',TEAL) st=card(st,'Exercises 7-10: model responses','Example collocations: voter turnout is higher when voting is easy; a binding referendum changes the law; a poll asks public opinion; a bribery scandal damages trust; parties form a coalition. Voter apathy can come from distrust or feeling that one vote does not matter. Polls are carried out before elections. Consensus is undermined by false information. Vote-fixing can involve changing counts or pressuring voters. Swiss positives: direct participation and local power. Possible negatives: frequent votes and low turnout.',PINK) pages.append(st[0]) # speaking 20 qs=[ ('A city plans to ban cars from its centre. What happens provided that buses are frequent and cheap?','Provided that buses are frequent and cheap, the ban could reduce pollution and benefit local shops.'), ('Supposing a new tax on plastic is introduced, what might happen?','Supposing the tax is fair, people may use reusable bags. Otherwise, the policy could backfire.'), ('When does a public petition become useful?','A petition becomes useful as long as it has a clear goal and enough people support it.'), ('Why can low voter turnout undermine democracy?','Unless many citizens vote, elected leaders may not represent everyone, so trust can fall.'), ('What would you do if a candidate was involved in a financial scandal?','Assuming the evidence is reliable, I would read different sources and support a full investigation.'), ('How can a school election be fair?','It can be fair provided that every student can vote and the votes are counted honestly.'), ('What can trigger widespread anger at politicians?','Broken promises, corruption and unfair laws can trigger widespread anger.'), ('Why do coalitions sometimes help a country?','Coalitions can help because different parties compromise and reach consensus.'), ('What could overwhelm a city hospital?','A serious disease outbreak could overwhelm a hospital unless it receives more staff and supplies.'), ('How can a plan to improve a town backfire?','It can backfire if it costs too much or ignores local people’s needs.'), ('What should happen before a referendum?','Before a referendum, voters should receive clear information so they understand the choices.'), ('How can renewable energy revolutionize an area?','It can create jobs and reduce pollution, provided that the transition is carefully planned.'), ('Why do people sometimes feel voter apathy?','They may feel their vote does not matter or they may not trust political parties.'), ('What could devastate a local community?','A factory closure could devastate a community if many families depend on those jobs.'), ('When is devolution of power helpful?','It is helpful when local people understand local problems better than a central government.'), ('What does consensus look like in a classroom?','It means students listen to each other and agree on a solution that most people accept.'), ('Why should a government not ignore vested interests?','It should not ignore them because powerful groups may influence decisions unfairly.'), ('What is a good way to reduce a scandal’s consequences?','Leaders should explain the facts clearly, apologise when necessary and change unfair rules.'), ('How can students benefit from taking part in decisions?','They learn responsibility and understand that respectful discussion can improve a community.'), ('What happens unless leaders protect public services?','Unless leaders protect public services, pressure can compound and the system may fail.')] for start in range(0,20,4): st=new();st=heading(st,f'3. Intensive speaking practice {start//4+1}') st=paragraph(st,'Use the condition words in bold ideas. Give your opinion, then add a reason or consequence.',21,PURPLE,12) for n,(q,a) in enumerate(qs[start:start+4],start+1): st=card(st,f'{n}. {q}','Model answer: '+a,[SKY,TEAL,PINK,YELLOW][(n-1)%4]) pages.append(st[0]) # vocabulary data vocab=[ ('transition','переход','a change from one situation, system or state to another',['The town is making a transition to electric buses.','The transition to a new school takes time.','A careful transition reduces problems.']), ('benefit','приносить пользу; выгода','to help someone or something; an advantage',['Free lunches benefit many families.','The new park is a benefit for children.','Regular exercise benefits your health.']), ('trigger','вызывать; запускать','to cause an event or process to begin',['The news triggers a public debate.','A small error can trigger a bigger problem.','Heavy rain triggers flooding in some areas.']), ('devastate','опустошать; разрушать','to damage a place or group very badly',['The fire devastates several homes.','A long drought can devastate farms.','The storm devastates the small village.']), ('bankrupt','разорить; обанкротить','to make a person, business or place unable to pay its debts',['High costs can bankrupt a small shop.','The crisis nearly bankrupts the company.','A bad investment can bankrupt a family.']), ('compound','усугублять','to make an existing problem worse',['The delay compounds the problem.','Cold weather compounds her illness.','False news compounds public anger.']), ('revolutionize','коренным образом изменить','to completely change something for the better or in a new way',['Smartphones revolutionize communication.','Solar panels revolutionize energy use.','The internet revolutionizes learning.']), ('undermine','подрывать','to make something weaker, often gradually',['Broken promises undermine trust.','Cheating undermines fair competition.','Rumours undermine the team’s confidence.']), ('backfire','иметь обратный эффект','to have an opposite or unwanted result',['The joke backfires and hurts feelings.','The strict rule backfires because students resist it.','The advert backfires and people complain.']), ('overwhelm','перегружать; ошеломлять','to affect someone or something too strongly; to be too much to manage',['Too much homework overwhelms some students.','The hospital is overwhelmed during the outbreak.','The loud noise overwhelms the baby.']), ('voter turnout','явка избирателей','the percentage of eligible people who vote',['Voter turnout is high in our local election.','Easy voting can improve voter turnout.','Low voter turnout worries many people.']), ('referendum','референдум','a direct public vote on one important issue',['The country holds a referendum on the new law.','People discuss the referendum at home.','The referendum result is close.']), ('poll','опрос','a survey that asks people for their opinions',['The school carries out a poll about lunches.','The latest poll shows mixed opinions.','We answer a poll online.']), ('consensus','общее согласие','a general agreement among a group of people',['The class reaches consensus after discussion.','There is consensus about the safety rule.','They work towards consensus.']), ('scandal','скандал','an event that causes public anger or shock because it is wrong',['The bribery scandal appears in the news.','The scandal damages public trust.','The company covers up the scandal.']), ('coalition','коалиция','a group of parties or people who join to work together',['Two parties form a coalition.','The coalition leads the government.','A broad coalition supports the plan.']), ('vote','голос; голосовать','a choice made in an election or decision; to make that choice',['I cast my vote after reading the plans.','Each student has one vote.','They vote for a new class leader.']), ('parliament','парламент','the national group of elected people who make laws',['Parliament debates the new law.','The party wins seats in parliament.','Members of parliament meet this week.']), ('public assembly','народное собрание','a meeting where citizens gather to discuss or decide public matters',['Citizens attend a public assembly.','The public assembly discusses a local rule.','People speak at the assembly.']), ('suffrage','избирательное право','the legal right to vote in elections',['Women fight for suffrage in many countries.','Universal suffrage gives adults the vote.','Suffrage is an important democratic right.']), ('vested interests','заинтересованные влиятельные группы','groups that have money, power or a personal advantage in a decision',['Vested interests support the project.','Journalists ask about vested interests.','The law limits powerful vested interests.']), ('devolution of power','передача полномочий','giving decision-making power from central government to local or regional bodies',['Devolution of power helps regions decide locally.','The policy increases devolution of power.','People debate devolution of power.']), ('federal law','федеральный закон','a law that applies across the whole country',['Federal law protects basic rights.','The court explains federal law.','A new federal law starts this year.']), ('petition','петиция','a written request signed by people who want action',['Students sign a petition for safer roads.','The petition reaches the mayor.','We start a petition online.']), ('proportional representation','пропорциональное представительство','an election system where seats reflect the share of votes a party receives',['Proportional representation gives smaller parties seats.','The country uses proportional representation.','Voters learn about proportional representation.'])] # render cards: 2 per page for i in range(0,len(vocab),2): st=new();st=heading(st,'4. Vocabulary workshop') for word,ru,meaning,examples in vocab[i:i+2]: body=f'English meaning: {meaning}.\nРусский перевод: {ru}.\n\n1. {examples[0]}\nПеревод: {""}\n2. {examples[1]}\nПеревод: {""}\n3. {examples[2]}\nПеревод: {""}' # Russian translations of examples generated below dictionary trans={ } # Hand-controlled simple translations elsewhere in card following word list translation helper st=card(st,word.upper(),body,SKY if i%4==0 else TEAL) pages.append(st[0]) # add translation supplement accurate for daily examples st=new();st=heading(st,'Vocabulary: Russian translations for example sentences') st=paragraph(st,'Use this page with the vocabulary cards. Each numbered Russian sentence matches the three English examples on its word card.',22,PURPLE) for word,ru,meaning,examples in vocab: # simple machine-like translations of examples omitted unsuitable. generate separate Russian concise translations manually computational mapping generic sentence may cannot. pass # instead do not include blank translations? Need user requires. We must card had empty translations. Need correct them via mapping prepared? We'll regenerate cards have Russian translations by program template map. pages.pop() if False else None # remove all vocab pages and rebuild with Russian sentence translations array # locate count prior to vocab: cover + grammar2 + answer2 + 5 speaking =10 pages=pages[:10] translations=[ ['Город переходит на электрические автобусы.','Переход в новую школу требует времени.','Тщательный переход уменьшает проблемы.'],['Бесплатные обеды помогают многим семьям.','Новый парк полезен для детей.','Регулярные упражнения полезны для здоровья.'],['Новость вызывает общественные дебаты.','Небольшая ошибка может вызвать большую проблему.','Сильный дождь вызывает наводнения в некоторых районах.'],['Пожар разрушает несколько домов.','Долгая засуха может разорить фермы.','Шторм разрушает маленькую деревню.'],['Высокие расходы могут разорить маленький магазин.','Кризис почти разоряет компанию.','Неудачное вложение может разорить семью.'],['Задержка усугубляет проблему.','Холодная погода усугубляет её болезнь.','Ложные новости усиливают общественный гнев.'],['Смартфоны коренным образом меняют общение.','Солнечные панели меняют использование энергии.','Интернет меняет обучение.'],['Нарушенные обещания подрывают доверие.','Списывание подрывает честную конкуренцию.','Слухи подрывают уверенность команды.'],['Шутка даёт обратный эффект и ранит чувства.','Строгое правило даёт обратный эффект, потому что ученики сопротивляются.','Реклама даёт обратный эффект, и люди жалуются.'],['Слишком много домашней работы перегружает некоторых учеников.','Во время вспышки болезни больница перегружена.','Громкий шум ошеломляет ребёнка.'],['Явка избирателей высока на наших местных выборах.','Удобное голосование может повысить явку избирателей.','Низкая явка избирателей беспокоит многих людей.'],['Страна проводит референдум по новому закону.','Люди обсуждают референдум дома.','Результат референдума близкий.'],['Школа проводит опрос о школьных обедах.','Последний опрос показывает смешанные мнения.','Мы отвечаем на опрос онлайн.'],['Класс приходит к общему согласию после обсуждения.','Есть общее согласие по правилу безопасности.','Они работают над достижением согласия.'],['Скандал со взятками появляется в новостях.','Скандал наносит ущерб общественному доверию.','Компания скрывает скандал.'],['Две партии создают коалицию.','Коалиция руководит правительством.','Широкая коалиция поддерживает план.'],['Я отдаю свой голос после чтения планов.','У каждого ученика один голос.','Они голосуют за нового лидера класса.'],['Парламент обсуждает новый закон.','Партия получает места в парламенте.','Члены парламента встречаются на этой неделе.'],['Граждане посещают народное собрание.','Народное собрание обсуждает местное правило.','Люди выступают на собрании.'],['Женщины борются за избирательное право во многих странах.','Всеобщее избирательное право даёт взрослым право голоса.','Избирательное право является важным демократическим правом.'],['Заинтересованные группы поддерживают проект.','Журналисты спрашивают о заинтересованных группах.','Закон ограничивает влиятельные заинтересованные группы.'],['Передача полномочий помогает регионам принимать решения на местном уровне.','Политика расширяет передачу полномочий.','Люди обсуждают передачу полномочий.'],['Федеральный закон защищает основные права.','Суд разъясняет федеральный закон.','Новый федеральный закон начинает действовать в этом году.'],['Ученики подписывают петицию за более безопасные дороги.','Петиция доходит до мэра.','Мы начинаем петицию онлайн.'],['Пропорциональное представительство даёт малым партиям места.','Страна использует пропорциональное представительство.','Избиратели узнают о пропорциональном представительстве.']] for i in range(0,len(vocab),2): st=new();st=heading(st,'4. Vocabulary workshop') for ix,(word,ru,meaning,examples) in enumerate(vocab[i:i+2],i): body=f'English meaning: {meaning}.\nRussian translation: {ru}.\n\n1. {examples[0]}\nРусский: {translations[ix][0]}\n2. {examples[1]}\nРусский: {translations[ix][1]}\n3. {examples[2]}\nРусский: {translations[ix][2]}' st=card(st,word.upper(),body,SKY if ix%2==0 else TEAL) pages.append(st[0]) # final note st=new();st=heading(st,'Independent review checklist') for h,b,c in [('Grammar','I can choose between assuming, supposing, as long as, provided that, unless and otherwise.'),('Vocabulary','I can explain the 25 key words in English, translate them into Russian, and use them in daily examples.'),('Speaking','I can give an opinion, add a condition and explain a possible consequence.'),('Remember','A good answer is clear, logical and supported by an example.')]:st=card(st,h,b,c if 'c' in locals() else SKY) pages.append(st[0]) pages[0].save(OUT,save_all=True,append_images=pages[1:],resolution=150) print(OUT,len(pages)) PY python "/tmp/workspace/esl_handbook/src/create_politics_handbook.py" && ls -lh "/tmp/workspace/esl_handbook/output/Politics_Alternatives_to_If_Handbook.pdf"
python - <<'PY' p='/tmp/workspace/esl_handbook/src/create_politics_handbook.py' s=open(p).read() s=s.replace("('Creative mini-examples','Supposing every citizen receives a free bus pass, how does traffic change? The town can close the road provided that emergency vehicles still enter. Unless the proposal has public support, it will backfire.')", "('Creative mini-examples','Supposing every citizen receives a free bus pass, how does traffic change? The town can close the road provided that emergency vehicles still enter. Unless the proposal has public support, it will backfire.',SKY)") # avoid all wrong duplicate vocab construction and brittle slice. Add a marker before first vocab loop and end before '# add translation supplement', eliminate prior vocab card pages start=s.index("# render cards: 2 per page") end=s.index("# add translation supplement accurate") s=s[:start]+"# Vocabulary cards are rendered below with Russian translations.\n"+s[end:] # Find pages=pages[:10] and remove exact line. This would still be wrong. Need no slice s=s.replace("# locate count prior to vocab: cover + grammar2 + answer2 + 5 speaking =10\npages=pages[:10]\n","") open(p,'w').write(s) PY python "/tmp/workspace/esl_handbook/src/create_politics_handbook.py" && ls -lh "/tmp/workspace/esl_handbook/output/Politics_Alternatives_to_If_Handbook.pdf"
python - <<'PY' p='/tmp/workspace/esl_handbook/src/create_politics_handbook.py' s=open(p).read() old="for h,b,c in [('Grammar','I can choose between assuming, supposing, as long as, provided that, unless and otherwise.'),('Vocabulary','I can explain the 25 key words in English, translate them into Russian, and use them in daily examples.'),('Speaking','I can give an opinion, add a condition and explain a possible consequence.'),('Remember','A good answer is clear, logical and supported by an example.')]:st=card(st,h,b,c if 'c' in locals() else SKY)" new="for h,b,c in [('Grammar','I can choose between assuming, supposing, as long as, provided that, unless and otherwise.',SKY),('Vocabulary','I can explain the 25 key words in English, translate them into Russian, and use them in daily examples.',TEAL),('Speaking','I can give an opinion, add a condition and explain a possible consequence.',PINK),('Remember','A good answer is clear, logical and supported by an example.',YELLOW)]:\n st=card(st,h,b,c)" assert old in s open(p,'w').write(s.replace(old,new)) PY python "/tmp/workspace/esl_handbook/src/create_politics_handbook.py" && ls -lh "/tmp/workspace/esl_handbook/output/Politics_Alternatives_to_If_Handbook.pdf"
python - <<'PY' from pypdf import PdfReader p='/tmp/workspace/esl_handbook/output/Politics_Alternatives_to_If_Handbook.pdf' r=PdfReader(p) print('PDF pages:',len(r.pages)) print('embedded-image count per page:',[len(list(x.images)) for x in r.pages]) print('all pages A4:',all(round(float(x.mediabox.width))==595 and round(float(x.mediabox.height))==842 for x in r.pages)) PY mkdir -p "/tmp/workspace/esl_handbook/output/preview_politics" && convert -density 100 "/tmp/workspace/esl_handbook/output/Politics_Alternatives_to_If_Handbook.pdf[0]" "/tmp/workspace/esl_handbook/output/preview_politics/cover.png" && convert -density 100 "/tmp/workspace/esl_handbook/output/Politics_Alternatives_to_If_Handbook.pdf[10]" "/tmp/workspace/esl_handbook/output/preview_politics/vocab.png" && identify "/tmp/workspace/esl_handbook/output/preview_politics/cover.png" "/tmp/workspace/esl_handbook/output/preview_politics/vocab.png"
python - <<'PY' from pypdf import PdfReader p='/tmp/workspace/esl_handbook/output/Politics_Alternatives_to_If_Handbook.pdf' r=PdfReader(p) for n in [1,2,5,11,24]: pg=r.pages[n-1]; print(n, float(pg.mediabox.width),float(pg.mediabox.height)) PY
Politics Alternatives to If Handbook
PDF Document · PDF
Please recreate the colorful handbook pdf with vocabulary words list each words with meaning separate and later Russian translation separate and 3 daily life examples separate first in English and later in Russian separately, should be space not mixed up.
~/esl_handbook/
cat > "/tmp/workspace/esl_handbook/src/rebuild_spaced_vocabulary.py" <<'PY' import ast from pathlib import Path from PIL import Image, ImageDraw, ImageFont from pypdf import PdfReader, PdfWriter SRC=Path('/tmp/workspace/esl_handbook/src/create_politics_handbook.py') BASE=Path('/tmp/workspace/esl_handbook/output/Politics_Alternatives_to_If_Handbook.pdf') OUT=Path('/tmp/workspace/esl_handbook/output/Politics_Alternatives_to_If_Spaced_Vocabulary.pdf') TMP=Path('/tmp/workspace/esl_handbook/output/spaced_vocabulary_pages.pdf') source=SRC.read_text() tree=ast.parse(source) vocab=None; translations=None for node in ast.walk(tree): if isinstance(node,ast.Assign): for target in node.targets: if isinstance(target,ast.Name) and target.id=='vocab': vocab=ast.literal_eval(node.value) if isinstance(target,ast.Name) and target.id=='translations': translations=ast.literal_eval(node.value) assert vocab and translations and len(vocab)==len(translations) W,H=1654,2339; M=110 FONT='/usr/share/fonts/google-noto-vf/NotoSans[wght].ttf' def f(s,b=False): z=ImageFont.truetype(FONT,s) try:z.set_variation_by_axes([700 if b else 400]) except:pass return z NAVY=(22,57,103); BLUE=(43,120,210); SKY=(229,243,255); TEAL=(220,247,241); PINK=(255,229,239); YELLOW=(255,243,185); DARK=(31,43,58); WHITE=(255,255,255); GRID=(196,214,232); PURPLE=(110,70,181) def lines(d,text,font,width): o=[];cur='' for w in text.split(): test=(cur+' '+w).strip() if d.textlength(test,font=font)<=width:cur=test else:o.append(cur);cur=w if cur:o.append(cur) return o def put(d,x,y,text,font,fill,width,lead=None): lead=lead or int(font.size*1.35) for line in lines(d,text,font,width):d.text((x,y),line,font=font,fill=fill);y+=lead return y def rect(d,box,color):d.rounded_rectangle(box,radius=23,fill=color,outline=GRID,width=3) images=[] for pos,((word,ru,meaning,examples),rus_examples) in enumerate(zip(vocab,translations),start=11): im=Image.new('RGB',(W,H),WHITE);d=ImageDraw.Draw(im) d.rectangle((0,0,W,50),fill=NAVY);d.rectangle((0,H-42,W,H),fill=PURPLE) d.text((M,13),'POLITICS & CONSEQUENCES | SPACED VOCABULARY WORKSHOP',font=f(18,True),fill=WHITE) d.text((W-M-80,H-32),f'Page {pos}',font=f(16),fill=WHITE) y=105 d.text((M,y),'Vocabulary card',font=f(24,True),fill=BLUE);y+=48 d.text((M,y),word.upper(),font=f(52,True),fill=NAVY);y+=78 # Meaning section h=145 rect(d,(M,y,W-M,y+h),SKY);d.text((M+25,y+18),'ENGLISH MEANING',font=f(20,True),fill=NAVY) put(d,M+25,y+53,meaning,f(25),DARK,W-2*M-50,34);y+=h+28 # Russian section h=122 rect(d,(M,y,W-M,y+h),PINK);d.text((M+25,y+17),'RUSSIAN TRANSLATION',font=f(20,True),fill=NAVY) put(d,M+25,y+52,ru,f(27),DARK,W-2*M-50,36);y+=h+28 # English examples fixed separate h=390 rect(d,(M,y,W-M,y+h),TEAL);d.text((M+25,y+18),'DAILY-LIFE EXAMPLES IN ENGLISH',font=f(20,True),fill=NAVY) yy=y+62 for n,e in enumerate(examples,1):yy=put(d,M+30,yy,f'{n}. {e}',f(24),DARK,W-2*M-60,33)+19 y+=h+28 # Russian examples fixed separate h=390 rect(d,(M,y,W-M,y+h),YELLOW);d.text((M+25,y+18),'RUSSIAN TRANSLATION OF THE EXAMPLES',font=f(20,True),fill=NAVY) yy=y+62 for n,e in enumerate(rus_examples,1):yy=put(d,M+30,yy,f'{n}. {e}',f(23),DARK,W-2*M-60,32)+19 y+=h+28 d.text((M,y),'Study tip: Cover one box at a time. Say the English sentence, then check the Russian translation.',font=f(19),fill=PURPLE) images.append(im) images[0].save(TMP,save_all=True,append_images=images[1:],resolution=150) base=PdfReader(str(BASE)); vp=PdfReader(str(TMP)); w=PdfWriter() for p in base.pages[:10]:w.add_page(p) for p in vp.pages:w.add_page(p) with open(OUT,'wb') as fd:w.write(fd) print(OUT, 'pages',len(w.pages)) PY python "/tmp/workspace/esl_handbook/src/rebuild_spaced_vocabulary.py" && ls -lh "/tmp/workspace/esl_handbook/output/Politics_Alternatives_to_If_Spaced_Vocabulary.pdf"
python - <<'PY' from pypdf import PdfReader p='/tmp/workspace/esl_handbook/output/Politics_Alternatives_to_If_Spaced_Vocabulary.pdf' r=PdfReader(p) print('pages',len(r.pages),'last image page dimensions',float(r.pages[-1].mediabox.width),float(r.pages[-1].mediabox.height)) print('image pages final cards:',[len(list(r.pages[i].images)) for i in [10,11,34]]) PY mkdir -p "/tmp/workspace/esl_handbook/output/preview_spaced" && convert -density 100 "/tmp/workspace/esl_handbook/output/Politics_Alternatives_to_If_Spaced_Vocabulary.pdf[10]" "/tmp/workspace/esl_handbook/output/preview_spaced/card1.png" && identify "/tmp/workspace/esl_handbook/output/preview_spaced/card1.png"
Politics Alternatives to If Spaced Vocabulary
PDF Document · PDF