eliza555beth2002 commited on
Commit
02c2107
·
verified ·
1 Parent(s): 3901395

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -7
app.py CHANGED
@@ -1,18 +1,85 @@
1
  from llama_cpp import Llama
2
  import gradio as gr
 
3
 
4
- MODEL_URL = "https://huggingface.co/eliza555beth2002/DeepSeek-R1-Distill-Text2SQL-OneEpoch-GGUF-q4/blob/main/unsloth.Q4_K_M.gguf"
 
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  llm = Llama(
7
- model_path=MODEL_URL, # можно подставить ссылку на модель
8
  n_ctx=4096,
9
  n_threads=4,
10
- n_gpu_layers=50,
 
11
  )
12
 
 
13
  def text2sql(question):
14
- prompt = f"Создай SQL-запрос для вопроса: {question}"
15
- output = llm(prompt)
16
- return output['choices'][0]['text']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- gr.Interface(fn=text2sql, inputs="text", outputs="text", title="Text2SQL Demo").launch()
 
 
1
  from llama_cpp import Llama
2
  import gradio as gr
3
+ import os
4
 
5
+ # Локальный путь, куда будет скачана модель при запуске
6
+ MODEL_PATH = "unsloth.Q4_K_M.gguf"
7
 
8
+ # Если модели ещё нет — скачиваем
9
+ if not os.path.exists(MODEL_PATH):
10
+ import requests
11
+
12
+ url = "https://huggingface.co/eliza555beth2002/DeepSeek-R1-Distill-Text2SQL-OneEpoch-GGUF-q4/resolve/main/unsloth.Q4_K_M.gguf"
13
+ print("📥 Скачиваю модель из Hugging Face...")
14
+ r = requests.get(url, stream=True)
15
+ with open(MODEL_PATH, "wb") as f:
16
+ for chunk in r.iter_content(chunk_size=8192):
17
+ f.write(chunk)
18
+ print("Модель скачана успешно!")
19
+
20
+ # Загружаем модель Llama.cpp
21
  llm = Llama(
22
+ model_path=MODEL_PATH,
23
  n_ctx=4096,
24
  n_threads=4,
25
+ n_gpu_layers=0, # если на CPU — ставим 0
26
+ verbose=False,
27
  )
28
 
29
+ # Основная функция
30
  def text2sql(question):
31
+ schema = """
32
+ create table Authors(
33
+ AuthorID integer not null primary key check(AuthorID>0),
34
+ AuthorFIO varchar(40) not null
35
+ );
36
+ create table Books(
37
+ Cipher integer not null primary key check(Cipher>0),
38
+ BookName varchar(4000) not null,
39
+ BookTheme varchar(30) not null
40
+ check(BookTheme in('Любовь','Дружба','Смерть','Общественные проблемы','Внутренние противоречия')),
41
+ BookGenre varchar(15) not null
42
+ check(BookGenre in('Роман','Поэма','Рассказ','Пьеса','Эпопея','Драма'))
43
+ );
44
+ create table Wrote(
45
+ IDAuthor integer not null check(IDAuthor>0),
46
+ BookCipher integer not null check(BookCipher>0),
47
+ foreign key(IDAuthor) references Authors(AuthorID),
48
+ foreign key(BookCipher) references Books(Cipher),
49
+ primary key(IDAuthor, BookCipher)
50
+ );
51
+ """
52
+
53
+ prompt = f"""Ты — помощник, который преобразует естественный язык в SQL.
54
+ Используй приведённую схему таблиц.
55
+ Вопрос: {question}
56
+ Контекст базы данных:
57
+ {schema}
58
+
59
+ Ответь ТОЛЬКО SQL-запросом в формате:
60
+ ```sql
61
+ SELECT ...
62
+ ```"""
63
+
64
+ # Генерация
65
+ output = llm(
66
+ prompt,
67
+ max_tokens=512,
68
+ temperature=0.2,
69
+ stop=["```"],
70
+ )
71
+
72
+ text = output["choices"][0]["text"].strip()
73
+ return text
74
+
75
+ # Интерфейс Gradio
76
+ demo = gr.Interface(
77
+ fn=text2sql,
78
+ inputs=gr.Textbox(label="Введите вопрос на естественном языке"),
79
+ outputs=gr.Textbox(label="Сгенерированный SQL-запрос"),
80
+ title="🧠 DeepSeek Text2SQL Demo",
81
+ description="Модель DeepSeek-R1-Distill преобразует текст в SQL-запрос по заданной схеме."
82
+ )
83
 
84
+ if __name__ == "__main__":
85
+ demo.launch()