22 Ιανουαρίου, 1970

Avatar with A.I

 Hello! How can I help you?


Το πρόγραμμα αυτό είναι ένας AI εικονικός βοηθός που χρησιμοποιεί φωνητική αναγνώριση, επεξεργασία φυσικής γλώσσας (NLP) και οπτική αναπαράσταση μέσω ενός avatar.

🔹 Κύριες λειτουργίες:

  1. Χρήση GPT-2 για δημιουργία απαντήσεων σε φυσική γλώσσα.
  2. Αναγνώριση ομιλίας με speech_recognition για λήψη φωνητικών εντολών.
  3. Μετατροπή κειμένου σε ομιλία (TTS) μέσω pyttsx3 για απάντηση στον χρήστη.
  4. Οπτική αναπαράσταση avatar με κινούμενο GIF μέσω pygame.
  5. Διατήρηση ιστορικού συνομιλιών για βελτίωση των απαντήσεων.
  6. Υποστήριξη αλληλεπίδρασης σε πραγματικό χρόνο, με τη δυνατότητα να τερματίζει με εντολές όπως "quit".

import os
os.system('cls' if os.name == 'nt' else 'clear')
import cv2
import numpy as np
import pygame
import time
import pyttsx3
import threading
import speech_recognition as sr
from PIL import Image, ImageSequence
import torch
from transformers import GPT2LMHeadModel, GPT2Tokenizer


model_name = "gpt2"
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
tokenizer.pad_token = tokenizer.eos_token
gpt2_model = GPT2LMHeadModel.from_pretrained(model_name)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
gpt2_model.to(device)

def generate_text(prompt, max_new_tokens=50):
    inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=100)
    input_ids = inputs.input_ids.to(device)
    attention_mask = inputs.attention_mask.to(device)

    output = gpt2_model.generate(
        input_ids,
        attention_mask=attention_mask,
        max_new_tokens=max_new_tokens,
        num_return_sequences=1,
        no_repeat_ngram_size=3,
        do_sample=True,
        top_k=50,
        top_p=0.90,
        temperature=0.8,
        pad_token_id=tokenizer.eos_token_id,
        eos_token_id=tokenizer.eos_token_id
    )

    generated_text = tokenizer.decode(output[0], skip_special_tokens=True)
    sentences = generated_text.split(".")
    response = sentences[0].strip() + "." if sentences else "I don't understand."
   
    return response

pygame.init()
pygame.font.init()

window_open = False
running = True
avatar_text = "Hello! How can I help you?"

image_path = r"C:\Users\tsifa\Desktop\d duck.gif"

def create_avatar_animation(image_path):
    if not os.path.exists(image_path):
        print(f"❌ File {image_path} not found!")
        exit()
   
    gif = Image.open(image_path)
    frames = [pygame.image.fromstring(frame.convert("RGBA").tobytes(), frame.size, "RGBA")
              for frame in ImageSequence.Iterator(gif)]
    return frames

avatar_frames = create_avatar_animation(image_path)
frame_index = 0

recognizer = sr.Recognizer()
mic = sr.Microphone()

def listen():
    with mic as source:
        print("🎤 Speak now...")
        recognizer.adjust_for_ambient_noise(source, duration=1)
       
        try:
            audio = recognizer.listen(source, timeout=5)
            print("✅ Audio Captured!")
        except sr.WaitTimeoutError:
            print("⏳ No speech detected. Try again.")
            return None

    try:
        text = recognizer.recognize_google(audio, language="en-US")
        print(f"✅ Recognition: {text}")
        return text
    except sr.UnknownValueError:
        print("🤖 Could not understand.")
        return None
    except sr.RequestError:
        print("❌ Connection error.")
        return None

engine = pyttsx3.init()
engine_lock = threading.Lock()

def speak(text):
    print(f"🔊 AI: {text}")
    with engine_lock:
        engine.say(text)
        engine.runAndWait()

def update_avatar_text(new_text):
    global avatar_text
    avatar_text = new_text
    pygame.event.post(pygame.event.Event(pygame.USEREVENT))

def show_avatar():
    global window_open, running, frame_index, avatar_text

    if window_open:
        return
    window_open = True

    screen = pygame.display.set_mode((500, 500))
    pygame.display.set_caption("AI Assistant")

    font = pygame.font.SysFont("Arial", 24)

    while running:
        screen.fill((0, 0, 0))
        text = font.render(avatar_text, True, (155, 155, 155))
        screen.blit(text, (50, 450))
        screen.blit(pygame.transform.scale(avatar_frames[frame_index], (400, 400)), (50, 50))
        pygame.display.update()

        frame_index = (frame_index + 1) % len(avatar_frames)
        time.sleep(0.1)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                print("🛑 Exiting program...")
                running = False
                pygame.quit()
                os._exit(0)

def conversation_loop():
    global running
    conversation_context = []

    initial_message = "Hello! How can I help you?"
    print(f"🤖 AI: {initial_message}")
    update_avatar_text(initial_message)
    speak(initial_message)

    while running:
        print("🎤 Waiting for user input...")
        user_input = listen()

        if user_input is None:
            print("🔄 No input detected. Listening again...")
            continue

        if user_input.lower() in ["quit", "exit", "stop"]:
            print("🛑 Exiting...")
            running = False
            break

        prompt = "\n".join(conversation_context) + f"\nUser: {user_input}\nAI:"
        ai_response = generate_text(prompt)

        print(f"📝 User: {user_input}")
        print(f"🤖 AI: {ai_response}")

        update_avatar_text(ai_response)
        speak(ai_response)

        conversation_context.append(f"User: {user_input}")
        conversation_context.append(f"AI: {ai_response}")

        if len(conversation_context) > 10:
            conversation_context = conversation_context[-10:]


conversation_thread = threading.Thread(target=conversation_loop)
conversation_thread.start()

show_avatar()  
conversation_thread.join()  


Με αυτό το πρόγραμμα, πετύχαμε τη δημιουργία ενός διαδραστικού AI βοηθού με φωνητική αναγνώριση, επεξεργασία φυσικής γλώσσας και οπτική αναπαράσταση.

Πλήρης κύκλος επικοινωνίας:

  • Ο χρήστης μιλάει → το πρόγραμμα καταγράφει τη φωνή → μετατρέπει σε κείμενο → επεξεργάζεται την είσοδο με GPT-2 → δημιουργεί απάντηση → τη μετατρέπει ξανά σε ομιλία.
  • Έτσι, έχουμε μια φυσική συνομιλία σε πραγματικό χρόνο.

Ενσωμάτωση AI μέσω GPT-2:

  • Χρησιμοποιούμε μοντέλο NLP για έξυπνες και συνεκτικές απαντήσεις.
  • Διατηρούμε ιστορικό συνομιλίας για καλύτερη συνοχή στις απαντήσεις.

Αλληλεπίδραση με Avatar:

  • Το πρόγραμμα προσθέτει οπτικό feedback μέσω ενός avatar που κινείται και εμφανίζει κείμενο συνομιλίας.
  • Αυτό βελτιώνει την εμπειρία χρήστη, κάνοντάς το πιο φιλικό και διαδραστικό.

Αυτονομία & ρεαλιστική εμπειρία:

  • Το πρόγραμμα είναι πλήρως αυτόνομο και μπορεί να τρέχει συνεχώς.
  • Ο χρήστης μπορεί να το ελέγχει με τη φωνή του χωρίς να χρειάζεται πληκτρολόγηση.
  • Υπάρχει δυνατότητα τερματισμού με φωνητικές εντολές όπως "quit", "exit", κτλ.