emizemani commited on
Commit
c52aaee
·
verified ·
1 Parent(s): 3a37f74

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -83
app.py CHANGED
@@ -2,90 +2,98 @@ import os
2
  import gradio as gr
3
  from huggingface_hub import hf_hub_download
4
  from llama_cpp import Llama
5
- from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
6
- from llama_cpp_agent.providers import LlamaCppPythonProvider
7
- from llama_cpp_agent.chat_history import BasicChatHistory
8
- from llama_cpp_agent.chat_history.messages import Roles
9
-
10
- # Define constants for repository and model details
11
- REPO_ID = "emizemani/editlyai-gguf"
12
- MODEL_FILENAME = "editlyai.gguf"
13
- MODEL_DIR = "./models"
14
- MODEL_PATH = os.path.join(MODEL_DIR, MODEL_FILENAME)
15
-
16
- # Ensure the model directory exists
17
- os.makedirs(MODEL_DIR, exist_ok=True)
18
-
19
- # API token for authenticated access to Hugging Face Hub
20
- HF_TOKEN = os.getenv("HF_TOKEN")
21
-
22
- # Download the model if it's not already present using the HF token for authentication
23
- if not os.path.exists(MODEL_PATH):
24
- hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, local_dir=MODEL_DIR, use_auth_token=HF_TOKEN)
25
-
26
- # Initialize the Llama model for CPU usage
27
- llm = Llama(
28
- model_path=MODEL_PATH,
29
- flash_attn=True, # Adjust this based on your hardware's capability
30
- n_gpu_layers=0, # Using CPU
31
- n_batch=1,
32
- n_ctx=4096
33
- )
34
-
35
- def respond(message, system_message):
36
- # Setup Llama provider and agent
37
- provider = LlamaCppPythonProvider(llm)
38
- agent = LlamaCppAgent(
39
- provider,
40
- system_prompt=system_message,
41
- predefined_messages_formatter_type=MessagesFormatterType.GEMMA_2,
42
- debug_output=True
43
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
- # Prepare chat history and settings
46
- settings = provider.get_provider_default_settings()
47
- messages = BasicChatHistory()
48
- messages.add_message({'role': Roles.system, 'content': system_message})
49
- messages.add_message({'role': Roles.user, 'content': message})
50
-
51
- # Generate response using the Llama model
52
- stream = agent.get_chat_response(
53
- message,
54
- llm_sampling_settings=settings,
55
- chat_history=messages,
56
- returns_streaming_generator=True,
57
- print_output=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  )
59
 
60
- # Process the model output
61
- output = ""
62
- try:
63
- for data in stream:
64
- if "text" in data:
65
- output += data["text"]
66
- yield output
67
- except Exception as e:
68
- yield f"An error occurred: {str(e)}"
69
-
70
- # Comprehensive system prompt for Editly AI
71
- SYSTEM_PROMPT = (
72
- "Hello, I am Editly AI, your intelligent text editing assistant. "
73
- "I specialize in correcting grammar, enhancing clarity, and refining the style of your text. "
74
- "Please type the text you want edited, and I will provide suggestions to improve it."
75
- )
76
-
77
- # Configure Gradio interface
78
- demo = gr.Interface(
79
- fn=respond,
80
- inputs=[
81
- gr.Textbox(label="Enter your text here", placeholder="Type here...", lines=4),
82
- gr.Textbox(value=SYSTEM_PROMPT, label="System message", visible=False),
83
- ],
84
- outputs="text",
85
- title="Editly AI - Text Editing Assistant",
86
- description="Interact with Editly AI to refine and enhance your text.",
87
- theme="huggingface"
88
- )
89
-
90
- if __name__ == "__main__":
91
- demo.launch()
 
2
  import gradio as gr
3
  from huggingface_hub import hf_hub_download
4
  from llama_cpp import Llama
5
+
6
+ # Define the system prompt for Editly AI
7
+ SYSTEM_PROMPT = "You are Editly AI, an English-speaking assistant specialized in editing and improving text. Communicate with users to enhance their writing. You will answer queries about editing only."
8
+
9
+ def get_message_tokens(model, role, content):
10
+ content = f"{role}\n{content}\n</s>"
11
+ content = content.encode("utf-8")
12
+ return model.tokenize(content, special=True)
13
+
14
+ def get_system_tokens(model):
15
+ system_message = {"role": "system", "content": SYSTEM_PROMPT}
16
+ return get_message_tokens(model, **system_message)
17
+
18
+ def load_model(
19
+ directory: str = ".",
20
+ model_name: str = "editlyai.gguf",
21
+ repo_id: str = "emizemani/editlyai-gguf"
22
+ ):
23
+ final_model_path = os.path.join(directory, model_name)
24
+
25
+ print("Downloading model...")
26
+ if not os.path.exists(final_model_path):
27
+ hf_hub_download(
28
+ repo_id=repo_id,
29
+ filename=model_name,
30
+ local_dir=directory,
31
+ use_auth_token=os.getenv('HF_TOKEN') # Ensure you have the HF_TOKEN set up in your environment
32
+ )
33
+ print("Model downloaded and ready to use.")
34
+
35
+ model = Llama(
36
+ model_path=final_model_path,
37
+ n_ctx=1024
 
 
 
 
 
38
  )
39
+
40
+ print("Model loaded!")
41
+ return model
42
+
43
+ # Initialize the model
44
+ MODEL = load_model()
45
+
46
+ def user(message, history):
47
+ new_history = history + [[message, None]]
48
+ return "", new_history
49
+
50
+ def bot(history, system_prompt):
51
+ model = MODEL
52
+ tokens = get_system_tokens(model)[:]
53
 
54
+ for user_message, bot_message in history[:-1]:
55
+ message_tokens = get_message_tokens(model=model, role="user", content=user_message)
56
+ tokens.extend(message_tokens)
57
+ if bot_message:
58
+ message_tokens = get_message_tokens(model=model, role="bot", content=bot_message)
59
+ tokens.extend(message_tokens)
60
+
61
+ last_user_message = history[-1][0]
62
+ message_tokens = get_message_tokens(model=model, role="user", content=last_user_message)
63
+ tokens.extend(message_tokens)
64
+
65
+ role_tokens = model.tokenize("bot\n".encode("utf-8"), special=True)
66
+ tokens.extend(role_tokens)
67
+ generator = model.generate(tokens)
68
+
69
+ partial_text = ""
70
+ for token in generator:
71
+ if token == model.token_eos():
72
+ break
73
+ partial_text += model.detokenize([token]).decode("utf-8", "ignore")
74
+ history[-1][1] = partial_text
75
+ yield history
76
+
77
+ # Gradio interface setup
78
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
79
+ gr.Markdown(f"<h1>Editly AI - Text Editing Assistant</h1>")
80
+ with gr.Row():
81
+ system_prompt_box = gr.Textbox(value=SYSTEM_PROMPT, label="System Prompt", interactive=False)
82
+ chatbot = gr.Chatbot(label="Conversation")
83
+ with gr.Row():
84
+ msg = gr.Textbox(label="Send a message")
85
+ submit = gr.Button("Send")
86
+
87
+ submit.click(
88
+ fn=user,
89
+ inputs=[msg, chatbot],
90
+ outputs=[msg, chatbot]
91
+ ).success(
92
+ fn=bot,
93
+ inputs=[chatbot, system_prompt_box],
94
+ outputs=chatbot
95
  )
96
 
97
+ demo.launch(show_error=True, share=True)
98
+
99
+