Jekyll2000 commited on
Commit
de8db4f
·
verified ·
1 Parent(s): dbb86b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -62
app.py CHANGED
@@ -1,63 +1,88 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
-
61
-
62
- if __name__ == "__main__":
63
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
3
+ import os
4
+ from langchain import PromptTemplate
5
+ from langchain import LLMChain
6
+ from langchain_together import Together
7
+ import re
8
+ import pdfplumber
9
+ # Set the API key with double quotes
10
+
11
+ os.environ['TOGETHER_API_KEY'] = "5653bbfbaf1f7c1438206f18e5dfc2f5992b8f0b6aa9796b0131ea454648ccde"
12
+
13
+ text = ""
14
+ max_pages = 16
15
+ with pdfplumber.open("/content/Ad_Mod_Daily_Sales.pdf") as pdf:
16
+ for i, page in enumerate(pdf.pages):
17
+ if i >= max_pages:
18
+ break
19
+ text += page.extract_text() + "\n"
20
+
21
+ def Bot(Questions):
22
+ chat_template = """
23
+ Based on the provided context: {text}
24
+ Please answer the following question: {Questions}
25
+ Only provide answers that are directly related to the context. If the question is unrelated, respond with "I don't know".
26
+ """
27
+ prompt = PromptTemplate(
28
+ input_variables=['text', 'Questions'],
29
+ template=chat_template
30
+ )
31
+ llama3 = Together(model="meta-llama/Llama-3-70b-chat-hf", max_tokens=250)
32
+ Generated_chat = LLMChain(llm=llama3, prompt=prompt)
33
+
34
+ try:
35
+ response = Generated_chat.invoke({
36
+ "text": text,
37
+ "Questions": Questions
38
+ })
39
+
40
+ response_text = response['text']
41
+
42
+ response_text = response_text.replace("assistant", "")
43
+
44
+ # Post-processing to handle repeated words and ensure completeness
45
+ words = response_text.split()
46
+ seen = set()
47
+ filtered_words = [word for word in words if word.lower() not in seen and not seen.add(word.lower())]
48
+ response_text = ' '.join(filtered_words)
49
+ response_text = response_text.strip() # Ensuring no extra spaces at the ends
50
+ if not response_text.endswith('.'):
51
+ response_text += '.'
52
+
53
+ return response_text
54
+ except Exception as e:
55
+ return f"Error in generating response: {e}"
56
+
57
+ def ChatBot(Questions):
58
+ greetings = ["hi", "hello", "hey", "greetings", "what's up", "howdy"]
59
+ # Check if the input question is a greeting
60
+ question_lower = Questions.lower().strip()
61
+ if question_lower in greetings or any(question_lower.startswith(greeting) for greeting in greetings):
62
+ return "Hello! How can I assist you with the document today?"
63
+ else:
64
+ response=Bot(Questions)
65
+ return response.translate(str.maketrans('', '', '\n'))
66
+ # text_embedding = model.encode(text, convert_to_tensor=True)
67
+ # statement_embedding = model.encode(statement, convert_to_tensor=True)
68
+
69
+ # # Compute the cosine similarity between the embeddings
70
+ # similarity = util.pytorch_cos_sim(text_embedding, statement_embedding)
71
+
72
+ # # Print the similarity score
73
+ # print(f"Cosine similarity: {similarity.item()}")
74
+
75
+ # # Define a threshold for considering the statement as related
76
+ # threshold = 0.7
77
+
78
+ # if similarity.item() > threshold:
79
+ # response=Bot(Questions)
80
+ # return response
81
+ # else:
82
+ # response="The statement is not related to the text."
83
+ # return response
84
+
85
+ iface = gr.Interface(fn=ChatBot, inputs="text", outputs="text", title="Chatbot")
86
+ iface.launch(debug=True)
87
+
88
+