File size: 4,507 Bytes
a3d1731
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1e8c9d
 
 
a3d1731
 
 
 
 
c91fc90
a3d1731
 
 
 
 
fdc124c
 
 
a3d1731
 
fdc124c
 
 
 
 
 
 
 
 
a3d1731
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
042032b
2b2fe65
a3d1731
042032b
 
c91fc90
 
 
 
 
 
 
a3d1731
f1e8c9d
a3d1731
 
 
fdc124c
10d7d2a
042032b
f1e8c9d
042032b
 
 
fdc124c
 
 
042032b
 
 
 
c91fc90
f1e8c9d
 
a194c92
 
a3d1731
042032b
a3d1731
f1e8c9d
 
 
 
 
 
 
 
 
 
 
 
c91fc90
f1e8c9d
 
 
 
 
1c16477
f1e8c9d
 
1c16477
 
f1e8c9d
 
1c16477
 
f1e8c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3d1731
f1e8c9d
 
2b2fe65
 
f1e8c9d
dc87fd6
f1e8c9d
a3d1731
f1e8c9d
 
 
 
 
 
 
 
c91fc90
 
a3d1731
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import io
from fastapi import FastAPI, File, UploadFile
from werkzeug.utils import secure_filename
import speech_recognition as sr
import subprocess
import os
import requests
import random
import pandas as pd
from pydub import AudioSegment
from datetime import datetime
from datetime import date
import numpy as np
from sklearn.ensemble import RandomForestRegressor
import shutil
import json
from transformers import AutoModelForQuestionAnswering, AutoTokenizer, pipeline
from pydantic import BaseModel
from typing import Annotated
from transformers import BertTokenizerFast, EncoderDecoderModel
import torch
import random
import string
import time

from fastapi import Form

class Query(BaseModel):
    text: str
    code:str
   
# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# tokenizer = BertTokenizerFast.from_pretrained('mrm8488/bert-small2bert-small-finetuned-cnn_daily_mail-summarization')
# model = EncoderDecoderModel.from_pretrained('mrm8488/bert-small2bert-small-finetuned-cnn_daily_mail-summarization').to(device)

from fairseq.checkpoint_utils import load_model_ensemble_and_task_from_hf_hub
from fairseq.models.text_to_speech.hub_interface import TTSHubInterface
import IPython.display as ipd


models, cfg, task = load_model_ensemble_and_task_from_hf_hub(
    "facebook/fastspeech2-en-ljspeech",
    # 'facebook/fastspeech2-en-200_speaker-cv4',
    arg_overrides={"vocoder": "hifigan", "fp16": False}
)
model = models[0]
TTSHubInterface.update_cfg_with_data_cfg(cfg, task.data_cfg)
generator = task.build_generator([model], cfg)





from fastapi import FastAPI, Request, Depends, UploadFile, File
from fastapi.exceptions import HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse


app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'],
)


# cred = credentials.Certificate('key.json')
# app1 = firebase_admin.initialize_app(cred)
# db = firestore.client()
# data_frame = pd.read_csv('data.csv')



@app.on_event("startup")
async def startup_event():
    print("on startup")
    

audio_space="https://audiospace-1-u9912847.deta.app/upload"

# @app.post("/code")
# async def get_code(request: Request):
#     data = await request.form()
#     code = data.get("code")
#     global audio_space
#     print("code ="+code)
#     audio_space= audio_space+code

import threading
@app.post("/")
async def get_answer(q: Query ):

    text = q.text
    code= q.code
    
    
    N = 20
    res = ''.join(random.choices(string.ascii_uppercase +
                             string.digits, k=N))



    res= res+ str(time.time())

    filename= res

    t = threading.Thread(target=do_ML, args=(filename,text,code))  
    t.start()

    return JSONResponse({"id": filename})

    

    return "hello"


import requests
import io
import torch
from scipy.io import wavfile
import soundfile as sf
import wave
import audioop
import io

    
def do_ML(filename:str,text:str,code:str):
    sample = TTSHubInterface.get_model_input(task, text)
    wav, rate = TTSHubInterface.get_prediction(task, model, generator, sample)

    def compress_audio_wav_bytes(wav_bytes, output_format):
    # Load the WAV data from bytes
        audio_data, sample_rate = sf.read((wav_bytes))

    # Compress and save the audio data with the specified output format
        output_bytes = io.BytesIO()
        sf.write(output_bytes, audio_data, sample_rate, format=output_format)

    # Retrieve the compressed audio data as bytes
        compressed_bytes = output_bytes.getvalue()
        return compressed_bytes



    wav_bytes = io.BytesIO()

# Write the audio data to the byte stream
    sf.write(wav_bytes, wav.numpy(), rate, format='WAV', subtype='PCM_16')

# Set the position of the byte stream to the beginning
    wav_bytes.seek(0)

    format = 'flac'  # Specify the output format ('flac', 'mp3', etc.)

    wav_bytes = compress_audio_wav_bytes(wav_bytes, format)

    
    files = {'file': wav_bytes}

    # global audio_space
    url = code

    data = {"filename": filename}
    response = requests.post(url, files=files,data= data)

    print(response.text)

    if response.status_code == 200:
        print("File uploaded successfully.")
    # Handle the response as needed
    else:
        print("File upload failed.")