🐍 Python Programming Tutorial

สร้างระบบรายงานอัตโนมัติด้วย AI และ Web Search

สำหรับผู้เริ่มต้น ภาษาไทย 80% Free APIs

📚 เกี่ยวกับโปรเจกต์นี้

ในบทเรียนนี้ เราจะเรียนรู้การสร้างโปรแกรม Python ที่สามารถ:

🎯 คำศัพท์ Programming ที่ต้องรู้

  • API (Application Programming Interface) = ช่องทางสื่อสารระหว่างโปรแกรม
  • Request = การขอข้อมูล
  • Response = การตอบกลับข้อมูล
  • JSON = รูปแบบการจัดเก็บข้อมูล
  • Import = การนำเข้า library หรือ module
  • Function = ฟังก์ชัน คือชุดคำสั่งที่ทำงานเฉพาะ

🔧 เตรียมความพร้อม (Setup)

ติดตั้ง Libraries ที่จำเป็น

เราจะใช้ libraries (ห้องสมุดโค้ด) ดังนี้:

# ติดตั้งผ่าน terminal/command prompt pip install requests matplotlib anthropic duckduckgo-search

📦 Library แต่ละตัวทำอะไร?

  • requests - ใช้สำหรับส่ง HTTP requests
  • matplotlib - ใช้สร้าง charts และกราฟ
  • anthropic - ใช้เชื่อมต่อกับ Claude AI
  • duckduckgo-search - ใช้ค้นหาข้อมูลจากเว็บฟรี

💻 เริ่มเขียนโค้ด (Let's Code!)

1 นำเข้า Libraries

ขั้นแรก เราต้อง import (นำเข้า) libraries ที่จะใช้:

import json import requests from duckduckgo_search import DDGS from anthropic import Anthropic import matplotlib.pyplot as plt from collections import Counter import re # ตั้งค่า API client client = Anthropic(api_key="your-api-key-here")

2 สร้าง Function สำหรับค้นหาข้อมูล

เราจะสร้าง function ที่รับ query (คำค้นหา) แล้วคืนค่าผลการค้นหา:

def search_web(query, max_results=5): """ ค้นหาข้อมูลจากเว็บโดยใช้ DuckDuckGo Parameters: query (str): คำที่ต้องการค้นหา max_results (int): จำนวนผลลัพธ์สูงสุด Returns: list: รายการผลการค้นหา """ try: # สร้าง search instance ddgs = DDGS() # ทำการค้นหา results = [] for result in ddgs.text(query, max_results=max_results): results.append({ 'title': result['title'], 'body': result['body'], 'url': result['href'] }) return results except Exception as e: print(f"เกิดข้อผิดพลาดในการค้นหา: {e}") return []

✅ เข้าใจโค้ดส่วนนี้

def search_web(query, max_results=5):

  • def = ประกาศว่าจะสร้าง function
  • search_web = ชื่อ function
  • query, max_results = parameters (ตัวแปรที่รับเข้ามา)
  • try...except = จัดการกับ error ที่อาจเกิดขึ้น

3 สร้าง Function สำหรับส่งข้อมูลให้ AI

ตอนนี้เราจะสร้าง function ที่ส่งข้อมูลจากการค้นหาไปให้ AI วิเคราะห์และสร้างรายงาน:

def generate_report_with_ai(prompt, search_results): """ ใช้ AI สร้างรายงานจากผลการค้นหา Parameters: prompt (str): คำถามหรือหัวข้อที่ต้องการ search_results (list): ผลการค้นหาจากเว็บ Returns: str: รายงานที่ AI สร้างขึ้น """ # เตรียมข้อมูลจากการค้นหา search_context = "\n\n".join([ f"แหล่งที่ {i+1}: {r['title']}\nURL: {r['url']}\n{r['body']}" for i, r in enumerate(search_results) ]) # สร้าง prompt สำหรับ AI ai_prompt = f"""โปรดวิเคราะห์ข้อมูลต่อไปนี้และสร้างรายงานเกี่ยวกับ: {prompt} ข้อมูลจากการค้นหา: {search_context} โปรดสร้างรายงานที่: 1. สรุปข้อมูลหลักอย่างชัดเจน 2. อ้างอิงแหล่งที่มาในรายงาน 3. เขียนเป็นภาษาไทยที่เข้าใจง่าย 4. มีความยาวประมาณ 300-400 คำ""" # เรียกใช้ AI try: message = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=2000, messages=[ {"role": "user", "content": ai_prompt} ] ) return message.content[0].text except Exception as e: return f"เกิดข้อผิดพลาดในการสร้างรายงาน: {e}"

⚠️ สำคัญ!

คุณต้องมี API key จาก Anthropic เพื่อใช้ Claude AI

สมัครได้ที่: https://console.anthropic.com/

มี free tier ให้ใช้งานทดลอง!

4 สร้างกราฟจากข้อมูล

เราจะวิเคราะห์คำที่ปรากฏบ่อยในผลการค้นหา แล้วสร้างเป็น bar chart (กราฟแท่ง):

def create_chart(search_results, output_file="chart.png"): """ สร้างกราฟแสดงคำที่พบบ่อยในผลการค้นหา Parameters: search_results (list): ผลการค้นหา output_file (str): ชื่อไฟล์ที่จะบันทึก """ # รวมข้อความทั้งหมด all_text = " ".join([ r['title'] + " " + r['body'] for r in search_results ]) # แยกคำและกรองเฉพาะคำที่มีความหมาย words = re.findall(r'\b[a-zA-Zก-๙]{4,}\b', all_text.lower()) # นับความถี่ของคำ word_freq = Counter(words) # เอา 10 คำที่พบบ่อยที่สุด top_words = word_freq.most_common(10) # สร้างกราฟ words_list = [word for word, count in top_words] counts_list = [count for word, count in top_words] plt.figure(figsize=(12, 6)) plt.bar(words_list, counts_list, color='#667eea') plt.title('คำที่พบบ่อยในผลการค้นหา (Top 10)', fontsize=16, fontweight='bold', pad=20) plt.xlabel('คำ', fontsize=12) plt.ylabel('ความถี่', fontsize=12) plt.xticks(rotation=45, ha='right') plt.tight_layout() # บันทึกกราฟ plt.savefig(output_file, dpi=300, bbox_inches='tight') plt.close() print(f"✅ บันทึกกราฟที่: {output_file}") return top_words

📊 เกี่ยวกับการสร้างกราฟ

matplotlib เป็น library ยอดนิยมสำหรับสร้างกราฟใน Python

  • plt.figure() = สร้างพื้นที่สำหรับกราฟ
  • plt.bar() = สร้างกราฟแท่ง
  • plt.savefig() = บันทึกเป็นไฟล์รูปภาพ

5 รวม Function ทั้งหมดเข้าด้วยกัน

ตอนนี้เรามาสร้าง main function ที่เรียกใช้ทุกอย่าง:

def main(): """ Main function ที่รวมทุกขั้นตอนเข้าด้วยกัน """ print("="*60) print("🤖 ระบบสร้างรายงานอัตโนมัติด้วย AI") print("="*60) # รับ input จากผู้ใช้ user_prompt = input("\n💭 ใส่หัวข้อที่ต้องการค้นหา: ") print(f"\n🔍 กำลังค้นหาข้อมูลเกี่ยวกับ: {user_prompt}...") # ขั้นตอนที่ 1: ค้นหาข้อมูล search_results = search_web(user_prompt, max_results=5) if not search_results: print("❌ ไม่พบผลการค้นหา") return print(f"✅ พบผลการค้นหา {len(search_results)} รายการ") # ขั้นตอนที่ 2: สร้างกราฟ print("\n📊 กำลังสร้างกราฟ...") top_words = create_chart(search_results) # ขั้นตอนที่ 3: ให้ AI สร้างรายงาน print("\n🤖 กำลังให้ AI สร้างรายงาน...") report = generate_report_with_ai(user_prompt, search_results) # บันทึกรายงาน report_file = "report.txt" with open(report_file, 'w', encoding='utf-8') as f: f.write(f"รายงานเรื่อง: {user_prompt}\n") f.write("="*60 + "\n\n") f.write(report) f.write("\n\n" + "="*60 + "\n") f.write("\nแหล่งอ้างอิง:\n") for i, result in enumerate(search_results, 1): f.write(f"{i}. {result['title']}\n") f.write(f" {result['url']}\n\n") # แสดงผลลัพธ์ print("\n" + "="*60) print("✅ สำเร็จ! ผลลัพธ์:") print("="*60) print(f"📄 รายงาน: {report_file}") print(f"📊 กราฟ: chart.png") print("\n📝 ตัวอย่างรายงาน:") print("-"*60) print(report[:500] + "...") print("-"*60) # รันโปรแกรม if __name__ == "__main__": main()

🎯 โค้ดเต็ม (Complete Code)

นี่คือโค้ดทั้งหมดที่พร้อมใช้งาน บันทึกเป็นไฟล์ ai_report_generator.py:

#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ AI Report Generator with Web Search ระบบสร้างรายงานอัตโนมัติด้วย AI และการค้นหาเว็บ """ import json import re from collections import Counter from duckduckgo_search import DDGS from anthropic import Anthropic import matplotlib.pyplot as plt # ใส่ API key ของคุณที่นี่ API_KEY = "your-api-key-here" client = Anthropic(api_key=API_KEY) def search_web(query, max_results=5): try: ddgs = DDGS() results = [] for result in ddgs.text(query, max_results=max_results): results.append({ 'title': result['title'], 'body': result['body'], 'url': result['href'] }) return results except Exception as e: print(f"Error: {e}") return [] def generate_report_with_ai(prompt, search_results): search_context = "\n\n".join([ f"แหล่งที่ {i+1}: {r['title']}\nURL: {r['url']}\n{r['body']}" for i, r in enumerate(search_results) ]) ai_prompt = f"""โปรดวิเคราะห์ข้อมูลและสร้างรายงานเกี่ยวกับ: {prompt} ข้อมูล: {search_context} สร้างรายงานที่สรุปชัดเจน อ้างอิงแหล่งที่มา และเขียนเป็นภาษาไทย""" try: message = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=2000, messages=[{"role": "user", "content": ai_prompt}] ) return message.content[0].text except Exception as e: return f"Error: {e}" def create_chart(search_results, output_file="chart.png"): all_text = " ".join([r['title'] + " " + r['body'] for r in search_results]) words = re.findall(r'\b[a-zA-Zก-๙]{4,}\b', all_text.lower()) word_freq = Counter(words) top_words = word_freq.most_common(10) words_list = [word for word, count in top_words] counts_list = [count for word, count in top_words] plt.figure(figsize=(12, 6)) plt.bar(words_list, counts_list, color='#667eea') plt.title('คำที่พบบ่อยในผลการค้นหา (Top 10)', fontsize=16, pad=20) plt.xlabel('คำ', fontsize=12) plt.ylabel('ความถี่', fontsize=12) plt.xticks(rotation=45, ha='right') plt.tight_layout() plt.savefig(output_file, dpi=300) plt.close() print(f"✅ Chart saved: {output_file}") return top_words def main(): print("="*60) print("🤖 AI Report Generator") print("="*60) user_prompt = input("\n💭 ใส่หัวข้อ: ") print(f"\n🔍 กำลังค้นหา: {user_prompt}...") search_results = search_web(user_prompt, max_results=5) if not search_results: print("❌ ไม่พบผลการค้นหา") return print(f"✅ พบ {len(search_results)} รายการ") print("\n📊 สร้างกราฟ...") create_chart(search_results) print("\n🤖 AI กำลังสร้างรายงาน...") report = generate_report_with_ai(user_prompt, search_results) with open("report.txt", 'w', encoding='utf-8') as f: f.write(f"รายงาน: {user_prompt}\n{'='*60}\n\n") f.write(report) f.write("\n\nแหล่งอ้างอิง:\n") for i, r in enumerate(search_results, 1): f.write(f"{i}. {r['title']} - {r['url']}\n") print("\n✅ สำเร็จ!") print("📄 report.txt | 📊 chart.png") if __name__ == "__main__": main()

🚀 วิธีใช้งาน (How to Use)

ขั้นตอนการใช้งาน

  1. บันทึกโค้ดเป็นไฟล์ ai_report_generator.py
  2. แก้ไข API_KEY ใส่ API key ของคุณ
  3. เปิด terminal/command prompt
  4. รันคำสั่ง: python ai_report_generator.py
  5. ใส่หัวข้อที่ต้องการค้นหา เช่น "Python programming trends 2025"
  6. รอสักครู่ โปรแกรมจะสร้างไฟล์:
    • report.txt = รายงานจาก AI
    • chart.png = กราฟแสดงข้อมูล

📊 ตัวอย่างผลลัพธ์ (Example Output)

💭 Input:

Python machine learning libraries

📄 Report (ตัวอย่าง):

รายงานเกี่ยวกับ Python Machine Learning Libraries

Python เป็นภาษาโปรแกรมมิ่งที่ได้รับความนิยมสูงสุดในด้าน Machine Learning โดยมี libraries หลักๆ ที่นักพัฒนาใช้งานกันอย่างแพร่หลาย ได้แก่ TensorFlow, PyTorch, scikit-learn และ Keras...

[รายงานต่อ...]

📊 Chart:

[กราฟแท่งแสดงคำที่พบบ่อย เช่น: python, machine, learning, data, model, etc.]

🎓 สิ่งที่ได้เรียนรู้ (What You Learned)

เราได้เรียนรู้:

  • การใช้ APIs เพื่อเชื่อมต่อกับ external services
  • การทำ web search ด้วย DuckDuckGo
  • การเชื่อมต่อกับ Claude AI ผ่าน Anthropic API
  • การสร้าง charts ด้วย matplotlib
  • การจัดการ data และ text processing
  • การเขียน functions และโครงสร้างโปรแกรม
  • การจัดการ errors ด้วย try-except
  • การอ่านเขียนไฟล์ (file I/O)

🔥 ไอเดียพัฒนาต่อ (Enhancement Ideas)

คุณสามารถพัฒนาโปรแกรมนี้ต่อได้โดย:

  1. เพิ่มการสร้าง PDF report ที่สวยงาม
  2. ทำ web interface ด้วย Flask หรือ Streamlit
  3. เพิ่มกราฟประเภทอื่นๆ เช่น pie chart, line graph
  4. บันทึกข้อมูลลง database เช่น SQLite
  5. เพิ่ม sentiment analysis วิเคราะห์อารมณ์
  6. ทำ email notification เมื่อรายงานเสร็จ
  7. เพิ่มการ export เป็น Word, Excel
  8. ทำ scheduled reports รายงานอัตโนมัติตามเวลา

⚡ Tips สำหรับผู้เริ่มต้น

💡 คำแนะนำ:

  • อ่านเอกสาร (Documentation): อ่าน docs ของแต่ละ library จะช่วยให้เข้าใจการใช้งาน
  • ทดสอบทีละส่วน: ทดสอบแต่ละ function แยกก่อน ค่อยรวมกัน
  • จัดการ Error: ใช้ try-except เสมอเมื่อเชื่อมต่อ API
  • Code Comments: เขียน comments ภาษาไทยได้ ช่วยให้จำได้
  • Version Control: ใช้ Git เพื่อติดตามการเปลี่ยนแปลง

📚 แหล่งเรียนรู้เพิ่มเติม (Resources)

เว็บไซต์แนะนำ:

  • 🌐 Python Official: python.org
  • 🤖 Anthropic Docs: docs.anthropic.com
  • 📊 Matplotlib: matplotlib.org
  • 🔍 DuckDuckGo Search: github.com/deedy5/duckduckgo_search
  • 📖 Real Python: realpython.com (มีคอร์สภาษาไทย)
  • 💬 Thai Dev Community: facebook.com/groups/thaidev

❓ คำถามที่พบบ่อย (FAQ)

Q: ต้องเสียเงินในการใช้ API หรือไม่?

A: Anthropic มี free tier ให้ทดลองใช้ DuckDuckGo search ฟรี matplotlib ฟรี

Q: โค้ดทำงานช้า ทำยังไง?

A: ลดจำนวน search results หรือใช้ async/await สำหรับ parallel processing

Q: จะเปลี่ยนกราฟเป็นภาษาอื่นได้ไหม?

A: ได้! แค่แก้ไขข้อความใน plt.title(), plt.xlabel(), plt.ylabel()

Q: Error "Module not found" แก้ยังไง?

A: ติดตั้ง library ด้วย pip install [library-name]

🎉 ยินดีด้วย!

คุณได้เรียนรู้การสร้างระบบ AI-powered report generator แล้ว!
ลองนำไปประยุกต์ใช้กับงานของคุณได้เลย

Happy Coding! 🚀