You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
2.6 KiB
76 lines
2.6 KiB
import base64
|
|
import json
|
|
import time
|
|
import asyncio
|
|
from django.shortcuts import render
|
|
from rest_framework.views import APIView
|
|
from rest_framework.response import Response
|
|
from rest_framework import status
|
|
from .serializers import OCRSerializer, AudioSerializer
|
|
from .utils import take_screenshot, translate_text, process_audio_for_translation
|
|
from channels.generic.websocket import WebsocketConsumer
|
|
from asgiref.sync import async_to_sync
|
|
from channels.generic.websocket import AsyncWebsocketConsumer
|
|
from io import BytesIO
|
|
|
|
|
|
|
|
class OCRView(APIView):
|
|
def post(self, request):
|
|
serializer = OCRSerializer(data=request.data)
|
|
if serializer.is_valid():
|
|
mode = serializer.validated_data['mode']
|
|
take_screenshot()
|
|
image = translate_text(mode)
|
|
if image is None:
|
|
return Response({'error': '无法识别的图像文件'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
|
|
|
# 将图片对象转换为 Base64 编码字符串
|
|
image_io = BytesIO()
|
|
image.save(image_io, format='JPEG')
|
|
image_io.seek(0)
|
|
image_base64 = base64.b64encode(image_io.getvalue()).decode('utf-8')
|
|
return Response({'image': image_base64}, status=status.HTTP_200_OK)
|
|
else:
|
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
class TranslateAudioView(APIView):
|
|
def post(self, request):
|
|
serializer = AudioSerializer(data=request.data)
|
|
if serializer.is_valid():
|
|
audio_file = serializer.validated_data['audio_file']
|
|
audio_data = audio_file.read()
|
|
audio_base64 = base64.b64encode(audio_data).decode('utf-8')
|
|
translation = process_audio_for_translation(audio_base64)
|
|
|
|
if translation:
|
|
return Response({'translation': translation}, status=status.HTTP_200_OK)
|
|
else:
|
|
return Response({'error': '无法翻译音频文件'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
|
else:
|
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
class SubtitleConsumer(WebsocketConsumer):
|
|
def connect(self):
|
|
self.accept()
|
|
|
|
def disconnect(self, close_code):
|
|
pass
|
|
|
|
def receive(self, text_data):
|
|
"""
|
|
接收消息
|
|
:param text_data: 客户端发送的消息
|
|
:return:
|
|
"""
|
|
print(text_data)
|
|
poetryList = [
|
|
"云想衣裳花想容",
|
|
"春风拂槛露华浓",
|
|
"若非群玉山头见",
|
|
"会向瑶台月下逢",
|
|
]
|
|
for i in poetryList:
|
|
time.sleep(0.5)
|
|
self.send(i) |