toolAvatarVoiceOnly.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. from fastapi import APIRouter
  2. from pydantic import BaseModel
  3. from gtts import gTTS
  4. import ffmpy
  5. import random
  6. from typing import Optional
  7. from fastapi.staticfiles import StaticFiles
  8. from fastapi import FastAPI,File,Request,Response
  9. import util,os, math, time
  10. from pydantic import BaseModel
  11. from fastapi.templating import Jinja2Templates
  12. import queue
  13. import threading
  14. import rpyc
  15. q = queue.Queue()
  16. router = APIRouter()
  17. class text_in(BaseModel):
  18. text: str
  19. lang: int #0:eng 1:zh
  20. avatar: int
  21. dir_sound = ''
  22. dir_anchor = ''
  23. @router.post("/get_material/", tags=["tools"])
  24. async def read_users(text_in: text_in):
  25. x = threading.Thread(target=memberOfQueue, args=(text_in.text,text_in.lang,text_in.avatar))
  26. x.start()
  27. return {'msg':'Pleas wait'}
  28. def memberOfQueue(txt,lang,avatar):
  29. q.put(compose(txt,lang,avatar))
  30. def compose(txt,lang,avatar):
  31. name_hash = str(time.time()).replace('.','')
  32. makeMP3(name_hash,txt,lang)
  33. call_anchor(name_hash,avatar)
  34. def makeMP3(name_hash,txt,lang):
  35. if lang==0:
  36. tts = gTTS(txt)
  37. tts.save(dir_sound+name_hash+"raw.mp3")
  38. else:
  39. tts = gTTS(txt,lang='zh-tw')
  40. tts.save(dir_sound+name_hash+"raw.mp3")
  41. #speed up
  42. ff = ffmpy.FFmpeg(inputs={dir_sound+name_hash+"raw.mp3": None}
  43. , outputs={dir_sound+name_hash+".mp3": ["-filter:a", "atempo=1.2"]})
  44. ff.run()
  45. os.remove(dir_sound+name_hash+"raw.mp3")
  46. def call_anchor(name_hash,avatar):
  47. conn = rpyc.classic.connect("192.168.1.111",18812)
  48. ros = conn.modules.os
  49. rsys = conn.modules.sys
  50. fr=open(dir_sound+name_hash+".mp3",'rb')# voice
  51. #warning!!! file my be replaced by other process
  52. fw=conn.builtins.open('/tmp/output.mp3','wb')
  53. while True:
  54. b=fr.read(1024)
  55. if b:
  56. fw.write(b)
  57. else:
  58. break
  59. fr.close()
  60. fw.close()
  61. val=random.randint(1000000,9999999)
  62. ros.chdir('/home/jared/to_video')
  63. ros.system('./p'+str(avatar)+'.sh '+str(val)+' &')
  64. while True:
  65. print('waiting...')
  66. if ros.path.exists('/tmp/results/'+str(val)):
  67. break
  68. time.sleep(5)
  69. print('waiting...')
  70. fr=conn.builtins.open('/tmp/results/'+str(val)+'.mp4','rb')
  71. fw=open(dir_anchor+name_hash+".mp4",'wb')
  72. while True:
  73. b=fr.read(1024)
  74. if b:
  75. fw.write(b)
  76. else:
  77. break
  78. fr.close()
  79. fw.close()