from fastapi import FastAPI, Request
import uuid
import requests
import asyncio
import uvicorn
from multiprocessing import Process, Queue, Manager
import multiprocessing
import threading
import time

app = FastAPI()

class TranscriptProcessorProcess:


def __init__(self, input_queue, output_queue, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper):
    self.input_queue = input_queue
    self.output_queue = output_queue
    
    self.ImageInterpretation = ImageInterpretation
    self.TranscriptProcessor = TranscriptProcessor
    self.GenerateLLMResponse = GenerateLLMResponse
    self.Wispper = Wispper

# Асинхронная функция для обработки транскриптов YouTube
async def get_transcript_youtube(self):
    from server_modules.youtube_transcript import get_transcript_from_message
    while True:
        request_id, message_content = await asyncio.get_event_loop().run_in_executor(None, self.input_queue.get)
        response = await get_transcript_from_message(message_content)
        await asyncio.get_event_loop().run_in_executor(None, self.output_queue.put, (request_id, response))

# Обертка для запуска процесса с asyncio
def _run(self):
    asyncio.run(self.get_transcript_youtube())
class ImageInterpretationProcess:


def __init__(self, input_queue, output_queue, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper, task_ImageInterpretationProcess_started):
    self.input_queue = input_queue
    self.output_queue = output_queue

    self.ImageInterpretation = ImageInterpretation
    self.TranscriptProcessor = TranscriptProcessor
    self.GenerateLLMResponse = GenerateLLMResponse
    self.task_ImageInterpretationProcess_started = task_ImageInterpretationProcess_started
    self.Wispper = Wispper

async def Qwen_interpretation(self):
    from server_modules.image_interpretation import Qwen_2_VL
    while True:
        
         # Задержка, чтобы не создавать излишнюю нагрузку на CPU
        await asyncio.sleep(1)

        # Принудительное чтение значений
        generate_llm_response_value = self.GenerateLLMResponse.value  # Принудительное чтение
        wispper_value = self.Wispper.value  # Принудительное чтение
        task_image_interpretation_process_started_value = self.task_ImageInterpretationProcess_started.value  # Принудительное чтение


        print("-------")
        print(f"GenerateLLMResponse: {generate_llm_response_value}")
        print(f"Wispper: {wispper_value}")
        print(f"task_ImageInterpretationProcess_started: {task_image_interpretation_process_started_value}")
        print("-------")


        # print(task_ImageInterpretationProcess_started.value)
        # if self.GenerateLLMResponse.value == False and self.Wispper.value == False and task_ImageInterpretationProcess_started == True:
        #     self.ImageInterpretation.value = True
        #     requests.post("http://127.0.0.1:5000/v1/internal/model/unload")
        #     request_id, message_content = await asyncio.get_event_loop().run_in_executor(None, self.input_queue.get)
        #     Qwen_2_VL.model_to_gpu
        #     response = await Qwen_2_VL.process_img(message_content)
        #     Qwen_2_VL.model_to_cpu
        #     await asyncio.get_event_loop().run_in_executor(None, self.output_queue.put, (request_id, response))
        #     self.ImageInterpretation.value = False
        #     data = {"model_name": "c4ai-command-r-08-2024-IQ4_XS.gguf", "args": {}, "settings": {}}
        #     requests.post("http://127.0.0.1:5000/v1/internal/model/load", json=data)
        if generate_llm_response_value == False and wispper_value == False and task_image_interpretation_process_started_value == True:
            print("Condition met for Image Interpretation")
            print("Image Interpretation started")
            requests.post("http://127.0.0.1:5000/v1/internal/model/unload")
            print("Model unloaded for Image Interpretation")
            request_id, message_content = await asyncio.get_event_loop().run_in_executor(None, self.input_queue.get)
            print("Request ID and message content retrieved")
            Qwen_2_VL.model_to_gpu
            print("Model moved to GPU for Image Interpretation")
            response = await Qwen_2_VL.process_img(message_content)
            print("Image processed")
            Qwen_2_VL.model_to_cpu
            print("Model moved to CPU")
            await asyncio.get_event_loop().run_in_executor(None, self.output_queue.put, (request_id, response))
            print("Response added to output queue")
            self.ImageInterpretation.value = False
            print("Image Interpretation completed")
            data = {"model_name": "c4ai-command-r-08-2024-IQ4_XS.gguf", "args": {}, "settings": {}}
            requests.post("http://127.0.0.1:5000/v1/internal/model/load", json=data)
            print("Model loaded for next task")

def _run(self):
    asyncio.run(self.Qwen_interpretation())
class GenerateResponseProcess:


def __init__(self, input_queue, output_queue, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper, task_GenerateResponseProcess_started):
    self.input_queue = input_queue
    self.output_queue = output_queue

    self.ImageInterpretation = ImageInterpretation
    self.TranscriptProcessor = TranscriptProcessor
    self.GenerateLLMResponse = GenerateLLMResponse
    self.task_GenerateResponseProcess_started = task_GenerateResponseProcess_started
    self.Wispper = Wispper

async def Get_LLM_Response(self):
    from server_modules.text_web_ui import local_answer
    while True:
        if self.ImageInterpretation.value == False  and self.Wispper.value == False and self.task_GenerateResponseProcess_started.value == True:
            self.GenerateLLMResponse.value = True
            request_id, message_content = await asyncio.get_event_loop().run_in_executor(None, self.input_queue.get)
            response = await local_answer(message_content)
            await asyncio.get_event_loop().run_in_executor(None, self.output_queue.put, (request_id, response))
            self.GenerateLLMResponse.value = False

def _run(self):
    asyncio.run(self.Get_LLM_Response())
Функция для обработки запросов
def process_request(request, input_queue, output_queue, request_queues):
request_id = str(uuid.uuid4())
response_queue = Manager().Queue() # Создаем очередь для ответа
request_queues[request_id] = response_queue
input_queue.put((request_id, request))


# Ожидаем ответа
response = response_queue.get()
del request_queues[request_id]  # Удаляем очередь после получения ответа
return {"response": response}
Функция для обработки ответов
def handle_responses(output_queue, request_queues):
while True:
request_id, response = output_queue.get()
if request_id in request_queues:
request_queues[request_id].put(response)

@app.post("/get_youtube_transcript")
async def process_request_endpoint_1(request: Request):
data = await request.json()
return process_request(data, input_queue_1, output_queue_1, request_queues_1)

@app.post("/image_interpretation")
async def process_request_endpoint_2(request: Request):
global task_ImageInterpretationProcess_started
print("получил данные")
data = await request.json()
print(task_ImageInterpretationProcess_started.value) # Это покажет текущее значение
task_ImageInterpretationProcess_started.value = True # Исправлено на корректную запись
print(task_ImageInterpretationProcess_started.value) # Это покажет новое значение
print(task_ImageInterpretationProcess_started.value)
return process_request(data, input_queue_2, output_queue_2, request_queues_2)

@app.post("/generate_LLM_response")
async def process_request_endpoint_3(request: Request):
global task_GenerateResponseProcess_started
task_GenerateResponseProcess_started = True
data = await request.json()
return process_request(data, input_queue_3, output_queue_3, request_queues_3)

@app.post("/get_youtube_transcript_4")
async def process_request_endpoint_4(request: Request):
data = await request.json()
return process_request(data, input_queue_4, output_queue_4, request_queues_4)

if name == "main":
multiprocessing.freeze_support()


# Shared objects using Manager
manager = Manager()

# cureent_tasks
# Создание очередей
ImageInterpretation = manager.Value('b', False)
TranscriptProcessor = manager.Value('b', False)
GenerateLLMResponse = manager.Value('b', False)
Wispper = manager.Value('b', False)
task_GenerateResponseProcess_started = manager.Value('b', False)
task_ImageInterpretationProcess_started = manager.Value('b', False)


input_queue_1 = manager.Queue()
input_queue_2 = manager.Queue()
input_queue_3 = manager.Queue()
input_queue_4 = manager.Queue()

output_queue_1 = manager.Queue()
output_queue_2 = manager.Queue()
output_queue_3 = manager.Queue()
output_queue_4 = manager.Queue()

request_queues_1 = manager.dict()
request_queues_2 = manager.dict()
request_queues_3 = manager.dict()
request_queues_4 = manager.dict()

# Создаем и запускаем процессы
processes = []

# for i in range(1, 5):
TPP = Process(target=TranscriptProcessorProcess(input_queue_1, output_queue_1, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper)._run)
IIP = Process(target=ImageInterpretationProcess(input_queue_2, output_queue_2, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper, task_GenerateResponseProcess_started)._run)
GRP = Process(target=GenerateResponseProcess(input_queue_3, output_queue_3, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper, task_GenerateResponseProcess_started)._run)
processes.append(TPP)
processes.append(IIP)
processes.append(GRP)
TPP.start(), IIP.start(), GRP.start()



# Threads to handle responses
threading.Thread(target=handle_responses, args=(output_queue_1, request_queues_1), daemon=True).start()
threading.Thread(target=handle_responses, args=(output_queue_2, request_queues_2), daemon=True).start()
threading.Thread(target=handle_responses, args=(output_queue_3, request_queues_3), daemon=True).start()
threading.Thread(target=handle_responses, args=(output_queue_4, request_queues_4), daemon=True).start()

uvicorn.run(app, host="127.0.0.1", port=5100)

# Остановка всех процессов после завершения работы
for p in processes:
    p.join()


при обращении на эндпоинт /image_interpretation процесс Qwen_interpretation не запускает обработку из-за того, что в нём не обновляются значения переменных для условия. Вывод консоли выглядит в этот момент так:
получил данные
False
True
True
GenerateLLMResponse: False
Wispper: False
task_ImageInterpretationProcess_started: False

Как решить эту проблему и из-за чего она возникает?