Python Streamlit과 Canva를 사용하여 이미지 인증 시스템을 만드는 방법!
포함
import streamlit as st import # your database manager here! from cryptography.fernet import Fernet from PIL import Image, PngImagePlugin import base64, hashlib, uuid
원하는 경우 Streamlit으로 세션을 초기화하세요
def initialize_session_state(): pass
메인 스크립트:
class BadgeConfig: def __init__(self): initialize_session_state() # Ensure badge_id is stored as a class attribute self.badge_id = None # Generate a SHA-256 hash from image data def generate_image_hash(self, image_data): return hashlib.sha256(image_data).hexdigest() # Create the encryption signature using Fernet def create_signature(self, unique_id): id_image_bytes = unique_id.encode("utf-8") # Ensure 32-byte length padded_id_image_bytes = id_image_bytes.ljust(32)[:32] encoded_key = base64.urlsafe_b64encode(padded_id_image_bytes) return Fernet(encoded_key) # Check if image was created on Canva using PngImagePlugin def is_canva_image(self, image): if isinstance(image, PngImagePlugin.PngImageFile): # Extract metadata from the image metadata = image.info # Info contains the metadata # Checking if 'Canva' appears in the 'xmp:CreatorTool' field xmp_metadata = metadata.get('XML:com.adobe.xmp', '') if "Canva" in xmp_metadata: return True return False # Display the uploaded badge and validate its dimensions and source def process_image(self, user_badge): try: image = Image.open(user_badge) WIDTH, HEIGHT = image.size if WIDTH != 1080 or HEIGHT != 1920: st.warning("This is not a valid dnakey-badge!") st.stop() # Check if the image is created on Canva if not self.is_canva_image(image): st.warning("The uploaded image is not a Canva PNG image!") st.stop() st.image(user_badge, caption="Uploaded Image", use_column_width=True) # Reset the file pointer and read the image data for hashing user_badge.seek(0) return user_badge.read() except Exception as e: st.error(f"Error processing the image: {str(e)}") st.stop() # Handle badge activation and update session def activate_badge(self, badge_usage, config_manager): if not st.session_state['toast_shown']: st.toast("**:blue[Your Id Badge is activated now!]**", icon="?") st.session_state['toast_shown'] = True if not st.session_state['usage_updated'] and badge_usage > 0: config_manager.update_usage_badge_count() st.session_state['usage_updated'] = True # Main function to create a session and handle badge logic def create_session(self, user_badge): # Process image and generate its unique ID image_data = self.process_image(user_badge) unique_id = self.generate_image_hash(image_data) # Create an encryption signature signature = self.create_signature(unique_id) # Create a UUID (version 5) based on the existing unique_id self.badge_id = str(uuid.uuid5(uuid.NAMESPACE_DNS, unique_id)) # Initialize config manager config_manager = ConfigManager(self.badge_id) badge_usage = config_manager.get_badge_usage() # Handle badge activation and session updates self.activate_badge(badge_usage, config_manager) return signature, self.badge_id # Return the badge_id as well # call the script with st.sidebar: st.title("Log-In Here:") with st.popover("Upload Your Agent Badge!", use_container_width=True): user_badge = st.file_uploader("Your Agent Badge!", type=["png"], key="agent_badge") if user_badge: # User badge is uploaded signature, badge_id = BadgeConfig().create_session(user_badge)
위 내용은 Python Streamlit과 Canva를 사용하여 이미지 인증 시스템을 만드는 방법!의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Python은 게임 및 GUI 개발에서 탁월합니다. 1) 게임 개발은 Pygame을 사용하여 드로잉, 오디오 및 기타 기능을 제공하며 2D 게임을 만드는 데 적합합니다. 2) GUI 개발은 Tkinter 또는 PYQT를 선택할 수 있습니다. Tkinter는 간단하고 사용하기 쉽고 PYQT는 풍부한 기능을 가지고 있으며 전문 개발에 적합합니다.

Python은 배우고 사용하기 쉽고 C는 더 강력하지만 복잡합니다. 1. Python Syntax는 간결하며 초보자에게 적합합니다. 동적 타이핑 및 자동 메모리 관리를 사용하면 사용하기 쉽지만 런타임 오류가 발생할 수 있습니다. 2.C는 고성능 응용 프로그램에 적합한 저수준 제어 및 고급 기능을 제공하지만 학습 임계 값이 높고 수동 메모리 및 유형 안전 관리가 필요합니다.

제한된 시간에 Python 학습 효율을 극대화하려면 Python의 DateTime, Time 및 Schedule 모듈을 사용할 수 있습니다. 1. DateTime 모듈은 학습 시간을 기록하고 계획하는 데 사용됩니다. 2. 시간 모듈은 학습과 휴식 시간을 설정하는 데 도움이됩니다. 3. 일정 모듈은 주간 학습 작업을 자동으로 배열합니다.

Python은 개발 효율에서 C보다 낫지 만 C는 실행 성능이 높습니다. 1. Python의 간결한 구문 및 풍부한 라이브러리는 개발 효율성을 향상시킵니다. 2.C의 컴파일 유형 특성 및 하드웨어 제어는 실행 성능을 향상시킵니다. 선택할 때는 프로젝트 요구에 따라 개발 속도 및 실행 효율성을 평가해야합니다.

Pythonlistsarepartoftsandardlardlibrary, whileraysarenot.listsarebuilt-in, 다재다능하고, 수집 할 수있는 반면, arraysarreprovidedByTearRaymoduledlesscommonlyusedDuetolimitedFunctionality.

파이썬은 자동화, 스크립팅 및 작업 관리가 탁월합니다. 1) 자동화 : 파일 백업은 OS 및 Shutil과 같은 표준 라이브러리를 통해 실현됩니다. 2) 스크립트 쓰기 : PSUTIL 라이브러리를 사용하여 시스템 리소스를 모니터링합니다. 3) 작업 관리 : 일정 라이브러리를 사용하여 작업을 예약하십시오. Python의 사용 편의성과 풍부한 라이브러리 지원으로 인해 이러한 영역에서 선호하는 도구가됩니다.

하루에 2 시간 동안 파이썬을 배우는 것으로 충분합니까? 목표와 학습 방법에 따라 다릅니다. 1) 명확한 학습 계획을 개발, 2) 적절한 학습 자원 및 방법을 선택하고 3) 실습 연습 및 검토 및 통합 연습 및 검토 및 통합,이 기간 동안 Python의 기본 지식과 고급 기능을 점차적으로 마스터 할 수 있습니다.

Python과 C는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1) Python은 간결한 구문 및 동적 타이핑으로 인해 빠른 개발 및 데이터 처리에 적합합니다. 2) C는 정적 타이핑 및 수동 메모리 관리로 인해 고성능 및 시스템 프로그래밍에 적합합니다.
