MOQTDA commited on
Commit
16cbd12
·
verified ·
1 Parent(s): d7a368e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -54
app.py CHANGED
@@ -1,64 +1,72 @@
 
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
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
  ],
 
 
 
 
 
 
 
60
  )
61
 
62
-
63
  if __name__ == "__main__":
64
- demo.launch()
 
1
+ from transformers import T5Tokenizer, T5ForConditionalGeneration
2
  import gradio as gr
3
+ import requests
4
+ import re
5
 
6
+ # تحميل نموذج CodeT5
7
+ model_name = "Salesforce/codet5-base"
8
+ tokenizer = T5Tokenizer.from_pretrained(model_name)
9
+ model = T5ForConditionalGeneration.from_pretrained(model_name)
10
 
11
+ # وظيفة لجلب الأكواد من الإنترنت تلقائيًا (مثلاً GitHub Gist أو مستودعات GitHub)
12
+ def fetch_code_from_github(keyword, language="python"):
13
+ try:
14
+ # البحث عن الأكواد عبر GitHub API
15
+ url = f"https://api.github.com/search/code?q={keyword}+language:{language}"
16
+ headers = {"Accept": "application/vnd.github.v3+json"}
17
+ response = requests.get(url, headers=headers)
18
+
19
+ if response.status_code == 200:
20
+ results = response.json()
21
+ # استخراج الروابط والمحتوى
22
+ items = results.get("items", [])
23
+ if items:
24
+ first_result = items[0]
25
+ file_url = first_result["html_url"]
26
+ return f"Code fetched from: {file_url}"
27
+ else:
28
+ return "No matching code found on GitHub."
29
+ else:
30
+ return f"Error fetching code: {response.status_code}"
31
+ except Exception as e:
32
+ return str(e)
33
 
34
+ # وظيفة للتعديل أو التوليد باستخدام CodeT5
35
+ def modify_or_generate_code(input_text, task="generate_code"):
36
+ try:
37
+ inputs = tokenizer(input_text, return_tensors="pt", max_length=512, truncation=True)
38
+ outputs = model.generate(**inputs, max_length=512, num_beams=4, early_stopping=True)
39
+ generated_code = tokenizer.decode(outputs[0], skip_special_tokens=True)
40
+ return generated_code
41
+ except Exception as e:
42
+ return str(e)
43
 
44
+ # واجهة Gradio
45
+ def main_interface(task, input_text, fetch_keyword=None, language="python"):
46
+ if task == "fetch_code":
47
+ return fetch_code_from_github(fetch_keyword, language)
48
+ elif task == "generate_code":
49
+ return modify_or_generate_code(input_text, task)
50
+ else:
51
+ return "Invalid task selected."
52
 
53
+ # إنشاء واجهة Gradio
54
+ interface = gr.Interface(
55
+ fn=main_interface,
56
+ inputs=[
57
+ gr.Radio(["fetch_code", "generate_code"], label="Task"),
58
+ gr.Textbox(lines=5, placeholder="Enter your input text or description here...", label="Input Text"),
59
+ gr.Textbox(placeholder="Enter keyword for fetching code...", label="Fetch Keyword (Optional)"),
60
+ gr.Textbox(value="python", placeholder="Language (default: python)", label="Programming Language"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  ],
62
+ outputs="text",
63
+ title="CodeT5 Code Assistant",
64
+ description="Generate or fetch code snippets using CodeT5 with extended features.",
65
+ examples=[
66
+ ["generate_code", "Translate Python to Java: def add(a, b): return a + b", None, "python"],
67
+ ["fetch_code", None, "factorial", "python"]
68
+ ]
69
  )
70
 
 
71
  if __name__ == "__main__":
72
+ interface.launch()