toolAvatarVoiceOnly.py 2.4 KB

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