Rooni commited on
Commit
7f992e4
·
1 Parent(s): 2cbe2b0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -42
app.py CHANGED
@@ -1,43 +1,79 @@
1
- # app.py
2
- import os
3
  import gradio as gr
4
- import openai
5
-
6
- # Установка ключа API OpenAI
7
- openai.api_key = os.getenv("API_KEY")
8
-
9
- # Функция для генерации решения с использованием GPT-3.5-turbo
10
- def generate_solution(prompt, image):
11
- # Ваша логика обработки изображения и текста перед отправкой модели
12
- # Здесь должен быть ваш код для обработки изображения и текста
13
-
14
- # Пример: конкатенация текста и описания изображения
15
- input_text = f"{prompt} {image}"
16
-
17
- # Запрос к модели GPT-3.5-turbo
18
- response = openai.Completion.create(
19
- engine="text-davinci-003", # Выбор движка GPT
20
- prompt=input_text,
21
- max_tokens=150, # Максимальное количество токенов в ответе
22
- n=1, # Количество ответов, которые вы хотите получить
23
- )
24
-
25
- # Извлечение сгенерированного текста из ответа модели
26
- generated_text = response["choices"][0]["text"]
27
-
28
- return generated_text
29
-
30
- # Определение интерфейса Gradio
31
- iface = gr.Interface(
32
- fn=generate_solution,
33
- inputs=[
34
- gr.Textbox("Введите описание задачи", lines=5), # Используем параметр lines для многострочного текстового поля
35
- gr.Image(type="pil", label="Загрузите изображение"),
36
- ],
37
- outputs=gr.Textbox("Решение задачи"),
38
- live=True,
39
- theme="huggingface",
40
- )
41
-
42
- # Запуск приложения Gradio
43
- iface.launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import requests
3
+ import json
4
+ import os
5
+ from PIL import Image
6
+
7
+ def generate(description, image):
8
+ if image is None:
9
+ # No image uploaded, generate text only
10
+ return generate_text(description)
11
+
12
+ # Image uploaded, generate text with image caption
13
+ return generate_text_with_image(description, image)
14
+
15
+ def generate_text(description):
16
+ headers = {
17
+ 'Content-Type': 'application/json',
18
+ 'Authorization': f'Bearer {os.getenv("API_KEY")}'
19
+ }
20
+
21
+ payload = {
22
+ 'messages': [{'role': 'system', 'content': f'{description}'}],
23
+ 'max_tokens': 10000,
24
+ 'model': os.getenv("MODEL")
25
+ }
26
+
27
+ response = requests.post(os.getenv("BASE_URL"), headers=headers, json=payload)
28
+ data = json.loads(response.text)
29
+
30
+ if 'choices' in data and len(data['choices']) > 0:
31
+ command = data['choices'][0]['message']['content'].strip()
32
+ return command
33
+ elif 'error' in data:
34
+ error_message = data['error']['message']
35
+ return f'Ошибка: {error_message}'
36
+ else:
37
+ return f'Не удалось сгенерировать текст. {data}'
38
+
39
+ def generate_text_with_image(description, image):
40
+ # Preprocess image
41
+ image = Image.open(image).resize((224, 224))
42
+ image = image.convert('RGB')
43
+ image = image.tobytes()
44
+
45
+ # Convert image to base64 encoding
46
+ image_base64 = base64.b64encode(image).decode('utf-8')
47
+
48
+ headers = {
49
+ 'Content-Type': 'application/json',
50
+ 'Authorization': f'Bearer {os.getenv("API_KEY")}'
51
+ }
52
+
53
+ payload = {
54
+ 'messages': [{
55
+ 'role': 'system',
56
+ 'content': f'{description}',
57
+ 'image': image_base64
58
+ }],
59
+ 'max_tokens': 10000,
60
+ 'model': os.getenv("MODEL")
61
+ }
62
+
63
+ response = requests.post(os.getenv("BASE_URL"), headers=headers, json=payload)
64
+ data = json.loads(response.text)
65
+
66
+ if 'choices' in data and len(data['choices']) > 0:
67
+ command = data['choices'][0]['message']['content'].strip()
68
+ return command
69
+ elif 'error' in data:
70
+ error_message = data['error']['message']
71
+ return f'Ошибка: {error_message}'
72
+ else:
73
+ return f'Не удалось сгенерировать текст. {data}'
74
+
75
+ iface = gr.Interface(fn=generate, inputs=[
76
+ gr.Textbox(label="Запрос"),
77
+ gr.File(label="Изображение")
78
+ ], outputs=gr.Textbox(label="Ответ"), title="GPT")
79
+ iface.launch()