'Task'
Please fix my C# script I'm trying to write an inference into my uvicorn script

'My C# Code'
public async Task WhisperTurbo()
{
    using var httpClient = new HttpClient();
    using var multipart = new MultipartFormDataContent();

    byte[] fileData = await File.ReadAllBytesAsync(outputFilePath);
    var fileContent = new ByteArrayContent(fileData);
    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
    multipart.Add(fileContent, "audio_file", Path.GetFileName(outputFilePath));

    multipart.Add(new StringContent(task), "task");

    string url = "http://localhost:21421/transcribe";
    HttpResponseMessage response = await httpClient.PostAsync(url, multipart);
    response.EnsureSuccessStatusCode();

    string jsonResponse = await response.Content.ReadAsStringAsync();

    // Simple extraction of "text" from JSON response
    var startIndex = jsonResponse.IndexOf("\"text\":\"") + 8;
    var endIndex = jsonResponse.LastIndexOf("\"");
    if (startIndex < 8 || endIndex < startIndex)
    {
        Console.WriteLine("Unexpected response: " + jsonResponse);
        return;
    }

    string transcript = jsonResponse.Substring(startIndex, endIndex - startIndex);
    transcript = System.Text.RegularExpressions.Regex.Unescape(transcript);

    Console.WriteLine("Transcription result:");
    Console.WriteLine(transcript);
}

'My Uvicorn Server's Code'
import io
from fastapi import FastAPI, File, UploadFile, Form, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from transformers import pipeline
import torch
import soundfile as sf

app = FastAPI(
    title="Fast Whisper Turbo HTTP API",
    description="Ultra-fast Whisper V3 Turbo inference HTTP server"
)

# Allow CORS for testing from WinForms if needed
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"], 
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

print("Loading model... This may take some time.")
pipe = pipeline(
    "automatic-speech-recognition",
    model="openai/whisper-large-v3-turbo",
    torch_dtype=torch.float16,
    device="cuda:0",
    model_kwargs={"attn_implementation": "flash_attention_2"},
)
print("Model loaded.")

@app.post("/transcribe")
async def transcribe(
    audio_file: UploadFile = File(...),
    task: str = Form("transcribe")
):
    """
    Transcribe or translate audio file.

    - audio_file: audio file (wav, mp3, etc)
    - task: "transcribe" or "translate"
    """
    if task not in ("transcribe", "translate"):
        raise HTTPException(status_code=400, detail="Invalid task parameter")

    contents = await audio_file.read()

    # Optionally ensure audio is loaded in a compatible format
    # The pipeline accepts filename or numpy array. We'll use numpy array.
    try:
        audio_bytes = io.BytesIO(contents)
        waveform, sample_rate = sf.read(audio_bytes)
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Could not read audio file: {e}")

    # Perform inference
    print(f"Starting {task} task for {audio_file.filename}")
    outputs = pipe(
        waveform,
        chunk_length_s=30,
        batch_size=128,
        generate_kwargs={"task": task},
        return_timestamps=False,
    )
    print("Finished transcription task")

    return {"text": outputs['text'].strip()}