asFrants commited on
Commit
f2f5171
1 Parent(s): e623457

add fastapi endpoint

Browse files
Files changed (5) hide show
  1. .gitignore +3 -0
  2. app.py +40 -12
  3. main.py +47 -0
  4. poetry.lock +14 -14
  5. pyproject.toml +2 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ __pycache__
2
+ .venv
3
+ flagged
app.py CHANGED
@@ -1,6 +1,7 @@
1
  import re
2
 
3
  import gradio as gr
 
4
  from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
5
  from loguru import logger
6
 
@@ -44,6 +45,21 @@ DEFAULT_RU_TEXT = """В результате взрыва на заправке,
44
  доноров для их пополнения на данный час тоже уже немало», — написало ведомство.
45
  """
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  class Summarizer():
48
  ru_summary_pipe: pipeline
49
  ru_sentiment_pipe: pipeline
@@ -96,21 +112,33 @@ class Summarizer():
96
  'ru': self.ru_sentiment_pipe,}
97
  return summary[lang], sentiment[lang]
98
 
99
- def summarize(self, text: str, lang: str = 'en') -> str:
100
- result = {}
101
- sum_pipe, sent_pipe = self.get_pipe(lang)
 
 
 
 
102
 
 
 
 
 
 
 
 
 
 
103
  response_summary = sum_pipe(text)
104
  logger.info(response_summary)
105
- result["summary"] = response_summary[0]["summary_text"]
106
-
107
  response_sentiment = sent_pipe(text)
108
  logger.info(response_sentiment)
109
- result["sentiment_label"] = response_sentiment[0]["label"]
110
- result["sentiment_score"] = response_sentiment[0]["score"]
111
-
112
- return f"Summary: {result['summary']}\n Sentiment: {result['sentiment_label']} ({result['sentiment_score']:.3f})"
113
-
 
114
 
115
  if __name__ == "__main__":
116
  pipe = Summarizer()
@@ -133,12 +161,12 @@ if __name__ == "__main__":
133
  ru_inbtn = gr.Button("Запустить")
134
 
135
  en_inbtn.click(
136
- pipe.summarize,
137
  [en_inputs, en_lang],
138
  [en_outputs],
139
  )
140
  ru_inbtn.click(
141
- pipe.summarize,
142
  [ru_inputs, ru_lang],
143
  [ru_outputs],
144
  )
 
1
  import re
2
 
3
  import gradio as gr
4
+ from pydantic import BaseModel
5
  from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
6
  from loguru import logger
7
 
 
45
  доноров для их пополнения на данный час тоже уже немало», — написало ведомство.
46
  """
47
 
48
+ class Request(BaseModel):
49
+ text: str
50
+
51
+
52
+ class Result(BaseModel):
53
+ sentiment_score: float
54
+ sentiment_label: str
55
+ summary: str
56
+
57
+ def to_str(self):
58
+ return f"Summary: {self.summary}\n Sentiment: {self.sentiment_label} ({self.sentiment_score:.3f})"
59
+
60
+ # class Response(BaseModel):
61
+ # results: List[Result] # list of Result objects
62
+
63
  class Summarizer():
64
  ru_summary_pipe: pipeline
65
  ru_sentiment_pipe: pipeline
 
112
  'ru': self.ru_sentiment_pipe,}
113
  return summary[lang], sentiment[lang]
114
 
115
+ # def summarize(self, text: str, lang: str = 'en') -> str:
116
+ # result = {}
117
+ # sum_pipe, sent_pipe = self.get_pipe(lang)
118
+
119
+ # response_summary = sum_pipe(text)
120
+ # logger.info(response_summary)
121
+ # result["summary"] = response_summary[0]["summary_text"]
122
 
123
+ # response_sentiment = sent_pipe(text)
124
+ # logger.info(response_sentiment)
125
+ # result["sentiment_label"] = response_sentiment[0]["label"]
126
+ # result["sentiment_score"] = response_sentiment[0]["score"]
127
+
128
+ # return f"Summary: {result['summary']}\n Sentiment: {result['sentiment_label']} ({result['sentiment_score']:.3f})"
129
+
130
+ def summarize(self, text: Request, lang: str = 'en') -> str:
131
+ sum_pipe, sent_pipe = self.get_pipe(lang)
132
  response_summary = sum_pipe(text)
133
  logger.info(response_summary)
 
 
134
  response_sentiment = sent_pipe(text)
135
  logger.info(response_sentiment)
136
+ result = Result(
137
+ summary=response_summary[0]["summary_text"],
138
+ sentiment_label=response_sentiment[0]["label"],
139
+ sentiment_score=response_sentiment[0]["score"],
140
+ )
141
+ return result
142
 
143
  if __name__ == "__main__":
144
  pipe = Summarizer()
 
161
  ru_inbtn = gr.Button("Запустить")
162
 
163
  en_inbtn.click(
164
+ pipe.summarize.to_str(),
165
  [en_inputs, en_lang],
166
  [en_outputs],
167
  )
168
  ru_inbtn.click(
169
+ pipe.summarize.to_str(),
170
  [ru_inputs, ru_lang],
171
  [ru_outputs],
172
  )
main.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from fastapi import FastAPI
3
+ from typing import List
4
+ from app import Summarizer, Request, Result
5
+ from app import EN_SENTIMENT_MODEL, EN_SUMMARY_MODEL, RU_SENTIMENT_MODEL, RU_SUMMARY_MODEL
6
+ from app import DEFAULT_EN_TEXT, DEFAULT_RU_TEXT
7
+
8
+ app = FastAPI()
9
+ pipe = Summarizer()
10
+
11
+
12
+ @app.post("/summ_ru", response_model=Result)
13
+ async def ru_summ_api(request: Request):
14
+ results = pipe.summarize(request.text)
15
+ return results
16
+
17
+
18
+ if __name__ == "__main__":
19
+
20
+ with gr.Blocks() as demo:
21
+ with gr.Row():
22
+ with gr.Column(scale=2, min_width=600):
23
+ en_sum_description=gr.Markdown(value=f"Model for Summary: {EN_SUMMARY_MODEL}")
24
+ en_sent_description=gr.Markdown(value=f"Model for Sentiment: {EN_SENTIMENT_MODEL}")
25
+ en_inputs=gr.Textbox(label="en_input", lines=5, value=DEFAULT_EN_TEXT, placeholder=DEFAULT_EN_TEXT)
26
+ en_lang=gr.Textbox(value='en',visible=False)
27
+ en_outputs=gr.Textbox(label="en_output", lines=5, placeholder="Summary and Sentiment would be here...")
28
+ en_inbtn = gr.Button("Proceed")
29
+ with gr.Column(scale=2, min_width=600):
30
+ ru_sum_description=gr.Markdown(value=f"Model for Summary: {RU_SUMMARY_MODEL}")
31
+ ru_sent_description=gr.Markdown(value=f"Model for Sentiment: {RU_SENTIMENT_MODEL}")
32
+ ru_inputs=gr.Textbox(label="ru_input", lines=5, value=DEFAULT_RU_TEXT, placeholder=DEFAULT_RU_TEXT)
33
+ ru_lang=gr.Textbox(value='ru',visible=False)
34
+ ru_outputs=gr.Textbox(label="ru_output", lines=5, placeholder="Здесь будет обобщение и эмоциональный окрас текста...")
35
+ ru_inbtn = gr.Button("Запустить")
36
+
37
+ en_inbtn.click(
38
+ pipe.summarize.to_str(),
39
+ [en_inputs, en_lang],
40
+ [en_outputs],
41
+ )
42
+ ru_inbtn.click(
43
+ pipe.summarize.to_str(),
44
+ [ru_inputs, ru_lang],
45
+ [ru_outputs],
46
+ )
47
+ demo.launch(show_api=False)
poetry.lock CHANGED
@@ -327,20 +327,20 @@ test = ["pytest (>=6)"]
327
 
328
  [[package]]
329
  name = "fastapi"
330
- version = "0.103.0"
331
  description = "FastAPI framework, high performance, easy to learn, fast to code, ready for production"
332
  category = "main"
333
  optional = false
334
- python-versions = ">=3.7"
335
  files = [
336
- {file = "fastapi-0.103.0-py3-none-any.whl", hash = "sha256:61ab72c6c281205dd0cbaccf503e829a37e0be108d965ac223779a8479243665"},
337
- {file = "fastapi-0.103.0.tar.gz", hash = "sha256:4166732f5ddf61c33e9fa4664f73780872511e0598d4d5434b1816dc1e6d9421"},
338
  ]
339
 
340
  [package.dependencies]
341
  pydantic = ">=1.7.4,<1.8 || >1.8,<1.8.1 || >1.8.1,<2.0.0 || >2.0.0,<2.0.1 || >2.0.1,<2.1.0 || >2.1.0,<3.0.0"
342
- starlette = ">=0.27.0,<0.28.0"
343
- typing-extensions = ">=4.5.0"
344
 
345
  [package.extras]
346
  all = ["email-validator (>=2.0.0)", "httpx (>=0.23.0)", "itsdangerous (>=1.1.0)", "jinja2 (>=2.11.2)", "orjson (>=3.2.1)", "pydantic-extra-types (>=2.0.0)", "pydantic-settings (>=2.0.0)", "python-multipart (>=0.0.5)", "pyyaml (>=5.3.1)", "ujson (>=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0)", "uvicorn[standard] (>=0.12.0)"]
@@ -2158,14 +2158,14 @@ files = [
2158
 
2159
  [[package]]
2160
  name = "starlette"
2161
- version = "0.27.0"
2162
  description = "The little ASGI library that shines."
2163
  category = "main"
2164
  optional = false
2165
- python-versions = ">=3.7"
2166
  files = [
2167
- {file = "starlette-0.27.0-py3-none-any.whl", hash = "sha256:918416370e846586541235ccd38a474c08b80443ed31c578a418e2209b3eef91"},
2168
- {file = "starlette-0.27.0.tar.gz", hash = "sha256:6a6b0d042acb8d469a01eba54e9cda6cbd24ac602c4cd016723117d6a7e73b75"},
2169
  ]
2170
 
2171
  [package.dependencies]
@@ -2552,14 +2552,14 @@ zstd = ["zstandard (>=0.18.0)"]
2552
 
2553
  [[package]]
2554
  name = "uvicorn"
2555
- version = "0.25.0"
2556
  description = "The lightning-fast ASGI server."
2557
  category = "main"
2558
  optional = false
2559
  python-versions = ">=3.8"
2560
  files = [
2561
- {file = "uvicorn-0.25.0-py3-none-any.whl", hash = "sha256:ce107f5d9bd02b4636001a77a4e74aab5e1e2b146868ebbad565237145af444c"},
2562
- {file = "uvicorn-0.25.0.tar.gz", hash = "sha256:6dddbad1d7ee0f5140aba5ec138ddc9612c5109399903828b4874c9937f009c2"},
2563
  ]
2564
 
2565
  [package.dependencies]
@@ -2683,4 +2683,4 @@ dev = ["black (>=19.3b0)", "pytest (>=4.6.2)"]
2683
  [metadata]
2684
  lock-version = "2.0"
2685
  python-versions = "^3.10"
2686
- content-hash = "baa66896f43ca309c23f1dc2f6e6902a89e532d449410ecaa4bed5ddeca83a7b"
 
327
 
328
  [[package]]
329
  name = "fastapi"
330
+ version = "0.109.0"
331
  description = "FastAPI framework, high performance, easy to learn, fast to code, ready for production"
332
  category = "main"
333
  optional = false
334
+ python-versions = ">=3.8"
335
  files = [
336
+ {file = "fastapi-0.109.0-py3-none-any.whl", hash = "sha256:8c77515984cd8e8cfeb58364f8cc7a28f0692088475e2614f7bf03275eba9093"},
337
+ {file = "fastapi-0.109.0.tar.gz", hash = "sha256:b978095b9ee01a5cf49b19f4bc1ac9b8ca83aa076e770ef8fd9af09a2b88d191"},
338
  ]
339
 
340
  [package.dependencies]
341
  pydantic = ">=1.7.4,<1.8 || >1.8,<1.8.1 || >1.8.1,<2.0.0 || >2.0.0,<2.0.1 || >2.0.1,<2.1.0 || >2.1.0,<3.0.0"
342
+ starlette = ">=0.35.0,<0.36.0"
343
+ typing-extensions = ">=4.8.0"
344
 
345
  [package.extras]
346
  all = ["email-validator (>=2.0.0)", "httpx (>=0.23.0)", "itsdangerous (>=1.1.0)", "jinja2 (>=2.11.2)", "orjson (>=3.2.1)", "pydantic-extra-types (>=2.0.0)", "pydantic-settings (>=2.0.0)", "python-multipart (>=0.0.5)", "pyyaml (>=5.3.1)", "ujson (>=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0)", "uvicorn[standard] (>=0.12.0)"]
 
2158
 
2159
  [[package]]
2160
  name = "starlette"
2161
+ version = "0.35.1"
2162
  description = "The little ASGI library that shines."
2163
  category = "main"
2164
  optional = false
2165
+ python-versions = ">=3.8"
2166
  files = [
2167
+ {file = "starlette-0.35.1-py3-none-any.whl", hash = "sha256:50bbbda9baa098e361f398fda0928062abbaf1f54f4fadcbe17c092a01eb9a25"},
2168
+ {file = "starlette-0.35.1.tar.gz", hash = "sha256:3e2639dac3520e4f58734ed22553f950d3f3cb1001cd2eaac4d57e8cdc5f66bc"},
2169
  ]
2170
 
2171
  [package.dependencies]
 
2552
 
2553
  [[package]]
2554
  name = "uvicorn"
2555
+ version = "0.27.0"
2556
  description = "The lightning-fast ASGI server."
2557
  category = "main"
2558
  optional = false
2559
  python-versions = ">=3.8"
2560
  files = [
2561
+ {file = "uvicorn-0.27.0-py3-none-any.whl", hash = "sha256:890b00f6c537d58695d3bb1f28e23db9d9e7a17cbcc76d7457c499935f933e24"},
2562
+ {file = "uvicorn-0.27.0.tar.gz", hash = "sha256:c855578045d45625fd027367f7653d249f7c49f9361ba15cf9624186b26b8eb6"},
2563
  ]
2564
 
2565
  [package.dependencies]
 
2683
  [metadata]
2684
  lock-version = "2.0"
2685
  python-versions = "^3.10"
2686
+ content-hash = "a0a8f5d7bbfd3d08c83e048ee2f8e18cf31729338afa2484b5f817c387457622"
pyproject.toml CHANGED
@@ -16,6 +16,8 @@ pretrainedmodels = "^0.7.4"
16
  sentencepiece = "^0.1.99"
17
  protobuf = "^4.25.1"
18
  loguru = "^0.7.2"
 
 
19
 
20
 
21
  [tool.poetry.group.dev.dependencies]
 
16
  sentencepiece = "^0.1.99"
17
  protobuf = "^4.25.1"
18
  loguru = "^0.7.2"
19
+ fastapi = "^0.109.0"
20
+ uvicorn = "^0.27.0"
21
 
22
 
23
  [tool.poetry.group.dev.dependencies]