Mehgoss commited on
Commit
9a382b7
Β·
verified Β·
1 Parent(s): 5e4f5d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -61
app.py CHANGED
@@ -1,70 +1,118 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
3
 
 
4
 
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- 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
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
 
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
-
25
- response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
  )
 
62
 
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
 
 
 
 
 
 
 
 
 
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  if __name__ == "__main__":
70
- demo.launch()
 
1
  import gradio as gr
2
+ from llama_cpp import Llama
3
+ from huggingface_hub import hf_hub_download
4
+ import os
5
 
6
+ print("Starting model download...")
7
 
8
+ # Download model file explicitly (better control)
9
+ try:
10
+ # Try to find the GGUF file in the repo
11
+ # If your repo has a different filename, change it here
12
+ model_path = hf_hub_download(
13
+ repo_id="TheBloke/CodeLlama-7B-Python-GGUF", # Using TheBloke's reliable repo
14
+ filename="codellama-7b-python.Q4_K_M.gguf", # 4.08GB file
15
+ cache_dir="./models"
16
+ )
17
+ print(f"βœ“ Model downloaded to: {model_path}")
18
+ except Exception as e:
19
+ print(f"Error downloading model: {e}")
20
+ raise
21
 
22
+ # Load the GGUF model
23
+ print("Loading model into memory...")
24
+ llm = Llama(
25
+ model_path=model_path,
26
+ n_ctx=2048, # Context window
27
+ n_threads=int(os.getenv("N_THREADS", "2")), # CPU threads
28
+ n_batch=512, # Batch size for prompt processing
29
+ verbose=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  )
31
+ print("βœ“ Model loaded successfully!")
32
 
33
+ def generate_code(prompt, max_tokens=500, temperature=0.7):
34
+ """Generate code from prompt"""
35
+ try:
36
+ response = llm(
37
+ prompt,
38
+ max_tokens=max_tokens,
39
+ temperature=temperature,
40
+ stop=["</s>", "###", "\n\n\n"], # Stop sequences
41
+ echo=False
42
+ )
43
+ return response['choices'][0]['text']
44
+ except Exception as e:
45
+ return f"Error generating code: {str(e)}"
46
 
47
+ # Create Gradio interface
48
+ with gr.Blocks(title="CodeLlama Assistant", theme=gr.themes.Soft()) as demo:
49
+ gr.Markdown("# πŸ¦™ CodeLlama-7B Python Assistant")
50
+ gr.Markdown("AI-powered code generation using CodeLlama-7B (4GB GGUF model)")
51
+
52
+ with gr.Row():
53
+ with gr.Column():
54
+ prompt_input = gr.Textbox(
55
+ label="Enter your coding question or task",
56
+ placeholder="Write a Python function to...",
57
+ lines=5
58
+ )
59
+ with gr.Row():
60
+ max_tokens = gr.Slider(
61
+ minimum=100,
62
+ maximum=1000,
63
+ value=500,
64
+ step=50,
65
+ label="Max Tokens"
66
+ )
67
+ temperature = gr.Slider(
68
+ minimum=0.1,
69
+ maximum=1.0,
70
+ value=0.7,
71
+ step=0.1,
72
+ label="Temperature"
73
+ )
74
+ submit_btn = gr.Button("πŸš€ Generate Code", variant="primary", size="lg")
75
+ clear_btn = gr.Button("πŸ—‘οΈ Clear", size="sm")
76
+
77
+ with gr.Column():
78
+ output = gr.Textbox(
79
+ label="Generated Code",
80
+ lines=15,
81
+ show_copy_button=True
82
+ )
83
+
84
+ # Button actions
85
+ submit_btn.click(
86
+ fn=generate_code,
87
+ inputs=[prompt_input, max_tokens, temperature],
88
+ outputs=output
89
+ )
90
+
91
+ clear_btn.click(
92
+ fn=lambda: ("", ""),
93
+ inputs=None,
94
+ outputs=[prompt_input, output]
95
+ )
96
+
97
+ # Example prompts
98
+ gr.Examples(
99
+ examples=[
100
+ ["Write a Python function to calculate fibonacci numbers"],
101
+ ["Create a binary search tree class with insert and search methods"],
102
+ ["Write a function to reverse a linked list"],
103
+ ["Implement quicksort algorithm in Python"],
104
+ ["Create a decorator to measure function execution time"]
105
+ ],
106
+ inputs=prompt_input
107
+ )
108
+
109
+ gr.Markdown("""
110
+ ### πŸ’‘ Tips:
111
+ - Be specific in your prompts for better results
112
+ - Lower temperature (0.3-0.5) for more focused code
113
+ - Higher temperature (0.7-0.9) for more creative solutions
114
+ - Model works best for Python code generation
115
+ """)
116
 
117
  if __name__ == "__main__":
118
+ demo.launch(server_name="0.0.0.0", server_port=7860)