#Python Friday #307 Experimenting With a Large PDF File in #LangChain - #ai #llm
https://pythonfriday.dev/2025/11/307-experimenting-with-a-large-pdf-file-in-langchain/
Επειδή μου χρειάστηκε να βγάλω κάτι contacts από ένα mail server για να τα βάλω σε μια mailing (news) list, έφτιαξα το παρακάτω #python script που μετατρέπει vcf σε csv. Το vcf μου το έφτιαξε το #roundcube που είναι web UI για τον mail server, με export των contacts και το csv έγινε import σε #listmonk. Το script τσεκάρει αν υπάρχει καταχωρημένο email αλλιώς απορρίπτει την επαφή.
Εκτελείται απλά με python vcf_to_csv.py contacts.vcf, χρησιμοποιείστε και μετατρέψτε ελεύθερα.
import vobject
import csv
import sys
# Check for input file argument
if len(sys.argv) < 2:
print("Usage: python vcf_to_csv.py <input_file.vcf>")
sys.exit(1)
input_vcf_file = sys.argv[1]
# Using a new, descriptive output file name
output_csv_file = input_vcf_file.replace('.vcf', '_email_only_filtered.csv')
def extract_name_email_attrs(vcf_path, csv_path):
data = []
# Define the required CSV header
data.append(['email', 'name', 'attributes'])
try:
with open(vcf_path, 'r', encoding='utf-8') as vcf_file:
# Read all vCards from the file
vCards = vobject.readComponents(vcf_file.read())
contacts_processed = 0
contacts_exported = 0
for card in vCards:
contacts_processed += 1
name = ''
email = ''
attributes = '' # Remains blank
# 1. Extract Full Name (FN)
if hasattr(card, 'fn'):
name = card.fn.value
# 2. Extract Email (only the first one found)
if hasattr(card, 'email') and card.email:
email = card.email_list[0].value
# 🌟 THE FILTER: Only append the contact if the email field is NOT empty
if email:
data.append([email, name, attributes])
contacts_exported += 1
# Note: If you also want to ensure a name exists, you could use:
# if email and name:
except FileNotFoundError:
print(f"Error: The file '{vcf_path}' was not found.")
return
except Exception as e:
print(f"An error occurred: {e}")
return
# Write the extracted data to the CSV file
try:
with open(csv_path, 'w', newline='', encoding='utf-8') as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerows(data)
print(f"✅ Conversion successful!")
print(f" Input file: {vcf_path}")
print(f" Output file: {csv_path}")
print(f" Contacts processed: {contacts_processed}")
print(f" Contacts with email exported: {contacts_exported}")
except Exception as e:
print(f"Error writing CSV file: {e}")
# Run the function
extract_name_email_attrs(input_vcf_file, output_csv_file)
Mal seit längerer Zeit mal wieder was mit #Python gemacht. #uv dabei entdeckt. Sehr schneller Paket und Projektmanager für Python. Sehr genial, funktioniert richtig gut. #Pip wirkte inzwischen wirklich sehr veraltet.
https://github.com/astral-sh/uv
Edit: #fastapi finde ich gerade übrigens auch extrem geil muss ich sagen.
Recently moved some Shiny apps, written in both #Rstats and #Python, over to ShinyProxy. The main goal was isolating the apps and their dependencies, but also the very much needed solution for user authentication and ability to restrict access to apps based on user groups. Cannot recommend it enough!
#shinyproxy
Джун наоборот или разоблачение главного мифа вайб-кодинга
Вчера (27 ноября) Хабр устроил «Авторский огонёк». Было очень интересно, и меня задело одно утверждение докладчика. Оно заключалось в том, что ИИ может помочь писать простые куски кода, но не работает со сложными вещами. Таким образом, большие языковые модели уподобляются программисту-джуну. Решил с утра накатать об этом статью, опираясь на свои знания и опыт в вычислительной математике (в прошлом занимался моделированием, а последние несколько лет преподаю вычислительную математику в МФТИ), оцените, что получилось. Я думаю, что это главный миф вайб-кодинга . Всё ровно наоборот — ИИ нередко хорошо пишет довольно сложные вещи и достает важную информацию, которую самостоятельно трудно найти. Но путается как раз таки в самых элементарных вещах. Это джун наоборот. Проблема в том, что это опасная иллюзия и я вам сейчас наглядно объясню, почему, и чем это может быть опасно. Заваривайте кофе и готовьтесь к разоблачению, которое, может быть, в будущем спасет ваши миллионы, карьеру или даже человеческие жизни.
https://habr.com/ru/articles/971226/?utm_source=habrahabr&utm_medium=rss&utm_campaign=971226
#LLM #численные_методы #Python #ошибки_в_коде #вайбкодинг #метод_Эйлера #математическое_моделирование #физика #качество_кода #рефакторинг
Cool debugging trick I picked up from this article:
Django bulk_update memory issue
https://blog.pecar.me/django-bulk-update-memory-issue
Logging memory usage in #Python using `psutil` - example below 👇
Bonus: comparing list comp vs gen expression 🐍 😍 📈

des mises à jour de framework d'application web "tout #Python" 🎉
- #NiceGUI (#FastAPI + #vuejs sous le capot) passe en version 3.0
- #Gradio passe en version 6.0
Les créateurs de NiceGUI étaient interviewés dans cet épisode du podcast @talkpython : https://talkpython.fm/episodes/show/525/nicegui-goes-3.0
Retrouvez présentations & démos de NiceGUI, Gradio et #streamlit dans la session #PythonRennes du 1er décembre 2023 : https://www.youtube.com/watch?v=yspHNEFjKfQ&list=PLv7xGPH0RMUT1GSCGHJmqnswpk-nyz5aq&index=10
Just released aiomoto 0.0.7 to PyPi. aiomoto is a drop in moto wrapper/replacement that supports all moto plus adds support for aiobotocore, aioboto3, and now s3fs. Your sync and async mocks share state - write to a sync mock S3 bucket and read it in async. All in process, no mock server. #python

#Snakemake 9.14 is released. It integrates with yet another scripting language ( #hy, adding to the already existing #python, #r, #rust, #bash, and #julia support). Further it offers a massively improved local storage footprint. Many thanks to our awesome community! https://snakemake.github.io
Support the Denver Python User Group, a PSF Fiscal Sponsoree, and help keep local #Python learning accessible to all. From weekly project nights to monthly talks, they create welcoming spaces- because Python is for everyone 🐍✨
Donate today: https://psfmember.org/civicrm/contribute/transact/?reset=1&id=48

My mental model of str vs repr in #Python continues to be shattered. Everybody claims that the interactive REPL uses repr. I now know of two exceptions:
If the value of an expression is None, the REPL prints nothing, but repr(None) == 'None'.
What if the value is a string?
expression: "isn't"
str: "isn't"
repr: '"isn\'t"'
printed: "isn't"
expression: 'hel\'lo'
str: "hel'lo"
repr: '"hel\'lo"'
printed: "hel'lo"
It looks like, if x is a string, the REPL prints that string, not repr(x).