Julien6411 commited on
Commit
3172b2b
·
verified ·
1 Parent(s): 7161048

duplicate code from first chapter

Browse files
Files changed (1) hide show
  1. app.py +97 -54
app.py CHANGED
@@ -1,64 +1,107 @@
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 smolagents import CodeAgent, HfApiModel, tool
2
+ import datetime
3
+ import pytz
4
+ import yaml
5
+ import os
6
+ from tools.final_answer import FinalAnswerTool
7
+ from Gradio_UI import GradioUI
8
+ from transformers import Tool # Import the Tool class
9
+ from PIL import Image
10
 
11
+ hf_token = os.getenv("HF_ACCESS_TOKEN")
 
 
 
12
 
13
 
14
+ @tool
15
+ def generate_landscape_image(timezone: str) -> Image.Image:
16
+ """
17
+ A tool that generates a landscape image based on the local time in a given timezone.
18
+ If it's daytime, the image will feature the sun in a position corresponding to the current time.
19
+ If it's nighttime, the image will feature the moon without a preferred position.
20
+
21
+ Args:
22
+ timezone: A valid timezone string (e.g., 'America/New_York').
23
+
24
+ Returns:
25
+ A PIL.Image object of the generated image or an error message as a string.
26
+ """
27
+ try:
28
+ # Create timezone object and get current time in that zone
29
+ tz = pytz.timezone(timezone)
30
+ now = datetime.datetime.now(tz)
31
+ hour = now.hour
32
+
33
+ # Build prompt based on day or night
34
+ if 6 <= hour < 18:
35
+ if hour < 12:
36
+ position = "rising in the east"
37
+ elif hour == 12:
38
+ position = "directly overhead"
39
+ else:
40
+ position = "setting in the west"
41
+ prompt = (
42
+ f"A breathtaking daytime landscape with the sun {position} at {now.strftime('%H:%M')}, "
43
+ "illuminating the scene with warm, golden light."
44
+ )
45
+ else:
46
+ prompt = "A serene nighttime landscape featuring a luminous moon shining in the dark sky."
47
+
48
+ # Call the image generation tool loaded from Space
49
+ result = image_generation_tool(prompt)
50
+
51
+ # If the result is an AgentImage, extract the underlying image.
52
+ if hasattr(result, "to_raw"):
53
+ image = result.to_raw()
54
+ else:
55
+ # Otherwise assume it's a file path and open it.
56
+ image = Image.open(result)
57
+ return image
58
+ except Exception as e:
59
+ return f"Error generating image for timezone '{timezone}': {str(e)}"
60
 
61
+ @tool
62
+ def get_current_time_in_timezone(timezone: str) -> str:
63
+ """
64
+ A tool that fetches the current local time in a specified timezone.
65
+
66
+ Args:
67
+ timezone: a valid timezone string (e.g., 'America/New_York')
68
+
69
+ Returns:
70
+ A string with the current local time or an error message.
71
+ """
72
+ try:
73
+ tz = pytz.timezone(timezone)
74
+ local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
75
+ return f"The current local time in {timezone} is: {local_time}"
76
+ except Exception as e:
77
+ return f"Error fetching time for timezone '{timezone}': {str(e)}"
78
 
79
+ final_answer = FinalAnswerTool()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
+ model = HfApiModel(
82
+ max_tokens=2096,
83
+ temperature=0.5,
84
+ model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',
85
+ custom_role_conversions=None,
86
+ token=hf_token
87
+ )
88
 
89
+ # Load the image generation tool directly from the public FLUX Space
90
+ image_generation_tool = Tool.from_space(
91
+ space_id="black-forest-labs/FLUX.1-dev",
92
+ name="image_generator",
93
+ description="Generate an image from a prompt"
 
 
 
 
 
 
 
 
 
 
 
 
94
  )
95
 
96
+ with open("prompts.yaml", 'r') as stream:
97
+ prompt_templates = yaml.safe_load(stream)
98
+
99
+ agent = CodeAgent(
100
+ model=model,
101
+ tools=[final_answer, generate_landscape_image, get_current_time_in_timezone],
102
+ max_steps=6,
103
+ verbosity_level=1,
104
+ prompt_templates=prompt_templates
105
+ )
106
 
107
+ GradioUI(agent).launch()