import time
import pygetwindow as gw
import pyautogui
import pytesseract
from transformers import pipeline
import sounddevice as sd
import soundfile as sf
import speech_recognition as sr
import threading
import sys

# Function to capture the window and return the text content
def capture_window_text(window_title):
    try:
        window = gw.getWindowsWithTitle(window_title)[0]
        # Activate the window
        window.activate()
        time.sleep(0.5)  # Wait for the window to come into focus

        # Take a screenshot of the window
        left, top, width, height = window.left, window.top, window.width, window.height
        screenshot = pyautogui.screenshot(region=(left, top, width, height))

        # Save the screenshot (optional)
        screenshot.save('window_capture.png')

        # Use OCR to extract text from the image
        text = pytesseract.image_to_string(screenshot)

        return text
    except IndexError:
        print(f"No window with title containing '{window_title}' found.")
        return None

# Function to capture audio output
def capture_audio(duration=5, filename='output.wav', samplerate=44100, channels=2):
    try:
        print("Starting audio recording...")
        # Record audio for the specified duration
        recording = sd.rec(int(duration * samplerate), samplerate=samplerate, channels=channels)
        sd.wait()  # Wait until recording is finished
        # Save recording to a file
        sf.write(filename, recording, samplerate)
        print("Audio recording complete.")
    except Exception as e:
        print(f"An error occurred while recording audio: {e}")

# Function to transcribe audio to text
def transcribe_audio(filename):
    r = sr.Recognizer()
    with sr.AudioFile(filename) as source:
        audio = r.record(source)
    try:
        print("Transcribing audio...")
        text = r.recognize_google(audio)
        print("Audio transcription complete.")
        return text
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand the audio")
        return ""
    except sr.RequestError as e:
        print(f"Could not request results from Google Speech Recognition service; {e}")
        return ""

# Function to generate a reaction using NLP
def generate_reaction(text):
    if not text.strip():
        return "Hmm, there's nothing to react to!"

    # Use a sentiment-analysis pipeline as an example
    nlp = pipeline('sentiment-analysis')

    # Process the text
    results = nlp(text)

    # Generate a reaction based on the sentiment
    for result in results:
        sentiment = result['label']
        score = result['score']
        if sentiment == 'POSITIVE':
            reaction = f"Wow, that's awesome! 😃 (confidence: {score:.2f})"
        elif sentiment == 'NEGATIVE':
            reaction = f"Oh no, that's not good! 😞 (confidence: {score:.2f})"
        else:
            reaction = f"Interesting... 🤔 (confidence: {score:.2f})"
        return reaction

# Main code
if name == 'main':
    # Specify the application window title (partial titles work)
    window_title = "Chrome"  # Replace with the title of the window you want to capture

    # Duration for capturing audio (in seconds)
    capture_duration = 5

    # Start audio recording in a separate thread
    audio_thread = threading.Thread(target=capture_audio, args=(capture_duration,))
    audio_thread.start()

    # Capture window text
    captured_text = capture_window_text(window_title)

    # Wait for audio recording to finish
    audio_thread.join()

    # Transcribe the audio
    transcribed_audio = transcribe_audio('output.wav')

    # Combine the captured text and transcribed audio
    combined_text = ""
    if captured_text:
        combined_text += captured_text.strip()
    if transcribed_audio:
        combined_text += "\n" + transcribed_audio.strip()

    if combined_text:
        print("Combined Text:")
        print(combined_text)

        # Generate reaction
        reaction = generate_reaction(combined_text)
        print("\nGenerated Reaction:")
        print(reaction)
    else:
        print("No text or audio could be extracted.")

issue [{
	"resource": "/d:/twitch_bot.py/twitch bot o1.py",
	"owner": "python",
	"code": {
		"value": "reportUndefinedVariable",
		"target": {
			"$mid": 1,
			"path": "/microsoft/pyright/blob/main/docs/configuration.md",
			"scheme": "https",
			"authority": "github.com",
			"fragment": "reportUndefinedVariable"
		}
	},
	"severity": 4,
	"message": "\"name\" is not defined",
	"source": "Pylance",
	"startLineNumber": 89,
	"startColumn": 4,
	"endLineNumber": 89,
	"endColumn": 8
}]