Skip to content

Instantly share code, notes, and snippets.

@agusmakmun
Last active January 31, 2016 05:57
Show Gist options
  • Save agusmakmun/81715f2cd4cc633a9106 to your computer and use it in GitHub Desktop.
Save agusmakmun/81715f2cd4cc633a9106 to your computer and use it in GitHub Desktop.
from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
from gtts import gTTS
from django.core.files.storage import default_storage as storage
from django.core.files.base import ContentFile
from cStringIO import StringIO
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
import datetime, time, threading
class Process_Threading(threading.Thread):
def __init__(self, detail):
self.detail = detail
threading.Thread.__init__(self)
def run(self):
txt = str(self.detail)
tts = gTTS(text=txt, lang='id')
tts.save("gallery/coba.mp3")
#Checking if file is available to remove it: http://stackoverflow.com/a/4905384/3445802
from django.core.files.storage import FileSystemStorage
class OverwriteStorage(FileSystemStorage):
def _save(self, name, content):
if self.exists(name):
self.delete(name)
return super(OverwriteStorage, self)._save(name, content)
def get_available_name(self, name):
return name
class Audio(models.Model):
....
detail = models.TextField()
mp3 = models.FileField(upload_to='files/audio/%Y/%m/%d', null=True, blank=True, storage=OverwriteStorage())
def make_audio(self, detail, mp3):
Process_Threading(detail).start()
fh = storage.open("coba.mp3")#, "r") #removing "r" mode, because if read mode, `StringIO` can't read it.
temp_audio = StringIO(fh.read()) #read file strorage with `StringIO`.
temp_audio.seek(0) #buff seek.
mp3.save("coba.mp3", ContentFile(temp_audio.read()), save=False)
fh.close()
return True
def save(self, *args, **kwargs):
super(Audio, self).save(*args, **kwargs)
if not self.make_audio(self.detail, self.mp3):
raise Exception('Could not create audio - is the file type valid?')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment