Spaces:
Runtime error
Runtime error
Update main.py
Browse files35 unmodified lines363738394041424344454647484950515253545556575859606162636465666756 unmodified lines12412512612712812913013 unmodified lines1441451461471481491501511521531541551568 unmodified lines1651661671681691701714 unmodified lines1761771781791801811824 unmodified lines1871881891901911921932 unmodified lines19619719819920020120268 unmodified lines27127227327427527627727835 unmodified linesmax_new_tokens: int = 2000top_p: float = 0.95repetition_penalty: float = 1.0class InputDataAsync(InputData):NumeroGenerazioni: int = 1StringaSplit: str = '********'NumeroCaratteriSplitInstruction: int = 30000class PostSpazio(BaseModel):nomeSpazio: strinput: str = ''api_name: str = "/chat"#--------------------------------------------------- Generazione TESTO ------------------------------------------------------@app.post("/Genera")def generate_text(request: Request, input_data: InputData):temperature = input_data.temperaturemax_new_tokens = input_data.max_new_tokenstop_p = input_data.top_prepetition_penalty = input_data.repetition_penaltyinput_text = generate_input_text(input_data)max_new_tokens = min(max_new_tokens, 29500 - len(input_text))print(f"{datetime.now()} - Input Text: {input_text}")history = []generated_response = generate(input_text, history, temperature, max_new_tokens, top_p, repetition_penalty)print(f"{datetime.now()} - Response Text: {generated_response}")return {"response": generated_response}def generate_input_text(input_data):if input_data.instruction.startswith("http"):try:56 unmodified lines#--------------------------------------------------- Generazione TESTO ASYNC ------------------------------------------------------@app.post("/GeneraAsync")def generate_textAsync(request: Request, input_data: InputDataAsync):print(input_data.input)result_data = asyncio.run(GeneraTestoAsync("https://matteoscript-fastapi.hf.space/Genera", input_data))return {"response": result_data}13 unmodified linesprint(result_data)return result_dataexcept (asyncio.TimeoutError, aiohttp.ClientError, requests.exceptions.HTTPError) as e:print(f"Error: {e}.")if isinstance(e, (asyncio.TimeoutError, requests.exceptions.HTTPError)) and e.response.status in [502, 504]:print("Skipping retries for this error.")breakprint("Retrying...")await asyncio.sleep(1)raise Exception("Max retries reached or skipping retries. Unable to make the request.")8 unmodified linesresult_data = await response.json()except aiohttp.ContentTypeError:result_data = await response.text()print(result_data)return result_dataasync def CreaListaInput(input_data):4 unmodified linesinput_data.instruction = resp.textexcept requests.exceptions.RequestException as e:input_data.instruction = ""print(input_data.instruction)try:lista_dizionari = []nuova_lista_dizionari = []4 unmodified linesnuova_lista_dizionari = DividiInstructionText(input_data)except json.JSONDecodeError:nuova_lista_dizionari = DividiInstructionText(input_data)print(nuova_lista_dizionari)return nuova_lista_dizionaridef split_at_space_or_dot(input_string, length):2 unmodified linesvalid_positions = [pos for pos in positions if pos >= 0]lastpos = max(valid_positions) if valid_positions else lengthindice_divisione = int(lastpos)print(indice_divisione)return indice_divisione + 1def DividiInstructionJSON(lista_dizionari, input_data):68 unmodified linestasks = []ListaInput = await CreaListaInput(input_data)for data in ListaInput:print('------------------------------------------------------------------------------------------------')print(data)tasks.extend([make_request(session, token, data, url) for _ in range(input_data.NumeroGenerazioni)])return await asyncio.gather(*tasks)35 unmodified lines36373839404142434445464748495051525354555657585960616263646566676869707172737475767756 unmodified lines13413513613713813913 unmodified lines1531541551561571581591601611628 unmodified lines1711721731741751764 unmodified lines1811821831841851864 unmodified lines1911921931941951962 unmodified lines19920020120220320468 unmodified lines27327427527627727827935 unmodified linesmax_new_tokens: int = 2000top_p: float = 0.95repetition_penalty: float = 1.0Async: bool = falseNumeroGenerazioni: int = 1StringaSplit: str = '********'NumeroCaratteriSplitInstruction: int = 30000class InputDataAsync(InputData):class PostSpazio(BaseModel):nomeSpazio: strinput: str = ''api_name: str = "/chat"def LoggaTesto(type, text)print(f"{datetime.now()}: ----------------------------------| {type} |-----------------------------------\n{text}\n\n")#--------------------------------------------------- Generazione TESTO ------------------------------------------------------@app.post("/Genera")def generate_text(request: Request, input_data: InputData):LoggaTesto("INPUT", input_data.input)if not input_data.Async:temperature = input_data.temperaturemax_new_tokens = input_data.max_new_tokenstop_p = input_data.top_prepetition_penalty = input_data.repetition_penaltyinput_text = generate_input_text(input_data)max_new_tokens = min(max_new_tokens, 29500 - len(input_text))history = []generated_response = generate(input_text, history, temperature, max_new_tokens, top_p, repetition_penalty)LoggaTesto("RISPOSTA SINCRONA", generated_response)return {"response": generated_response}else:input_data.Async = falseresult_data = asyncio.run(GeneraTestoAsync("https://matteoscript-fastapi.hf.space/Genera", input_data))LoggaTesto("RISPOSTA ASINCRONA FINALE", result_data)return {"response": result_data}def generate_input_text(input_data):if input_data.instruction.startswith("http"):try:56 unmodified lines#--------------------------------------------------- Generazione TESTO ASYNC ------------------------------------------------------@app.post("/GeneraAsync")def generate_textAsync(request: Request, input_data: InputDataAsync):result_data = asyncio.run(GeneraTestoAsync("https://matteoscript-fastapi.hf.space/Genera", input_data))return {"response": result_data}13 unmodified linesprint(result_data)return result_dataexcept (asyncio.TimeoutError, aiohttp.ClientError, requests.exceptions.HTTPError) as e:LoggaTesto("ERRORE ASYNC", {e})if isinstance(e, (asyncio.TimeoutError, requests.exceptions.HTTPError)) and e.response.status in [502, 504]:breakawait asyncio.sleep(1)raise Exception("Max retries reached or skipping retries. Unable to make the request.")8 unmodified linesresult_data = await response.json()except aiohttp.ContentTypeError:result_data = await response.text()return result_dataasync def CreaListaInput(input_data):4 unmodified linesinput_data.instruction = resp.textexcept requests.exceptions.RequestException as e:input_data.instruction = ""try:lista_dizionari = []nuova_lista_dizionari = []4 unmodified linesnuova_lista_dizionari = DividiInstructionText(input_data)except json.JSONDecodeError:nuova_lista_dizionari = DividiInstructionText(input_data)return nuova_lista_dizionaridef split_at_space_or_dot(input_string, length):2 unmodified linesvalid_positions = [pos for pos in positions if pos >= 0]lastpos = max(valid_positions) if valid_positions else lengthindice_divisione = int(lastpos)return indice_divisione + 1def DividiInstructionJSON(lista_dizionari, input_data):68 unmodified linestasks = []ListaInput = await CreaListaInput(input_data)for data in ListaInput:LoggaTesto("RICHIESTA ASINCRONA", data)tasks.extend([make_request(session, token, data, url) for _ in range(input_data.NumeroGenerazioni)])return await asyncio.gather(*tasks)
main.py+26-25