dzz5181 commited on
Commit
07794a3
β€’
1 Parent(s): 1657fc1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -63
app.py CHANGED
@@ -7,14 +7,23 @@ import spaces
7
  import torch
8
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
9
 
 
 
 
 
 
 
 
 
10
  MAX_MAX_NEW_TOKENS = 2048
11
  DEFAULT_MAX_NEW_TOKENS = 1024
12
  MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
13
 
14
  DESCRIPTION = """\
15
- # Llama-2 7B Chat
16
 
17
- This Space demonstrates model [Llama-2-7b-chat](https://huggingface.co/meta-llama/Llama-2-7b-chat) by Meta, a Llama 2 model with 7B parameters fine-tuned for chat instructions. Feel free to play with it, or duplicate to run generations without a queue! If you want to run your own service, you can also [deploy the model on Inference Endpoints](https://huggingface.co/inference-endpoints).
 
18
 
19
  πŸ”Ž For more details about the Llama 2 family of models and how to use them with `transformers`, take a look [at our blog post](https://huggingface.co/blog/llama2).
20
 
@@ -32,13 +41,32 @@ this demo is governed by the original [license](https://huggingface.co/spaces/hu
32
  if not torch.cuda.is_available():
33
  DESCRIPTION += "\n<p>Running on CPU πŸ₯Ά This demo does not work on CPU.</p>"
34
 
35
-
36
  if torch.cuda.is_available():
37
- model_id = "meta-llama/Llama-2-7b-chat-hf"
38
- model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
39
- tokenizer = AutoTokenizer.from_pretrained(model_id)
 
 
 
40
  tokenizer.use_default_system_prompt = False
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
  @spaces.GPU
44
  def generate(
@@ -84,63 +112,21 @@ def generate(
84
  outputs.append(text)
85
  yield "".join(outputs)
86
 
 
 
 
87
 
88
- chat_interface = gr.ChatInterface(
89
- fn=generate,
90
- additional_inputs=[
91
- gr.Textbox(label="System prompt", lines=6),
92
- gr.Slider(
93
- label="Max new tokens",
94
- minimum=1,
95
- maximum=MAX_MAX_NEW_TOKENS,
96
- step=1,
97
- value=DEFAULT_MAX_NEW_TOKENS,
98
- ),
99
- gr.Slider(
100
- label="Temperature",
101
- minimum=0.1,
102
- maximum=4.0,
103
- step=0.1,
104
- value=0.6,
105
- ),
106
- gr.Slider(
107
- label="Top-p (nucleus sampling)",
108
- minimum=0.05,
109
- maximum=1.0,
110
- step=0.05,
111
- value=0.9,
112
- ),
113
- gr.Slider(
114
- label="Top-k",
115
- minimum=1,
116
- maximum=1000,
117
- step=1,
118
- value=50,
119
- ),
120
- gr.Slider(
121
- label="Repetition penalty",
122
- minimum=1.0,
123
- maximum=2.0,
124
- step=0.05,
125
- value=1.2,
126
- ),
127
- ],
128
- stop_btn=None,
129
- examples=[
130
- ["Hello there! How are you doing?"],
131
- ["Can you explain briefly to me what is the Python programming language?"],
132
- ["Explain the plot of Cinderella in a sentence."],
133
- ["How many hours does it take a man to eat a Helicopter?"],
134
- ["Write a 100-word article on 'Benefits of Open-Source in AI research'"],
135
- ],
136
- cache_examples=False,
137
  )
138
 
139
- with gr.Blocks(css="style.css", fill_height=True) as demo:
140
- gr.Markdown(DESCRIPTION)
141
- gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
142
- chat_interface.render()
143
- gr.Markdown(LICENSE)
144
-
145
- if __name__ == "__main__":
146
- demo.queue(max_size=20).launch()
 
7
  import torch
8
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
9
 
10
+ from llama_index.core.prompts.prompts import SimpleInputPrompt
11
+ from llama_index.llms.huggingface import HuggingFaceLLM
12
+ from llama_index.legacy.embeddings.langchain import LangchainEmbedding
13
+ from langchain.embeddings.huggingface import HuggingFaceEmbeddings
14
+ from llama_index.core import set_global_service_context, ServiceContext, VectorStoreIndex, Document
15
+ from pathlib import Path
16
+ import fitz # PyMuPDF
17
+
18
  MAX_MAX_NEW_TOKENS = 2048
19
  DEFAULT_MAX_NEW_TOKENS = 1024
20
  MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
21
 
22
  DESCRIPTION = """\
23
+ # Llama-2 7B Chat with Document Context
24
 
25
+ This Space demonstrates model [Llama-2-7b-chat](https://huggingface.co/meta-llama/Llama-2-7b-chat) by Meta, a Llama 2 model with 7B parameters fine-tuned for chat instructions, now enhanced with document-based context.
26
+ Feel free to play with it, or duplicate to run generations without a queue! If you want to run your own service, you can also [deploy the model on Inference Endpoints](https://huggingface.co/inference-endpoints).
27
 
28
  πŸ”Ž For more details about the Llama 2 family of models and how to use them with `transformers`, take a look [at our blog post](https://huggingface.co/blog/llama2).
29
 
 
41
  if not torch.cuda.is_available():
42
  DESCRIPTION += "\n<p>Running on CPU πŸ₯Ά This demo does not work on CPU.</p>"
43
 
 
44
  if torch.cuda.is_available():
45
+ model_name = "meta-llama/Llama-2-7b-chat-hf"
46
+ token_file = open("HF_TOKEN.txt")
47
+ auth_token = token_file.readline().strip()
48
+
49
+ model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto", token=auth_token)
50
+ tokenizer = AutoTokenizer.from_pretrained(model_name, cache_dir='./model/', token=auth_token)
51
  tokenizer.use_default_system_prompt = False
52
 
53
+ # Load documents and create the index
54
+ def read_pdf_to_documents(file_path):
55
+ doc = fitz.open(file_path)
56
+ documents = []
57
+ for page_num in range(len(doc)):
58
+ page = doc.load_page(page_num)
59
+ text = page.get_text()
60
+ documents.append(Document(text=text))
61
+ return documents
62
+
63
+ file_path = Path('/content/Full_Pamplet.pdf') # Update with your document path
64
+ documents = read_pdf_to_documents(file_path)
65
+ embeddings = LangchainEmbedding(HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2"))
66
+ service_context = ServiceContext.from_defaults(chunk_size=1024, embed_model=embeddings)
67
+ set_global_service_context(service_context)
68
+ index = VectorStoreIndex.from_documents(documents)
69
+ query_engine = index.as_query_engine()
70
 
71
  @spaces.GPU
72
  def generate(
 
112
  outputs.append(text)
113
  yield "".join(outputs)
114
 
115
+ def query_model(question):
116
+ response = query_engine.query(question)
117
+ return response.response
118
 
119
+ update_prompt_interface = gr.Interface(
120
+ fn=update_system_prompt,
121
+ inputs=gr.Textbox(lines=5, placeholder="Enter the system prompt here...", label="System Prompt", value=system_prompt),
122
+ outputs=gr.Textbox(label="Status"),
123
+ title="System Prompt Updater",
124
+ description="Update the system prompt used for context."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  )
126
 
127
+ query_interface = gr.Interface(
128
+ fn=query_model,
129
+ inputs=gr.Textbox(lines=2, placeholder="Enter your question here...", label="User Question"),
130
+ outputs=gr.Textbox(label="Response"),
131
+ title="Document Query Assistant",
132
+ description="Ask questions based on the conte