検索エンジン「Voogle」

import requests
from flask import Flask, request, jsonify

app = Flask(__name__)

class SearchEngine:
    def __init__(self, documents):
        self.documents = documents

    def search_local(self, query):
        results = []
        for doc in self.documents:
            if query.lower() in doc["text"].lower():
                results.append(doc)
        return results

    def search_wikipedia(self, query, lang='ja'):
        base_url = f"https://{lang}.wikipedia.org/w/api.php"
        params = {
            'action': 'query',
            'list': 'search',
            'srsearch': query,
            'format': 'json'
        }
        response = requests.get(base_url, params=params)
        if response.status_code == 200:
            search_results = response.json().get('query', {}).get('search', [])
            return [{'id': result['pageid'], 'text': result['snippet']} for result in search_results]
        else:
            return []

# サンプルドキュメントデータ
documents = [
    {"id": 1, "text": "Pythonは汎用の高水準言語です。"},
    {"id": 2, "text": "検索エンジンは情報を検索するためのツールです。"},
    {"id": 3, "text": "人工知能はコンピュータによる知的な振る舞いを実現する技術です。"},
    {"id": 4, "text": "Web開発では、HTML、CSS、JavaScriptなどの技術が使われます。"},
    {"id": 5, "text": "データサイエンティストはデータから有益な情報を引き出す専門家です。"}
]

# SearchEngineインスタンスの作成
search_engine = SearchEngine(documents)

@app.route("/", methods=["GET", "POST"])
def search():
    # 以前の関数の内容は変更なし
    if request.method == "POST":
        query = request.form["query"]
        local_results = search_engine.search_local(query)
        wiki_results = search_engine.search_wikipedia(query)
        all_results = local_results + wiki_results
        if not all_results:
            return "検索結果はありません。"
        else:
            result_text = "<br>".join([f"<div><strong>ID:</strong> {result['id']}, <strong>Text:</strong> {result['text']}</div>" for result in all_results])
            return f"""
            <!DOCTYPE html>
            <html>
            <head>
                <title>検索エンジン</title>
                <style>
                    body {{
                        font-family: Arial, sans-serif;
                        margin: 0 auto;
                        max-width: 800px;
                        padding: 20px;
                    }}
                    h1 {{
                        color: #333;
                    }}
                    form {{
                        margin-bottom: 20px;
                    }}
                    input[type="text"] {{
                        margin-right: 10px;
                        padding: 10px;
                        width: calc(100% - 122px);
                    }}
                    input[type="submit"] {{
                        padding: 10px 20px;
                        background-color: #4CAF50;
                        color: white;
                        border: none;
                        cursor: pointer;
                    }}
                    input[type="submit"]:hover {{
                        background-color: #45a049;
                    }}
                    div {{
                        margin-bottom: 10px;
                        padding: 10px;
                        background-color: #f2f2f2;
                        border-left: 4px solid #4CAF50;
                    }}
                </style>
            </head>
            <body>
                <h1>検索エンジン</h1>
                <form method="POST">
                    <label for="query">検索キーワード:</label>
                    <input type="text" name="query" id="query" required>
                    <input type="submit" value="検索">
                </form>
                {result_text}
            </body>
            </html>
            """
    return """
    <!DOCTYPE html>
    <html>
    <head>
        <title>検索エンジン</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                margin: 0 auto;
                max-width: 800px;
                padding: 20px;
            }
            h1 {
                color: #333;
            }
            form {
                margin-bottom: 20px;
            }
            input[type="text"] {
                margin-right: 10px;
                padding: 10px;
                width: calc(100% - 122px);
            }
            input[type="submit"] {
                padding: 10px 20px;
                background-color: #4CAF50;
                color: white;
                border: none;
                cursor: pointer;
            }
            input[type="submit"]:hover {
                background-color: #45a049;
            }
        </style>
    </head>
    <body>
        <h1>検索エンジン</h1>
        <form method="POST">
            <label for="query">検索キーワード:</label>
            <input type="text" name="query" id="query" required>
            <input type="submit" value="検索">
        </form>
    </body>
    </html>
    """

if __name__ == "__main__":
    app.run(debug=True)

https://voogle.onrender.com/

GPT-2とWikipediaを使って生成するAI

GPT-2.py

from flask import Flask, render_template, request, redirect, url_for
from transformers import GPT2Tokenizer, GPT2LMHeadModel
import wikipedia

app = Flask(__name__)

# GPT-2のトークナイザーとモデルをロード
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained("gpt2")

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/generate', methods=['POST'])
def generate_text():
    # ユーザーからの入力を取得
    prompt_text = request.form['prompt']
    
    try:
        # Wikipediaからテキストを取得
        wikipedia_text = wikipedia.summary(prompt_text)
        
        # テキストの生成
        inputs = tokenizer.encode(wikipedia_text, return_tensors="pt")
        outputs = model.generate(inputs, max_length=100, num_return_sequences=1, temperature=0.7)
        
        # 生成されたテキストをデコードしてHTMLコードに組み込む
        generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
        
        # 生成されたテキストとWikipediaのテキストと共にHTMLを返す
        return render_template('index.html', prompt_text=prompt_text, generated_text=generated_text, wikipedia_text=wikipedia_text)
    
    except wikipedia.exceptions.DisambiguationError as e:
        # 曖昧性がある場合は、候補のリストを表示
        options = e.options
        return render_template('disambiguation.html', options=options)
    
    except wikipedia.exceptions.PageError:
        wikipedia_text = "Wikipediaにそのトピックが見つかりませんでした。"
        return render_template('index.html', prompt_text=prompt_text, wikipedia_text=wikipedia_text)

@app.route('/generate_with_option/<option>', methods=['GET'])
def generate_with_option(option):
    try:
        # Wikipediaからテキストを取得
        wikipedia_text = wikipedia.summary(option)
        
        # テキストの生成
        inputs = tokenizer.encode(wikipedia_text, return_tensors="pt")
        outputs = model.generate(inputs, max_length=100, num_return_sequences=1, temperature=0.7)
        
        # 生成されたテキストをデコードしてHTMLコードに組み込む
        generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
        
        # 生成されたテキストとWikipediaのテキストと共にHTMLを返す
        return render_template('index.html', prompt_text=option, generated_text=generated_text, wikipedia_text=wikipedia_text)
    
    except wikipedia.exceptions.PageError:
        wikipedia_text = "Wikipediaにそのトピックが見つかりませんでした。"
        return render_template('index.html', prompt_text=option, wikipedia_text=wikipedia_text)

if __name__ == '__main__':
    app.run(debug=True)

templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate Text</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }

        h1 {
            text-align: center;
            margin-top: 50px;
        }

        form {
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        label {
            font-weight: bold;
        }

        input[type="text"] {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            padding: 10px 20px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        button:hover {
            background-color: #0056b3;
        }

        .response {
            max-width: 600px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        .generated-text {
            margin-top: 20px;
        }

        .tweet-link {
            display: block;
            margin-top: 10px;
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>Generate Text</h1>
    <form action="/generate" method="POST">
        <label for="prompt">Enter your prompt:</label><br>
        <input type="text" id="prompt" name="prompt"><br><br>
        <button type="submit">Generate</button>
    </form>

    <!-- 生成されたテキストを表示 -->
    {% if generated_text %}
    <div class="response">
        <h2>Generated Text:</h2>
        <p class="generated-text">{{ generated_text }}</p>
        <a href="https://twitter.com/intent/tweet?text={{ generated_text }}" class="tweet-link" target="_blank">Tweet</a>
    </div>
    {% endif %}
</body>
</html>

templates/disambiguation.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Disambiguation Page</title>
</head>
<body>
    <h1>Disambiguation</h1>
    <p>Multiple meanings were found for the provided prompt. Please select the intended meaning:</p>
    <ul>
        {% for option in options %}
            <li><a href="{{ url_for('generate_with_option', option=option) }}">{{ option }}</a></li>
        {% endfor %}
    </ul>
</body>
</html>

python GPT-2

from transformers import GPT2LMHeadModel, GPT2Tokenizer

def generate_text(prompt, max_length=100):
    tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
    model = GPT2LMHeadModel.from_pretrained("gpt2")

    inputs = tokenizer.encode(prompt, return_tensors='pt')
    outputs = model.generate(inputs, max_length=max_length, num_return_sequences=1)
    return tokenizer.decode(outputs[0], skip_special_tokens=True)

prompt = "こんにちは"
generated_text = generate_text(prompt)
print(generated_text)

python タスク

import os
import json
from datetime import datetime

class Task:
    def __init__(self, description, deadline=None, completed=False):
        self.description = description
        self.deadline = deadline
        self.completed = completed

    def to_dict(self):
        return {
            "description": self.description,
            "deadline": self.deadline.strftime("%Y-%m-%d %H:%M") if self.deadline else None,
            "completed": self.completed
        }

    @classmethod
    def from_dict(cls, task_dict):
        deadline_str = task_dict.get("deadline")
        deadline = datetime.strptime(deadline_str, "%Y-%m-%d %H:%M") if deadline_str else None
        return cls(task_dict["description"], deadline, task_dict["completed"])

class TaskList:
    def __init__(self, filename):
        self.filename = filename
        self.tasks = []
        self.load_tasks()

    def load_tasks(self):
        if os.path.exists(self.filename):
            with open(self.filename, 'r') as file:
                task_data = json.load(file)
                self.tasks = [Task.from_dict(task_dict) for task_dict in task_data]

    def save_tasks(self):
        with open(self.filename, 'w') as file:
            task_data = [task.to_dict() for task in self.tasks]
            json.dump(task_data, file, indent=4)

    def add_task(self, description, deadline_str=None):
        deadline = datetime.strptime(deadline_str, "%Y-%m-%d %H:%M") if deadline_str else None
        task = Task(description, deadline)
        self.tasks.append(task)
        self.save_tasks()
        print("タスクを追加しました")

    def edit_task(self, task_index, description=None, deadline_str=None):
        if 1 <= task_index <= len(self.tasks):
            task = self.tasks[task_index - 1]
            if description:
                task.description = description
            if deadline_str:
                task.deadline = datetime.strptime(deadline_str, "%Y-%m-%d %H:%M") if deadline_str else None
            self.save_tasks()
            print("タスクを編集しました")
        else:
            print("無効なタスク番号です")

    def display_tasks(self):
        if not self.tasks:
            print("タスクはありません")
        else:
            print("タスク一覧:")
            for i, task in enumerate(self.tasks, 1):
                status = "完了" if task.completed else "未完了"
                deadline = task.deadline.strftime("%Y-%m-%d %H:%M") if task.deadline else "なし"
                print(f"{i}. [{status}] {task.description} (締切: {deadline})")

    def mark_task_completed(self, task_index):
        if 1 <= task_index <= len(self.tasks):
            task = self.tasks[task_index - 1]
            task.completed = True
            self.save_tasks()
            print(f"タスク '{task.description}' を完了にしました")
        else:
            print("無効なタスク番号です")

    def delete_task(self, task_index):
        if 1 <= task_index <= len(self.tasks):
            deleted_task = self.tasks.pop(task_index - 1)
            self.save_tasks()
            print(f"タスク '{deleted_task.description}' を削除しました")
        else:
            print("無効なタスク番号です")

def main():
    filename = "tasks.json"
    task_list = TaskList(filename)

    while True:
        print("\n操作を選択してください:")
        print("1. タスクを追加")
        print("2. タスクを編集")
        print("3. タスク一覧を表示")
        print("4. タスクを完了にする")
        print("5. タスクを削除する")
        print("6. 終了")

        choice = input("選択 (1/2/3/4/5/6): ")

        if choice == '6':
            break
        elif choice == '1':
            description = input("新しいタスクの説明を入力してください: ")
            deadline_str = input("締切日時 (YYYY-MM-DD HH:MM) を入力してください (未入力可): ")
            task_list.add_task(description, deadline_str)
        elif choice == '2':
            task_list.display_tasks()
            task_index = int(input("編集するタスクの番号を入力してください: "))
            description = input("新しい説明を入力してください (未入力で変更なし): ")
            deadline_str = input("新しい締切日時 (YYYY-MM-DD HH:MM) を入力してください (未入力で変更なし): ")
            task_list.edit_task(task_index, description, deadline_str)
        elif choice == '3':
            task_list.display_tasks()
        elif choice == '4':
            task_list.display_tasks()
            task_index = int(input("完了にするタスクの番号を入力してください: "))
            task_list.mark_task_completed(task_index)
        elif choice == '5':
            task_list.display_tasks()
            task_index = int(input("削除するタスクの番号を入力してください: "))
            task_list.delete_task(task_index)
        else:
            print("無効な選択です")

if __name__ == "__main__":
    main()

python 検索エンジン

# データ
documents = [
    "Python is a popular programming language.",
    "It is known for its simplicity and readability.",
    "Python has a large community of developers.",
    "Python is widely used in web development."
]

# データの前処理
def preprocess(text):
    return text.lower()

# インデックスの作成
def create_index(documents):
    index = {}
    for doc_id, doc in enumerate(documents):
        doc = preprocess(doc)
        words = doc.split()
        for word in words:
            if word not in index:
                index[word] = []
            index[word].append(doc_id)
    return index

# クエリ処理
def search(query, index):
    query = preprocess(query)
    words = query.split()
    result = set(range(len(documents)))

    for word in words:
        if word in index:
            result &= set(index[word])

    return [documents[i] for i in result]

# メイン
if __name__ == "__main__":
    index = create_index(documents)

    while True:
        query = input("検索クエリを入力してください (終了するには 'exit' を入力): ")
        if query == 'exit':
            break
        results = search(query, index)
        if results:
            for i, result in enumerate(results, start=1):
                print(f"{i}. {result}")
        else:
            print("一致する文書はありません。")

python todoリスト

import os

# ファイル名
todo_filename = 'todo.txt'

# TODOリストを表示する関数
def show_todo_list():
    if os.path.exists(todo_filename):
        with open(todo_filename, 'r') as file:
            todo_list = file.readlines()
            if todo_list:
                print("TODOリスト:")
                for i, item in enumerate(todo_list, start=1):
                    print(f"{i}. {item.strip()}")
            else:
                print("TODOリストは空です。")
    else:
        print("TODOリストはまだ作成されていません。")

# TODOアイテムを追加する関数
def add_todo_item(item):
    with open(todo_filename, 'a') as file:
        file.write(item + '\n')
    print(f"'{item}' をTODOリストに追加しました。")

# TODOアイテムを削除する関数
def remove_todo_item(item_number):
    if os.path.exists(todo_filename):
        with open(todo_filename, 'r') as file:
            todo_list = file.readlines()
        if 1 <= item_number <= len(todo_list):
            removed_item = todo_list.pop(item_number - 1).strip()
            with open(todo_filename, 'w') as file:
                file.writelines(todo_list)
            print(f"'{removed_item}' をTODOリストから削除しました。")
        else:
            print("指定された番号のTODOアイテムは存在しません。")
    else:
        print("TODOリストはまだ作成されていません。")

# メインメニューを表示する関数
def main_menu():
    while True:
        print("\nメニュー:")
        print("1. TODOリストを表示")
        print("2. TODOアイテムを追加")
        print("3. TODOアイテムを削除")
        print("4. 終了")
        
        choice = input("選択してください: ")

        if choice == '1':
            show_todo_list()
        elif choice == '2':
            item = input("追加するTODOアイテムを入力してください: ")
            add_todo_item(item)
        elif choice == '3':
            show_todo_list()
            item_number = int(input("削除するTODOアイテムの番号を入力してください: "))
            remove_todo_item(item_number)
        elif choice == '4':
            print("アプリケーションを終了します。")
            break
        else:
            print("無効な選択です。再度選択してください。")

if __name__ == "__main__":
    main_menu()

python メソッドのオーバーライド

class Post: # 親クラス Superクラス
def init(self, text):
self._text = text
self._likes = 0

def show(self):
    print(f"{self._text} - {self._likes}")

def like(self):
    self._likes += 1

class SponsoredPost(Post): # 子クラス Subクラス
def init(self, text, sponsor):
# self._text = text
# self._likes = 0
super().init(text)
self._sponsor = sponsor

def show(self):
    print(f"{self._text} - {self._likes} sponsored by {self._sponsor}")

posts = [
Post(“Hello”),
Post(“Hi”),
SponsoredPost(“Hey”, “dotinstall”),
]

posts[2].like()

for post in posts:
post.show()

python クラスの継承

class Post: # 親クラス Superクラス
def init(self, text):
self._text = text
self._likes = 0

def show(self):
    print(f"{self._text} - {self._likes}")

def like(self):
    self._likes += 1

class SponsoredPost(Post): # 子クラス Subクラス
pass

posts = [
Post(“Hello”),
Post(“Hi”),
SponsoredPost(“Hey”),
]

for post in posts:
post.show()

python メソッドの定義

class Post:
_count = 0
def init(self, text):
self._text = text
self._likes = 0
Post._count += 1

@classmethod
def show_count(cls):
    print(f"{cls._count} instances created")
def show(self):
    print(f"{self._text} - {self._likes}")

def like(self):
    self._likes += 1

posts = [
Post(“Hello”),
Post(“Hi”),
]

for post in posts:
post.show()

Post.show_count()