Felguk commited on
Commit
2ad4f36
·
verified ·
1 Parent(s): fecb126

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -22
app.py CHANGED
@@ -1,33 +1,55 @@
1
  import gradio as gr
2
- from transformers import pipeline
 
3
 
4
- # Load a custom model (replace with your DeepSeek model)
5
- # Example: Using a Hugging Face model as a placeholder
6
- code_generator = pipeline("text-generation", model="deepseek-ai/deepseek-coder-1.3b-instruct") # Replace with your DeepSeek model
7
 
8
- # Function to generate code
 
 
 
 
9
  def generate_code(prompt, file_type):
10
  if file_type in ["Gradio", "Vercel", "Streamlit"]:
11
- # Handle platform-specific code generation
12
  prompt_with_file_type = f"Write a configuration or setup code for {file_type} to: {prompt}"
13
  else:
14
- # Handle programming language code generation
15
  prompt_with_file_type = f"Write a {file_type} code for: {prompt}"
16
 
17
- # Generate code using the custom model
18
- generated_code = code_generator(prompt_with_file_type, max_length=200, num_return_sequences=1)
19
- return generated_code[0]['generated_text']
 
 
 
 
 
 
 
 
 
20
 
21
- # Function to update code
22
  def update_code(existing_code, update_prompt):
23
- # Combine the existing code and the update prompt
24
  prompt_with_update = f"Rewrite the following code to: {update_prompt}\n\nExisting Code:\n{existing_code}"
25
 
26
- # Generate updated code using the custom model
27
- updated_code = code_generator(prompt_with_update, max_length=200, num_return_sequences=1)
28
- return updated_code[0]['generated_text']
 
 
 
 
 
 
 
 
29
 
30
- # Examples for the interface
31
  examples = [
32
  ["Write a function to calculate factorial", "Python"],
33
  ["Create a simple interface for a calculator", "Gradio"],
@@ -37,7 +59,7 @@ examples = [
37
  ["Create a responsive navbar", "HTML"],
38
  ]
39
 
40
- # Gradio interface
41
  with gr.Blocks(theme='Nymbo/Nymbo_Theme') as demo:
42
  gr.Markdown("# AI Code Generator with Update Feature")
43
  gr.Markdown("Enter a prompt and select the file type or platform to generate code. You can also update the generated code with a new prompt.")
@@ -50,27 +72,40 @@ with gr.Blocks(theme='Nymbo/Nymbo_Theme') as demo:
50
  value="Python"
51
  )
52
 
53
- output_code = gr.Textbox(label="Generated Code", lines=10, interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  generate_button = gr.Button("Generate Code")
56
  generate_button.click(fn=generate_code, inputs=[input_prompt, file_type], outputs=output_code)
57
 
58
- # Update Code Section
59
  with gr.Row():
60
  update_prompt = gr.Textbox(label="Update Prompt", placeholder="e.g., Add error handling to the code...")
61
  update_button = gr.Button("Update Code")
62
 
63
  update_button.click(fn=update_code, inputs=[output_code, update_prompt], outputs=output_code)
64
 
65
- # Add examples
66
  gr.Examples(
67
  examples=examples,
68
  inputs=[input_prompt, file_type],
69
  outputs=output_code,
70
  fn=generate_code,
71
- cache_examples=True, # Cache results for faster loading
72
  label="Click on an example to get started!"
73
  )
74
 
75
- # Launch the interface
76
  demo.launch()
 
1
  import gradio as gr
2
+ from transformers import AutoModelForCausalLM
3
+ import torch
4
 
5
+ # Загрузка модели DeepSeek-Coder-1.3b-instruct
6
+ model_name = "deepseek-ai/deepseek-coder-1.3b-instruct"
7
+ model = AutoModelForCausalLM.from_pretrained(model_name)
8
 
9
+ # Проверка доступности GPU
10
+ device = "cuda" if torch.cuda.is_available() else "cpu"
11
+ model.to(device)
12
+
13
+ # Функция для генерации кода
14
  def generate_code(prompt, file_type):
15
  if file_type in ["Gradio", "Vercel", "Streamlit"]:
16
+ # Генерация кода для платформ
17
  prompt_with_file_type = f"Write a configuration or setup code for {file_type} to: {prompt}"
18
  else:
19
+ # Генерация кода для языков программирования
20
  prompt_with_file_type = f"Write a {file_type} code for: {prompt}"
21
 
22
+ # Генерация кода с использованием модели
23
+ inputs = prompt_with_file_type # Передаем текст напрямую
24
+ outputs = model.generate(
25
+ inputs, # Модель должна поддерживать прямой ввод текста
26
+ max_length=200, # Ограничение длины вывода
27
+ num_return_sequences=1, # Один вариант ответа
28
+ temperature=0.7, # Контроль случайности
29
+ top_p=0.9, # Контроль разнообразия
30
+ )
31
+
32
+ # Возвращаем сгенерированный код
33
+ return outputs[0] # Предполагаем, что модель возвращает текст напрямую
34
 
35
+ # Функция для обновления кода
36
  def update_code(existing_code, update_prompt):
37
+ # Объединение существующего кода и нового запроса
38
  prompt_with_update = f"Rewrite the following code to: {update_prompt}\n\nExisting Code:\n{existing_code}"
39
 
40
+ # Генерация обновленного кода
41
+ outputs = model.generate(
42
+ prompt_with_update,
43
+ max_length=250, # Увеличен для обновления кода
44
+ num_return_sequences=1,
45
+ temperature=0.7,
46
+ top_p=0.9,
47
+ )
48
+
49
+ # Возвращаем обновленный код
50
+ return outputs[0]
51
 
52
+ # Примеры для интерфейса
53
  examples = [
54
  ["Write a function to calculate factorial", "Python"],
55
  ["Create a simple interface for a calculator", "Gradio"],
 
59
  ["Create a responsive navbar", "HTML"],
60
  ]
61
 
62
+ # Gradio интерфейс
63
  with gr.Blocks(theme='Nymbo/Nymbo_Theme') as demo:
64
  gr.Markdown("# AI Code Generator with Update Feature")
65
  gr.Markdown("Enter a prompt and select the file type or platform to generate code. You can also update the generated code with a new prompt.")
 
72
  value="Python"
73
  )
74
 
75
+ # Панель для кода с безлимитными строками
76
+ output_code = gr.Textbox(label="Generated Code", lines=None, interactive=False)
77
+
78
+ # Кнопка "Скопировать"
79
+ copy_button = gr.Button("Скопировать код")
80
+ copy_button.click(
81
+ None, # Не требует Python-функции
82
+ inputs=[output_code], # Входные данные — текст из output_code
83
+ outputs=None, # Нет выходных данных
84
+ js="""(text) => {
85
+ navigator.clipboard.writeText(text);
86
+ alert('Код скопирован в буфер обмена!');
87
+ }"""
88
+ )
89
 
90
  generate_button = gr.Button("Generate Code")
91
  generate_button.click(fn=generate_code, inputs=[input_prompt, file_type], outputs=output_code)
92
 
93
+ # Секция для обновления кода
94
  with gr.Row():
95
  update_prompt = gr.Textbox(label="Update Prompt", placeholder="e.g., Add error handling to the code...")
96
  update_button = gr.Button("Update Code")
97
 
98
  update_button.click(fn=update_code, inputs=[output_code, update_prompt], outputs=output_code)
99
 
100
+ # Добавление примеров
101
  gr.Examples(
102
  examples=examples,
103
  inputs=[input_prompt, file_type],
104
  outputs=output_code,
105
  fn=generate_code,
106
+ cache_examples=True, # Кэширование для ускорения
107
  label="Click on an example to get started!"
108
  )
109
 
110
+ # Запуск интерфейса
111
  demo.launch()