Spaces:
Runtime error
Runtime error
File size: 15,325 Bytes
a231872 510d2c1 a231872 8243283 5a68da9 a231872 d83c996 a231872 d152ed5 d83c996 5a68da9 d152ed5 5a68da9 d83c996 d152ed5 5a68da9 a231872 d83c996 a231872 5a68da9 a231872 9598ec0 a231872 9598ec0 a231872 510d2c1 5a68da9 510d2c1 d83c996 510d2c1 d83c996 8243283 d83c996 8243283 510d2c1 8243283 d152ed5 8243283 d152ed5 8243283 d83c996 |
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 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 |
from django.http import JsonResponse
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import serializers
from .engine import execute_prompt, bundle_function, propose_recipes, compute_reduced_prices
from rest_framework.views import APIView
from mistralai import Mistral
import os
import base64
import json
import requests
from openai import OpenAI
from ollama import Client
from django.http import FileResponse
import io
class TTSView(APIView):
def post(self, request, format=None):
# Define the API endpoint
# Define the URL for the TTS API
url = 'http://localhost:5002/api/tts'
# Define the multiline text
text = "This is the first line"
# Prepare the parameters for the GET request
params = {
'text': text
}
# Make the GET request
response = requests.get(url, params=params)
# Check if the request was successful
if response.status_code == 200:
# Save the audio response as a WAV file
# Create a file-like object with the audio data
audio_data = io.BytesIO(response.content)
# Return the audio file as a response
return FileResponse(audio_data, as_attachment=True, filename='audio_output.wav')
else:
return Response({"error": "Failed to synthesize speech"}, status=response.status_code)
class SpeechASRView(APIView):
def post(self, request, format=None):
try:
data = request.data
##prompt = data['prompt']
audio = data['audio']
client = OpenAI(api_key="cant-be-empty", base_url="http://localhost:11800/v1/")
#filename= '/home/gaganyatri/Music/test1.flac'
audio_bytes = audio.read()
#audio_file = open(filename, "rb")
transcript = client.audio.transcriptions.create(
model="Systran/faster-distil-whisper-small.en", file=audio_bytes
)
#print(transcript.text)
voice_content = transcript.text
return Response({"response": voice_content})
except Exception as e:
print(f"An error occurred: {e}")
return Response({'error': 'Something went wrong'}, status=500)
class SpeechToSpeechView(APIView):
def post(self, request, format=None):
try:
data = request.data
##prompt = data['prompt']
audio = data['audio']
client = OpenAI(api_key="cant-be-empty", base_url="http://localhost:11800/v1/")
#filename= '/home/gaganyatri/Music/test1.flac'
audio_bytes = audio.read()
#audio_file = open(filename, "rb")
transcript = client.audio.transcriptions.create(
model="Systran/faster-distil-whisper-small.en", file=audio_bytes
)
#print(transcript.text)
voice_content = transcript.text
#content = 'audio recieved'
system_prompt = "Please summarize the following prompt into a concise and clear statement:"
model = "mistral-nemo:latest"
client = Client(host='http://localhost:11434')
response = client.chat(
model=model,
messages=[
{
"role": "system",
"content": system_prompt
},
{
"role": "user",
"content": voice_content,
}
],
)
# Extract the model's response about the image
response_text = response['message']['content'].strip()
url = 'http://localhost:5002/api/tts'
# Define the multiline text
#text = "This is the first line"
# Prepare the parameters for the GET request
params = {
'text': response_text
}
# Make the GET request
response = requests.get(url, params=params)
# Check if the request was successful
if response.status_code == 200:
# Save the audio response as a WAV file
# Create a file-like object with the audio data
audio_data = io.BytesIO(response.content)
# Return the audio file as a response
return FileResponse(audio_data, as_attachment=True, filename='audio_output.wav')
else:
return Response({"error": "Failed to synthesize speech"}, status=response.status_code)
except Exception as e:
print(f"An error occurred: {e}")
return Response({'error': 'Something went wrong'}, status=500)
class SpeechLLMView(APIView):
def post(self, request, format=None):
try:
data = request.data
##prompt = data['prompt']
audio = data['audio']
client = OpenAI(api_key="cant-be-empty", base_url="http://localhost:11800/v1/")
#filename= '/home/gaganyatri/Music/test1.flac'
audio_bytes = audio.read()
#audio_file = open(filename, "rb")
transcript = client.audio.transcriptions.create(
model="Systran/faster-distil-whisper-small.en", file=audio_bytes
)
#print(transcript.text)
voice_content = transcript.text
#content = 'audio recieved'
model = "mistral-nemo:latest"
client = Client(host='http://localhost:11434')
response = client.chat(
model=model,
messages=[{
"role": "user",
"content": voice_content,
}],
)
# Extract the model's response about the image
response_text = response['message']['content'].strip()
return Response({"response": response_text})
except Exception as e:
print(f"An error occurred: {e}")
return Response({'error': 'Something went wrong'}, status=500)
class TranslateLLMView(APIView):
def post(self, request, format=None):
try:
data = request.data
prompt = data['messages'][0]['prompt']
# Specify model
source_language = data['sourceLanguage']
target_language = data['targetLanguage']
#model = data['model']
# Define the messages for the chat
api_key=os.getenv("SARVAM_API_KEY", "")
url = "https://api.sarvam.ai/translate"
payload = {
"input": prompt,
"source_language_code": source_language,
"target_language_code": target_language,
"speaker_gender": "Male",
"mode": "formal",
"model": "mayura:v1",
"enable_preprocessing": True
}
headers = {"Content-Type": "application/json",
'API-Subscription-Key': f"{api_key}"
}
response = requests.request("POST", url, json=payload, headers=headers)
content = response.text
#print(chat_response.choices[0].message.content)
# Return the content of the response
return Response({"response": content})
except Exception as e:
print(f"An error occurred: {e}")
return Response({'error': 'Something went wrong'}, status=500)
class TextLLMView(APIView):
def post(self, request, format=None):
try:
data = request.data
isOnline = data['isOnline']
print(isOnline)
prompt = data['messages'][0]['prompt']
# Specify model
#model = "pixtral-12b-2409"
model = data['model']
# Define the messages for the chat
messages = [
{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
}
]
}
]
if(isOnline):
api_key = os.environ["MISTRAL_API_KEY"]
# Initialize the Mistral client
client = Mistral(api_key=api_key)
# Get the chat response
chat_response = client.chat.complete(
model=model,
messages=messages
)
content = chat_response.choices[0].message.content
else:
content = "helloWorld"
#print(chat_response.choices[0].message.content)
# Return the content of the response
return Response({"response": content})
except Exception as e:
print(f"An error occurred: {e}")
return Response({'error': 'Something went wrong'}, status=500)
class IndicLLMView(APIView):
def post(self, request, format=None):
try:
data = request.data
isOnline = data['isOnline']
print(isOnline)
prompt = data['messages'][0]['prompt']
# Specify model
#model = "pixtral-12b-2409"
model = data['model']
# Define the messages for the chat
client = Client(host='http://localhost:11434')
response = client.chat(
model=model,
messages=[{
"role": "user",
"content": prompt,
}],
)
# Extract the model's response about the image
response_text = response['message']['content'].strip()
#print(chat_response.choices[0].message.content)
# Return the content of the response
return Response({"response": response_text})
except Exception as e:
print(f"An error occurred: {e}")
return Response({'error': 'Something went wrong'}, status=500)
@api_view(['GET'])
def recipe_generate_route(request):
isLocal = False
try:
json_objs = compute_reduced_prices()
obj= json.loads(json_objs)
bundle_articles = bundle_function(obj[:10])
result = execute_prompt(propose_recipes(bundle_articles), False)
except (FileNotFoundError, json.JSONDecodeError) as e:
return Response({'error': str(e)}, status=500)
except Exception as e:
print(f"An error occurred: {e}")
return Response({'error': 'Something went wrong'}, status=500)
return Response(result)
class LlamaVisionView(APIView):
def post(self, request, format=None):
try:
data = request.data
image_data = (data['messages'][0]['image'][0])
prompt = data['messages'][0]['prompt']
# Specify model
#model = "pixtral-12b-2409"
model = data['model']
# Define the messages for the chat
# Define the messages for the chat
client = Client(host='http://localhost:21434')
response = client.chat(
model="x/llama3.2-vision:latest",
messages=[{
"role": "user",
"content": prompt,
"images": [image_data]
}],
)
# Extract the model's response about the image
response_text = response['message']['content'].strip()
print(response_text)
content = response_text
#print(chat_response.choices[0].message.content)
# Return the content of the response
return Response({"response": content})
except Exception as e:
print(f"An error occurred: {e}")
return Response({'error': 'Something went wrong'}, status=500)
class VisionLLMView(APIView):
def post(self, request, format=None):
try:
data = request.data
api_key = os.environ["MISTRAL_API_KEY"]
# Initialize the Mistral client
client = Mistral(api_key=api_key)
image_data = (data['messages'][0]['image'][0])
prompt = data['messages'][0]['prompt']
# Specify model
#model = "pixtral-12b-2409"
model = data['model']
# Define the messages for the chat
messages = [
{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{image_data}"
}
]
}
]
# Get the chat response
chat_response = client.chat.complete(
model=model,
messages=messages
)
content = chat_response.choices[0].message.content
#print(chat_response.choices[0].message.content)
# Return the content of the response
return Response({"response": content})
except Exception as e:
print(f"An error occurred: {e}")
return Response({'error': 'Something went wrong'}, status=500)
class NIMVisionLLMView(APIView):
def post(self, request, format=None):
try:
invoke_url = "https://ai.api.nvidia.com/v1/gr/meta/llama-3.2-11b-vision-instruct/chat/completions"
stream = False
api_key = os.environ["NIM_API_KEY"]
data = request.data
model = data['model']
print(model)
image_data = (data['messages'][0]['image'][0])
prompt = data['messages'][0]['prompt']
headers = {
"Authorization": f"Bearer {api_key}",
"Accept": "text/event-stream" if stream else "application/json"
}
payload = {
"model": model,
"messages": [
{
"role": "user",
"content": f'{prompt} <img src="data:image/png;base64,{image_data}" />'
}
],
"max_tokens": 512,
"temperature": 1.00,
"top_p": 1.00,
"stream": stream
}
response = requests.post(invoke_url, headers=headers, json=payload)
if stream:
for line in response.iter_lines():
if line:
#print(line.decode("utf-8"))
data = line.decode("utf-8")
#content = json.loads(data)['choices'][0]['delta'].get('content', '')
else:
#print(response.json())
data = response.json()
content = data['choices'][0]['message']['content']
#print(content)
return Response({"response": content})
except Exception as e: # Added general exception handling
print(f"An error occurred: {e}")
return Response({'error': 'Something went wrong'}, status=500)
|