freddyaboulton HF staff commited on
Commit
3659338
β€’
1 Parent(s): 142c8a2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -0
app.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+
4
+ if gr.NO_RELOAD:
5
+ client = InferenceClient()
6
+
7
+ system_message = {
8
+ "role": "system",
9
+ "content": """
10
+ You are a helpful assistant.
11
+ You will be given a question and a set of answers along with a confidence score between 0 and 1 for each answer.
12
+ You job is to turn this information into a short, coherent response.
13
+
14
+ For example:
15
+ Question: "Who is being invoiced?", answer: {"answer": "John Doe", "confidence": 0.98}
16
+
17
+ You should respond with something like:
18
+ With a high degree of confidence, I can say John Doe is being invoiced.
19
+
20
+ Question: "What is the invoice total?", answer: [{"answer": "154.08", "confidence": 0.75}, {"answer": "155", "confidence": 0.25}
21
+
22
+ You should respond with something like:
23
+ I belive the invoice total is $154.08 thought it can also be $155.
24
+ """}
25
+
26
+ def chat_fn(multimodal_message):
27
+ question = multimodal_message["text"]
28
+ image = multimodal_message["files"][0]
29
+
30
+ answer = client.document_question_answering(image=image, question=question, model="impira/layoutlm-document-qa")
31
+
32
+ answer = [{"answer": a.answer, "confidence": a.score} for a in answer]
33
+
34
+ user_message = {"role": "user", "content": f"Question: {question}, answer: {answer}"}
35
+
36
+ message = ""
37
+ for token in client.chat_completion(messages=[system_message, user_message],
38
+ max_tokens=100,
39
+ stream=True,
40
+ model="HuggingFaceH4/zephyr-7b-beta"):
41
+ if token.choices[0].finish_reason is not None:
42
+ continue
43
+ message += token.choices[0].delta.content
44
+ yield message
45
+
46
+ with gr.Blocks() as demo:
47
+ gr.Markdown("# πŸ” Document Analyzer Chatbot")
48
+ response = gr.Textbox(lines=5, label="Response")
49
+ chat = gr.MultimodalTextbox(file_types=["image"], interactive=True,
50
+ show_label=False, placeholder="Upload a document image by blicking '+' and ask a question.")
51
+ chat.submit(chat_fn, inputs=chat, outputs=response)
52
+
53
+ if __name__ == "__main__":
54
+ demo.launch()