rateshhf25 commited on
Commit
4def602
·
verified ·
1 Parent(s): edb3cd8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -54
app.py CHANGED
@@ -1,70 +1,151 @@
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 groq import Groq
3
+ from dotenv import load_dotenv
4
+ import os, datetime, re
5
 
6
+ # === Load API key ===
7
+ load_dotenv()
8
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
9
 
10
+ # === Helper Functions ===
11
+ def sanitize_filename(name):
12
+ return re.sub(r"[^a-zA-Z0-9_-]", "_", name)
 
 
 
 
 
 
 
 
 
 
13
 
14
+ def save_code(code, language):
15
+ os.makedirs("outputs", exist_ok=True)
16
+ ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
17
+ filename = f"outputs/{sanitize_filename(language)}_{ts}.txt"
18
+ with open(filename, "w", encoding="utf-8") as f:
19
+ f.write(code)
20
+ return f" Code saved to `{filename}`"
21
 
22
+ # === Simple Heuristic Language Detector ===
23
+ def detect_language(prompt_or_code):
24
+ text = prompt_or_code.lower()
25
+ if "python" in text or "def " in text or "import " in text:
26
+ return "python"
27
+ elif "#include" in text or "printf" in text:
28
+ return "c"
29
+ elif "iostream" in text or "cout" in text:
30
+ return "cpp"
31
+ elif "public static void main" in text or "System.out.println" in text:
32
+ return "java"
33
+ elif "console.log" in text or "function(" in text:
34
+ return "javascript"
35
+ else:
36
+ return "python" # default fallback
37
 
38
+ # === Code Generation ===
39
+ def generate_code(prompt, language, history):
40
+ try:
41
+ # Auto-detect language if none selected
42
+ if language == "auto" or not language:
43
+ language = detect_language(prompt)
44
 
45
+ response = client.chat.completions.create(
46
+ model="llama-3.1-8b-instant",
47
+ messages=[
48
+ {"role": "system", "content": "You are an expert software engineer."},
49
+ {"role": "user", "content": f"Write a {language} program for: {prompt}"}
50
+ ],
51
+ temperature=0.4
52
+ )
53
+ text = response.choices[0].message.content.strip()
54
+ text = re.sub(r"```[a-zA-Z]*", "", text).replace("```", "").strip()
55
 
56
+ history.append({"action": "Generated", "prompt": prompt, "language": language, "code": text})
57
+ return text, history, language
58
+ except Exception as e:
59
+ return f"Error: {e}", history, language
 
 
 
 
 
 
 
60
 
61
+ # === Debugging & Explanation ===
62
+ def debug_code(code, error_message, language, history):
63
+ try:
64
+ # Auto-detect language from code
65
+ if language == "auto" or not language:
66
+ language = detect_language(code)
67
 
68
+ debug_prompt = f"""
69
+ You are a professional {language} developer and debugger.
70
+ Here is the user's code that produced an error:
71
 
72
+ CODE:
73
+ {code}
74
+
75
+ ERROR MESSAGE / OUTPUT:
76
+ {error_message}
77
+
78
+ Please identify and fix the issue. Return only the corrected code.
79
  """
80
+ response = client.chat.completions.create(
81
+ model="llama-3.1-8b-instant",
82
+ messages=[
83
+ {"role": "system", "content": "You are an expert code debugger."},
84
+ {"role": "user", "content": debug_prompt}
85
+ ],
86
+ temperature=0.3
87
+ )
88
+ fixed_code = response.choices[0].message.content.strip()
89
+ fixed_code = re.sub(r"```[a-zA-Z]*", "", fixed_code).replace("```", "").strip()
90
+
91
+ # Explain fix
92
+ exp_prompt = f"Explain briefly (under 100 words) what was wrong in this {language} code and how it was fixed."
93
+ exp_response = client.chat.completions.create(
94
+ model="llama-3.1-8b-instant",
95
+ messages=[
96
+ {"role": "system", "content": "You are an expert software explainer."},
97
+ {"role": "user", "content": f"{exp_prompt}\n\nOriginal Code:\n{code}\n\nFixed Code:\n{fixed_code}"}
98
+ ],
99
+ temperature=0.4
100
+ )
101
+ explanation = exp_response.choices[0].message.content.strip()
102
+
103
+ history.append({
104
+ "action": "Debugged",
105
+ "language": language,
106
+ "error": error_message,
107
+ "fixed_code": fixed_code,
108
+ "explanation": explanation
109
+ })
110
+ return fixed_code, explanation, history, language
111
+ except Exception as e:
112
+ return f"Error: {e}", "Could not generate explanation.", history, language
113
+
114
+ # === GUI ===
115
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="violet", neutral_hue="gray"), title="LLaMA 3.1 Code Assistant") as demo:
116
+ gr.HTML("<h1 style='text-align:center;'>🧠 LLaMA 3.1 Code Assistant + Debugger + Explainer</h1>")
117
+ gr.Markdown("An intelligent, debugging-friendly AI tool built with **Groq API (LLaMA 3.1)** — generate, debug, and learn code effortlessly.")
118
+
119
+ history = gr.State([])
120
+
121
+ with gr.Row():
122
+ with gr.Column(scale=2):
123
+ gr.Markdown("### Code Generation")
124
+ prompt = gr.Textbox(label="Enter your programming request", placeholder="e.g., Write a Python program to check palindrome", lines=3)
125
+ language = gr.Dropdown(
126
+ ["auto", "python", "c", "cpp", "java", "javascript"],
127
+ label="Select Language (auto-detect default)",
128
+ value="auto"
129
+ )
130
+ run_btn = gr.Button("Generate Code", variant="primary")
131
+ output = gr.Code(label="Generated Code", language="python", interactive=False)
132
+ save_btn = gr.Button("Save Code")
133
+ save_status = gr.Markdown("")
134
+ with gr.Column(scale=2):
135
+ gr.Markdown("### Debugging & Explanation")
136
+ error_box = gr.Textbox(label="Paste Error Message / Output", lines=3, placeholder="e.g., segmentation fault, syntax error...")
137
+ debug_btn = gr.Button("Debug Code")
138
+ debugged_output = gr.Code(label="Fixed Code", language="python", interactive=False)
139
+ explanation_box = gr.Textbox(label="Explanation", interactive=False, lines=4)
140
+
141
+ # Event Bindings
142
+ run_btn.click(fn=generate_code, inputs=[prompt, language, history], outputs=[output, history, language])
143
+ save_btn.click(fn=save_code, inputs=[output, language], outputs=save_status)
144
+ debug_btn.click(fn=debug_code, inputs=[output, error_box, language, history], outputs=[debugged_output, explanation_box, history, language])
145
 
146
+ with gr.Accordion("Session Memory (History)", open=False):
147
+ gr.JSON(history)
148
 
149
+ # === Launch ===
150
  if __name__ == "__main__":
151
  demo.launch()