Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files12345678940 unmodified lines5051525354555657585915 unmodified lines7576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311413 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621632 unmodified lines1661671681691701711722 unmodified lines1751761771781791801811821831841851861871881891901915 unmodified lines1971981992002012022032042052062072082092102113 unmodified lines215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256import streamlit as stimport qrcodefrom qrcode.image.styledpil import StyledPilImagefrom qrcode.image.styles.moduledrawers import RoundedModuleDrawer, CircleModuleDrawer, SquareModuleDrawerfrom qrcode.image.styles.colorfills import SolidFillColorMask, RadialGradiantColorMask, SquareGradiantColorMaskfrom PIL import Image, ImageDrawimport ioimport base6440 unmodified linesmargin: 1rem 0;box-shadow: 0 2px 4px rgba(0,0,0,0.1);}</style>""", unsafe_allow_html=True)def create_qr_code(data, fill_color, back_color, border, box_size, error_correction, style_type):"""Generate QR code with custom styling"""# Error correction levels15 unmodified linesqr.add_data(data)qr.make(fit=True)# Style configurationsif style_type == "Standard":img = qr.make_image(fill_color=fill_color, back_color=back_color)elif style_type == "Rounded":img = qr.make_image(image_factory=StyledPilImage,module_drawer=RoundedModuleDrawer(),fill_color=fill_color,back_color=back_color)elif style_type == "Circular":img = qr.make_image(image_factory=StyledPilImage,module_drawer=CircleModuleDrawer(),fill_color=fill_color,back_color=back_color)elif style_type == "Gradient":img = qr.make_image(image_factory=StyledPilImage,color_mask=RadialGradiantColorMask(),fill_color=fill_color,back_color=back_color)return imgdef get_download_link(img, filename):"""Generate download link for the QR code"""buffered = io.BytesIO()img.save(buffered, format="PNG")img_str = base64.b64encode(buffered.getvalue()).decode()href = f'<a href="data:image/png;base64,{img_str}" download="{filename}" class="download-btn">π₯ Download QR Code</a>'return href# Main headerst.markdown("""13 unmodified linescontent_type = st.selectbox("Content Type",["Text", "URL", "Email", "Phone", "SMS", "WiFi"])if content_type == "Text":qr_data = st.text_area("Enter your text:", height=100)elif content_type == "URL":qr_data = st.text_input("Enter URL:", placeholder="https://example.com")elif content_type == "Email":email = st.text_input("Email address:")subject = st.text_input("Subject (optional):")body = st.text_area("Message (optional):", height=80)qr_data = f"mailto:{email}?subject={subject}&body={body}" if email else ""elif content_type == "Phone":qr_data = st.text_input("Phone number:", placeholder="+1234567890")if qr_data:qr_data = f"tel:{qr_data}"elif content_type == "SMS":phone = st.text_input("Phone number:", placeholder="+1234567890")message = st.text_area("Message:", height=80)qr_data = f"sms:{phone}?body={message}" if phone else ""elif content_type == "WiFi":ssid = st.text_input("Network Name (SSID):")password = st.text_input("Password:", type="password")security = st.selectbox("Security Type", ["WPA", "WEP", "nopass"])hidden = st.checkbox("Hidden Network")if ssid:qr_data = f"WIFI:T:{security};S:{ssid};P:{password};H:{'true' if hidden else 'false'};;"else:qr_data = ""st.markdown('</div>', unsafe_allow_html=True)# Style Settings2 unmodified linesstyle_type = st.selectbox("QR Style",["Standard", "Rounded", "Circular", "Gradient"])col1, col2 = st.columns(2)2 unmodified lineswith col2:back_color = st.color_picker("Background Color", "#FFFFFF")st.markdown('</div>', unsafe_allow_html=True)# Advanced Settingsst.markdown('<div class="sidebar-section">', unsafe_allow_html=True)st.markdown("### βοΈ Advanced Settings")box_size = st.slider("Module Size", 1, 20, 10)border = st.slider("Border Width", 1, 10, 4)error_correction = st.selectbox("Error Correction Level",["L (~7%)", "M (~15%)", "Q (~25%)", "H (~30%)"])st.markdown('</div>', unsafe_allow_html=True)5 unmodified linesif qr_data:try:# Generate QR codeqr_img = create_qr_code(qr_data, fill_color, back_color, border,box_size, error_correction, style_type)# Display QR codest.markdown("### π± Your QR Code")st.image(qr_img, caption="Generated QR Code", use_container_width=True)# Download sectionst.markdown("""<div class="download-section">3 unmodified lines""", unsafe_allow_html=True)# Download buttonfilename = f"qrcode_{content_type.lower()}.png"st.markdown(get_download_link(qr_img, filename), unsafe_allow_html=True)except Exception as e:st.error(f"Error generating QR code: {str(e)}")else:st.info("π Please enter content in the sidebar to generate your QR code")with col2:st.markdown("### π Features")features = ["π¨ Multiple visual styles","π Custom colors","π± Various content types","βοΈ Advanced settings","π₯ Instant download","π§ Error correction levels"]for feature in features:st.markdown(f'<div class="feature-box">{feature}</div>', unsafe_allow_html=True)st.markdown("### π‘ Tips")st.info("""**Higher Error Correction** = More resilient to damage but larger QR code**Larger Module Size** = Easier to scan but bigger file**Good Contrast** = Better scanning reliability""")# Footerst.markdown("---")st.markdown("""<div style="text-align: center; color: #666; padding: 2rem;"><p>π Built with Streamlit | π Made with love for QR code enthusiasts</p></div>""", unsafe_allow_html=True)12345640 unmodified lines474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710815 unmodified lines12412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722813 unmodified lines2422432442452462472482492502512 unmodified lines2542552562572582592602 unmodified lines2632642652662672682692702712722732742752762772782792802812822832842855 unmodified lines2912922932942952962972982993003013023033043053063073083093103113 unmodified lines315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402import streamlit as stimport qrcodefrom PIL import Image, ImageDraw, ImageFontimport ioimport base6440 unmodified linesmargin: 1rem 0;box-shadow: 0 2px 4px rgba(0,0,0,0.1);}.stDownloadButton > button {background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);color: white;border: none;border-radius: 10px;padding: 0.5rem 2rem;font-weight: bold;width: 100%;}</style>""", unsafe_allow_html=True)def hex_to_rgb(hex_color):"""Convert hex color to RGB tuple"""hex_color = hex_color.lstrip('#')return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))def create_gradient_image(size, start_color, end_color, direction='horizontal'):"""Create a gradient image"""image = Image.new('RGB', size)draw = ImageDraw.Draw(image)if direction == 'horizontal':for x in range(size[0]):ratio = x / size[0]r = int(start_color[0] * (1 - ratio) + end_color[0] * ratio)g = int(start_color[1] * (1 - ratio) + end_color[1] * ratio)b = int(start_color[2] * (1 - ratio) + end_color[2] * ratio)draw.line([(x, 0), (x, size[1])], fill=(r, g, b))else: # verticalfor y in range(size[1]):ratio = y / size[1]r = int(start_color[0] * (1 - ratio) + end_color[0] * ratio)g = int(start_color[1] * (1 - ratio) + end_color[1] * ratio)b = int(start_color[2] * (1 - ratio) + end_color[2] * ratio)draw.line([(0, y), (size[0], y)], fill=(r, g, b))return imagedef create_rounded_qr(qr_img, corner_radius=20):"""Create rounded corners for QR code"""# Create mask for rounded cornerssize = qr_img.sizemask = Image.new('L', size, 0)draw = ImageDraw.Draw(mask)draw.rounded_rectangle([(0, 0), size], corner_radius, fill=255)# Apply maskqr_rounded = Image.new('RGBA', size, (255, 255, 255, 0))qr_rounded.paste(qr_img, (0, 0))qr_rounded.putalpha(mask)return qr_roundeddef create_qr_code(data, fill_color, back_color, border, box_size, error_correction, style_type, gradient_end_color=None):"""Generate QR code with custom styling"""# Error correction levels15 unmodified linesqr.add_data(data)qr.make(fit=True)# Generate base QR codeif style_type == "Gradient" and gradient_end_color:# Create gradient backgroundimg = qr.make_image(fill_color='black', back_color='white')# Create gradientstart_rgb = hex_to_rgb(fill_color)end_rgb = hex_to_rgb(gradient_end_color)gradient = create_gradient_image(img.size, start_rgb, end_rgb, 'horizontal')# Apply gradient to QR codeimg_array = img.load()gradient_array = gradient.load()for x in range(img.size[0]):for y in range(img.size[1]):if img_array[x, y] == 0: # Black pixel (QR code data)img_array[x, y] = gradient_array[x, y]else: # White pixel (background)img_array[x, y] = hex_to_rgb(back_color)else:img = qr.make_image(fill_color=fill_color, back_color=back_color)# Apply style modificationsif style_type == "Rounded":img = create_rounded_qr(img, corner_radius=box_size*2)elif style_type == "With Logo Space":# Create space in center for logodraw = ImageDraw.Draw(img)center_x, center_y = img.size[0] // 2, img.size[1] // 2logo_size = min(img.size) // 6draw.rectangle([center_x - logo_size//2, center_y - logo_size//2,center_x + logo_size//2, center_y + logo_size//2], fill=back_color, outline=fill_color, width=2)return imgdef get_qr_data_by_type(content_type):"""Get QR data based on content type"""if content_type == "Text":return st.text_area("Enter your text:", height=100, placeholder="Hello World!")elif content_type == "URL":url = st.text_input("Enter URL:", placeholder="https://example.com")if url and not url.startswith(('http://', 'https://')):url = 'https://' + urlreturn urlelif content_type == "Email":email = st.text_input("Email address:", placeholder="contact@example.com")subject = st.text_input("Subject (optional):")body = st.text_area("Message (optional):", height=80)if email:params = []if subject:params.append(f"subject={subject}")if body:params.append(f"body={body}")return f"mailto:{email}{'?' + '&'.join(params) if params else ''}"return ""elif content_type == "Phone":phone = st.text_input("Phone number:", placeholder="+1234567890")return f"tel:{phone}" if phone else ""elif content_type == "SMS":phone = st.text_input("Phone number:", placeholder="+1234567890")message = st.text_area("Message:", height=80, placeholder="Hello!")if phone:return f"sms:{phone}{'?body=' + message if message else ''}"return ""elif content_type == "WiFi":ssid = st.text_input("Network Name (SSID):", placeholder="MyWiFi")password = st.text_input("Password:", type="password")security = st.selectbox("Security Type", ["WPA", "WEP", "nopass"])hidden = st.checkbox("Hidden Network")if ssid:return f"WIFI:T:{security};S:{ssid};P:{password};H:{'true' if hidden else 'false'};;"return ""elif content_type == "vCard":name = st.text_input("Full Name:", placeholder="John Doe")phone = st.text_input("Phone:", placeholder="+1234567890")email = st.text_input("Email:", placeholder="john@example.com")organization = st.text_input("Organization (optional):", placeholder="Company Inc.")if name:vcard = f"BEGIN:VCARD\nVERSION:3.0\nFN:{name}\n"if phone:vcard += f"TEL:{phone}\n"if email:vcard += f"EMAIL:{email}\n"if organization:vcard += f"ORG:{organization}\n"vcard += "END:VCARD"return vcardreturn ""# Main headerst.markdown("""13 unmodified linescontent_type = st.selectbox("Content Type",["Text", "URL", "Email", "Phone", "SMS", "WiFi", "vCard"])qr_data = get_qr_data_by_type(content_type)st.markdown('</div>', unsafe_allow_html=True)# Style Settings2 unmodified linesstyle_type = st.selectbox("QR Style",["Standard", "Rounded", "Gradient", "With Logo Space"])col1, col2 = st.columns(2)2 unmodified lineswith col2:back_color = st.color_picker("Background Color", "#FFFFFF")gradient_end_color = Noneif style_type == "Gradient":gradient_end_color = st.color_picker("Gradient End Color", "#333333")st.markdown('</div>', unsafe_allow_html=True)# Advanced Settingsst.markdown('<div class="sidebar-section">', unsafe_allow_html=True)st.markdown("### βοΈ Advanced Settings")box_size = st.slider("Module Size", 5, 20, 10, help="Size of each QR code square")border = st.slider("Border Width", 1, 10, 4, help="White border around QR code")error_correction = st.selectbox("Error Correction Level",["L (~7%)", "M (~15%)", "Q (~25%)", "H (~30%)"],index=1,help="Higher levels = more damage resistance but larger code")st.markdown('</div>', unsafe_allow_html=True)5 unmodified linesif qr_data:try:# Generate QR codewith st.spinner("π¨ Generating your beautiful QR code..."):qr_img = create_qr_code(qr_data, fill_color, back_color, border,box_size, error_correction, style_type, gradient_end_color)# Display QR codest.markdown("### π± Your QR Code")st.image(qr_img, caption="Generated QR Code", use_container_width=True)# Convert to bytes for downloadimg_buffer = io.BytesIO()qr_img.save(img_buffer, format="PNG")img_bytes = img_buffer.getvalue()# Download sectionst.markdown("""<div class="download-section">3 unmodified lines""", unsafe_allow_html=True)# Download buttonfilename = f"qrcode_{content_type.lower()}_{style_type.lower().replace(' ', '_')}.png"st.download_button(label="π₯ Download QR Code",data=img_bytes,file_name=filename,mime="image/png",use_container_width=True)# QR Code Infost.info(f"""**QR Code Details:**- Content Type: {content_type}- Style: {style_type}- Size: {qr_img.size[0]}x{qr_img.size[1]} pixels- Error Correction: {error_correction}""")except Exception as e:st.error(f"β Error generating QR code: {str(e)}")st.info("π‘ Try adjusting your content or settings")else:# Welcome message with examplest.markdown("""### π Welcome to QR Code Generator!π **Get started by entering content in the sidebar**#### π What you can create:- **Text QR codes** for messages- **URL QR codes** for websites- **Contact QR codes** (vCard format)- **WiFi QR codes** for easy connection- **Email & SMS QR codes**#### π¨ Styling options:- Custom colors- Rounded corners- Gradient effects- Logo space preparation""")with col2:st.markdown("### β¨ Features")features = ["π¨ Multiple visual styles","π Custom colors & gradients","π± Various content types","βοΈ Advanced settings","π₯ Instant PNG download","π§ Error correction levels","π vCard contact support","πΆ WiFi QR codes"]for feature in features:st.markdown(f'<div class="feature-box">{feature}</div>', unsafe_allow_html=True)st.markdown("### π‘ Pro Tips")st.success("""**π― Best Practices:**- Use high contrast colors- Test with your phone camera- Higher error correction for outdoor use- Larger module size for distant scanning- Keep URLs short for simpler codes""")st.markdown("### π Error Correction Guide")st.info("""- **L (7%)**: Good for clean environments- **M (15%)**: Standard recommendation- **Q (25%)**: Better for rough handling- **H (30%)**: Best for outdoor/damaged codes""")# Footerst.markdown("---")st.markdown("""<div style="text-align: center; color: #666; padding: 2rem;"><p>π Built with Streamlit | π Made for QR code enthusiasts</p><p><small>π‘ Tip: Bookmark this page for quick QR code generation!</small></p></div>""", unsafe_allow_html=True)
src/streamlit_app.py+232-86