Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions Doc_to_QR_vice_versa.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import os
import cv2
import qrcode
from docx import Document
from textwrap import wrap
from PIL import Image

# === CONFIG ===
MAX_CHARS = 1000 # Max characters per QR (to avoid overflow)

# === FUNCTIONS ===

def read_txt_file(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
return f.read()

def read_docx_file(file_path):
doc = Document(file_path)
return '\n'.join([para.text for para in doc.paragraphs])

def generate_qr_codes(text, output_folder='qr_output'):
os.makedirs(output_folder, exist_ok=True)
chunks = wrap(text, MAX_CHARS)
for i, chunk in enumerate(chunks, start=1):
qr = qrcode.make(chunk)
qr.save(os.path.join(output_folder, f'qr_page_{i}.png'))
print(f"\n✅ {len(chunks)} QR code(s) generated in folder: '{output_folder}'")

def convert_file_to_qr():
file_path = input("Enter path of .txt or .docx file: ").strip()
if not os.path.exists(file_path):
print("❌ File not found.")
return

ext = os.path.splitext(file_path)[1].lower()
if ext == '.txt':
content = read_txt_file(file_path)
elif ext == '.docx':
content = read_docx_file(file_path)
else:
print("❌ Unsupported file type. Use .txt or .docx only.")
return

generate_qr_codes(content)

def read_qr_code(image_path):
img = cv2.imread(image_path)
detector = cv2.QRCodeDetector()
data, _, _ = detector.detectAndDecode(img)
return data

def reconstruct_text_from_qr(folder_path):
qr_files = sorted(
[f for f in os.listdir(folder_path) if f.endswith('.png')],
key=lambda x: int(''.join(filter(str.isdigit, x)) or 0)
)
full_text = ""
for file in qr_files:
qr_path = os.path.join(folder_path, file)
data = read_qr_code(qr_path)
full_text += data
return full_text

def save_as_txt(text, filename='reconstructed.txt'):
with open(filename, 'w', encoding='utf-8') as f:
f.write(text)
print(f"✅ Text saved as {filename}")

def save_as_docx(text, filename='reconstructed.docx'):
doc = Document()
for line in text.split('\n'):
doc.add_paragraph(line)
doc.save(filename)
print(f"✅ DOCX saved as {filename}")

def convert_qr_to_file():
folder_path = input("Enter folder path with QR images: ").strip()
if not os.path.isdir(folder_path):
print("❌ Invalid folder.")
return

text = reconstruct_text_from_qr(folder_path)
output_format = input("Save as (txt/docx)? ").strip().lower()

if output_format == 'txt':
save_as_txt(text)
elif output_format == 'docx':
save_as_docx(text)
else:
print("❌ Invalid format. Choose 'txt' or 'docx'.")

# === MAIN ===

def main():
print("\n📌 Choose an option:\n1. Convert DOCX/TXT to QR Code(s)\n2. Convert QR Code(s) to DOCX/TXT")
choice = input("Enter 1 or 2: ").strip()

if choice == '1':
convert_file_to_qr()
elif choice == '2':
convert_qr_to_file()
else:
print("❌ Invalid choice.")

if __name__ == '__main__':
main()
106 changes: 106 additions & 0 deletions doc_to_qr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import os
import cv2
import qrcode
from docx import Document
from textwrap import wrap
from PIL import Image

# === CONFIG ===
MAX_CHARS = 1000 # Max characters per QR (to avoid overflow)

# === FUNCTIONS ===

def read_txt_file(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
return f.read()

def read_docx_file(file_path):
doc = Document(file_path)
return '\n'.join([para.text for para in doc.paragraphs])

def generate_qr_codes(text, output_folder='qr_output'):
os.makedirs(output_folder, exist_ok=True)
chunks = wrap(text, MAX_CHARS)
for i, chunk in enumerate(chunks, start=1):
qr = qrcode.make(chunk)
qr.save(os.path.join(output_folder, f'qr_page_{i}.png'))
print(f"\n✅ {len(chunks)} QR code(s) generated in folder: '{output_folder}'")

def convert_file_to_qr():
file_path = input("Enter path of .txt or .docx file: ").strip()
if not os.path.exists(file_path):
print("❌ File not found.")
return

ext = os.path.splitext(file_path)[1].lower()
if ext == '.txt':
content = read_txt_file(file_path)
elif ext == '.docx':
content = read_docx_file(file_path)
else:
print("❌ Unsupported file type. Use .txt or .docx only.")
return

generate_qr_codes(content)

def read_qr_code(image_path):
img = cv2.imread(image_path)
detector = cv2.QRCodeDetector()
data, _, _ = detector.detectAndDecode(img)
return data

def reconstruct_text_from_qr(folder_path):
qr_files = sorted(
[f for f in os.listdir(folder_path) if f.endswith('.png')],
key=lambda x: int(''.join(filter(str.isdigit, x)) or 0)
)
full_text = ""
for file in qr_files:
qr_path = os.path.join(folder_path, file)
data = read_qr_code(qr_path)
full_text += data
return full_text

def save_as_txt(text, filename='reconstructed.txt'):
with open(filename, 'w', encoding='utf-8') as f:
f.write(text)
print(f"✅ Text saved as {filename}")

def save_as_docx(text, filename='reconstructed.docx'):
doc = Document()
for line in text.split('\n'):
doc.add_paragraph(line)
doc.save(filename)
print(f"✅ DOCX saved as {filename}")

def convert_qr_to_file():
folder_path = input("Enter folder path with QR images: ").strip()
if not os.path.isdir(folder_path):
print("❌ Invalid folder.")
return

text = reconstruct_text_from_qr(folder_path)
output_format = input("Save as (txt/docx)? ").strip().lower()

if output_format == 'txt':
save_as_txt(text)
elif output_format == 'docx':
save_as_docx(text)
else:
print("❌ Invalid format. Choose 'txt' or 'docx'.")

# === MAIN ===

def main():
print("\n📌 Choose an option:\n1. Convert DOCX/TXT to QR Code(s)\n2. Convert QR Code(s) to DOCX/TXT")
choice = input("Enter 1 or 2: ").strip()

if choice == '1':
convert_file_to_qr()
elif choice == '2':
convert_qr_to_file()
else:
print("❌ Invalid choice.")

if __name__ == '__main__':
main()