ocaklisemih commited on
Commit
6ad4d93
·
verified ·
1 Parent(s): e96bed3

Upload 3 files

Browse files
Files changed (2) hide show
  1. app.py +29 -153
  2. requirements.txt +1 -3
app.py CHANGED
@@ -1,30 +1,15 @@
1
- from smolagents import CodeAgent, load_tool, tool
2
- try:
3
- from smolagents import HfApiModel
4
- except ImportError:
5
- try:
6
- from smolagents.models import HfApiModel
7
- except ImportError:
8
- from smolagents import TransformersModel as HfApiModel
9
- print("Using TransformersModel as fallback for HfApiModel")
10
  import datetime
11
  import requests
12
  import pytz
13
  import yaml
14
- import os
15
  from tools.final_answer import FinalAnswerTool
16
- from tools.web_search import DuckDuckGoSearchTool
17
- from tools.visit_webpage import VisitWebpageTool
18
  from typing import Any, Optional
19
  import duckduckgo_search
20
  from kerykeion import AstrologicalSubject, Report, KerykeionChartSVG
21
  import gradio as gr
22
  from Gradio_UI import GradioUI
23
 
24
- # Charts klasörünü oluştur
25
- if not os.path.exists("charts"):
26
- os.makedirs("charts")
27
-
28
  @tool
29
  def get_current_time_in_timezone(timezone: str) -> str:
30
  """A tool that fetches the current local time in a specified timezone.
@@ -55,13 +40,9 @@ def create_birth_chart(name: str, year: int, month: int, day: int, hour: int, mi
55
  nation: Birth country
56
 
57
  Returns:
58
- str: Success message with file paths
59
  """
60
  try:
61
- print(f"🔮 {name} için doğum haritası oluşturuluyor...")
62
- print(f"📅 Doğum: {day}/{month}/{year} {hour}:{minute:02d}")
63
- print(f"🌍 Konum: {city}, {nation}")
64
-
65
  # Create birth chart
66
  person = AstrologicalSubject(
67
  name=name,
@@ -76,83 +57,28 @@ def create_birth_chart(name: str, year: int, month: int, day: int, hour: int, mi
76
 
77
  # Create SVG file
78
  chart = KerykeionChartSVG(person)
79
- safe_name = name.lower().replace(' ', '_').replace('ı', 'i').replace('ğ', 'g').replace('ü', 'u').replace('ş', 's').replace('ö', 'o').replace('ç', 'c')
80
- svg_path = f"charts/{safe_name}_birth_chart.svg"
81
  chart.makeSVG(svg_path)
82
 
83
  # Create astrological report
84
  report = Report(person)
85
  report_text = report.get_full_report()
86
 
87
- print(f"✅ Doğum haritası başarıyla oluşturuldu: {svg_path}")
88
- return f"SUCCESS|{svg_path}|{report_text}"
 
 
89
 
90
  except Exception as e:
91
- error_msg = f" Doğum haritası oluşturulurken hata: {str(e)}"
92
- print(error_msg)
93
- return f"ERROR|{str(e)}"
94
-
95
- @tool
96
- def interpret_astrological_report(raw_report: str, person_name: str) -> str:
97
- """Interprets a raw astrological report using LLM to create a user-friendly version.
98
-
99
- Args:
100
- raw_report: Raw technical astrological report
101
- person_name: Name of the person
102
-
103
- Returns:
104
- str: LLM-interpreted astrological report
105
- """
106
-
107
- interpretation_prompt = f"""
108
- Aşağıdaki ham astrolojik raporu {person_name} için kullanıcı dostu, anlaşılır ve etkileyici bir astrolojik yorum haline getir.
109
- Türkçe olarak yaz ve astrolojik terimları açıklayarak kişilik analizi, güçlü yanlar, zayıf yanlar ve genel öneriler içeren kapsamlı bir rapor oluştur.
110
-
111
- Ham Rapor:
112
- {raw_report}
113
-
114
- Lütfen şu başlıklar altında organize et:
115
- 🌟 Kişilik Analizi
116
- 💪 Güçlü Yanlarınız
117
- ⚡ Gelişim Alanlarınız
118
- 💕 İlişkiler ve Aşk
119
- 💼 Kariyer ve Başarı
120
- 🔮 Genel Astrolojik Öneriler
121
- """
122
-
123
- try:
124
- # Ham raporu Türkçe format ile yorumlayalım
125
- return f"""
126
- 🌟 **Kişilik Analizi**
127
- {person_name} için detaylı astrolojik analiz:
128
-
129
- 📋 **Ham Astrolojik Veri:**
130
- {raw_report}
131
-
132
- 💭 **Bu rapor, {person_name}'in doğum haritasından çıkarılan temel astrolojik verilerdir.
133
- Detaylı yorumlar için astroloji uzmanına başvurunuz.**
134
- """.strip()
135
- except Exception as e:
136
- return f"Rapor işlenirken hata oluştu: {str(e)}"
137
 
138
  final_answer = FinalAnswerTool()
139
- # Model konfigürasyonu - HfApiModel'in alternatifi olarak TransformersModel kullanıyoruz
140
- try:
141
- from smolagents import HfApiModel
142
- model = HfApiModel(
143
- max_tokens=2096,
144
- temperature=0.5,
145
- model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
146
- )
147
- except ImportError:
148
- # Fallback: TransformersModel kullan
149
- from smolagents import TransformersModel
150
- model = TransformersModel(
151
- model_id="HuggingFaceTB/SmolLM-1.7B-Instruct", # Küçük model local için
152
- max_new_tokens=2096,
153
- temperature=0.5,
154
- )
155
- print("HfApiModel bulunamadı, TransformersModel kullanılıyor.")
156
 
157
  # Import tool from Hub
158
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
@@ -160,14 +86,10 @@ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_co
160
  with open("prompts.yaml", 'r') as stream:
161
  prompt_templates = yaml.safe_load(stream)
162
 
163
- # Initialize tools
164
- web_search_tool = DuckDuckGoSearchTool()
165
- visit_webpage_tool = VisitWebpageTool()
166
-
167
  agent = CodeAgent(
168
  model=model,
169
- tools=[final_answer, create_birth_chart, interpret_astrological_report, web_search_tool, visit_webpage_tool],
170
- max_steps=8,
171
  verbosity_level=1,
172
  grammar=None,
173
  planning_interval=None,
@@ -179,86 +101,40 @@ agent = CodeAgent(
179
  def process_birth_chart(text_input: str):
180
  """Processes user input to create a birth chart."""
181
  try:
182
- # Enhanced prompt for the agent
183
- enhanced_prompt = f"""
184
- Sen astroloji uzmanısın. Kullanıcının doğum bilgilerini analiz et ve astrolojik doğum haritası oluştur.
185
-
186
- Kullanıcı girdisi: {text_input}
187
-
188
- Şu adımları takip et:
189
- 1. Kullanıcının girdiğinden kişinin adını, doğum tarihini (yıl/ay/gün), doğum saatini (saat:dakika), şehrini ve ülkesini çıkar
190
- 2. Bu bilgileri kullanarak create_birth_chart tool'u ile doğum haritasını oluştur
191
- 3. Oluşan ham astrolojik raporu alıp kullanıcı dostu bir Türkçe yoruma dönüştür
192
- 4. Final answer olarak şu başlıklar altında organize edilmiş kapsamlı bir rapor sun:
193
-
194
- 🌟 **Kişilik Analizi**
195
- 💪 **Güçlü Yanlarınız**
196
- ⚡ **Gelişim Alanlarınız**
197
- 💕 **İlişkiler ve Aşk**
198
- 💼 **Kariyer ve Başarı**
199
- 🔮 **Genel Astrolojik Öneriler**
200
-
201
- Raporu Türkçe olarak, sıcak ve anlaşılır bir dille yaz. Astrolojik terimları açıkla.
202
- """
203
-
204
  # Send query to agent and get response
205
- response = agent.run(enhanced_prompt)
206
-
207
- # Response'u string olarak al
208
- if hasattr(response, 'content'):
209
- response_text = response.content
210
- else:
211
- response_text = str(response)
212
-
213
- # Check if SVG file was created successfully
214
- svg_files = [f for f in os.listdir("charts") if f.endswith('.svg')]
215
 
216
- if svg_files:
217
- # Get the most recent SVG file
218
- latest_svg = max([os.path.join("charts", f) for f in svg_files], key=os.path.getctime)
219
- return gr.Image(value=latest_svg), response_text
220
  else:
221
- return None, response_text if response_text else "Doğum haritası oluşturulamadı."
222
 
223
  except Exception as e:
224
- return None, f"Bir hata oluştu: {str(e)}"
225
 
226
  # Create Gradio interface
227
- with gr.Blocks(theme=gr.themes.Soft(), title="🌟 Astrolojik Doğum Haritası Oluşturucu") as demo:
228
- gr.Markdown("# 🌟 Astrolojik Doğum Haritası Oluşturucu")
229
- gr.Markdown("### Doğum bilgilerinizi girin ve kişisel astrolojik analizinizi alın")
230
 
231
  with gr.Row():
232
  text_input = gr.Textbox(
233
- label="🎂 Doğum Bilgilerinizi Girin",
234
- placeholder="Örnek: Benim adım Ahmet Yılmaz, 5 Mayıs 1990 tarihinde saat 15:30'da İstanbul, Türkiye'de doğdum.",
235
- lines=3
236
  )
237
 
238
  with gr.Row():
239
- submit_btn = gr.Button("🔮 Doğum Haritası Oluştur", variant="primary", scale=1)
240
 
241
  with gr.Row():
242
- with gr.Column():
243
- chart_output = gr.Image(label="🌟 Doğum Haritanız", height=400)
244
- with gr.Column():
245
- report_output = gr.Textbox(label="📋 Astrolojik Raporunuz", lines=20, max_lines=30)
246
 
247
  submit_btn.click(
248
  fn=process_birth_chart,
249
  inputs=[text_input],
250
  outputs=[chart_output, report_output]
251
  )
252
-
253
- gr.Markdown("---")
254
- gr.Markdown("### 💡 Nasıl Kullanılır?")
255
- gr.Markdown("""
256
- 1. **Doğum bilgilerinizi** tam olarak girin (ad, tarih, saat, şehir, ülke)
257
- 2. **'Doğum Haritası Oluştur'** butonuna tıklayın
258
- 3. **Doğum haritanızı** ve **kişisel astrolojik analizinizi** görün
259
-
260
- ⭐ **Örnek girdi:** "Benim adım Ayşe Demir, 15 Haziran 1995 tarihinde saat 14:20'de Ankara, Türkiye'de doğdum."
261
- """)
262
 
263
  if __name__ == "__main__":
264
  demo.launch()
 
1
+ from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
 
 
 
 
 
 
 
 
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
 
6
  from tools.final_answer import FinalAnswerTool
 
 
7
  from typing import Any, Optional
8
  import duckduckgo_search
9
  from kerykeion import AstrologicalSubject, Report, KerykeionChartSVG
10
  import gradio as gr
11
  from Gradio_UI import GradioUI
12
 
 
 
 
 
13
  @tool
14
  def get_current_time_in_timezone(timezone: str) -> str:
15
  """A tool that fetches the current local time in a specified timezone.
 
40
  nation: Birth country
41
 
42
  Returns:
43
+ str: Path to the generated SVG file and astrological report
44
  """
45
  try:
 
 
 
 
46
  # Create birth chart
47
  person = AstrologicalSubject(
48
  name=name,
 
57
 
58
  # Create SVG file
59
  chart = KerykeionChartSVG(person)
60
+ svg_path = f"charts/{name.lower().replace(' ', '_')}_birth_chart.svg"
 
61
  chart.makeSVG(svg_path)
62
 
63
  # Create astrological report
64
  report = Report(person)
65
  report_text = report.get_full_report()
66
 
67
+ return {
68
+ "svg_path": svg_path,
69
+ "report": report_text
70
+ }
71
 
72
  except Exception as e:
73
+ return f"Error occurred: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  final_answer = FinalAnswerTool()
76
+ model = HfApiModel(
77
+ max_tokens=2096,
78
+ temperature=0.5,
79
+ model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud',
80
+ custom_role_conversions=None,
81
+ )
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  # Import tool from Hub
84
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
 
86
  with open("prompts.yaml", 'r') as stream:
87
  prompt_templates = yaml.safe_load(stream)
88
 
 
 
 
 
89
  agent = CodeAgent(
90
  model=model,
91
+ tools=[final_answer, create_birth_chart],
92
+ max_steps=6,
93
  verbosity_level=1,
94
  grammar=None,
95
  planning_interval=None,
 
101
  def process_birth_chart(text_input: str):
102
  """Processes user input to create a birth chart."""
103
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  # Send query to agent and get response
105
+ response = agent.run(text_input)
 
 
 
 
 
 
 
 
 
106
 
107
+ if isinstance(response, dict) and "svg_path" in response:
108
+ # Return SVG file and report
109
+ return gr.Image(value=response["svg_path"]), response["report"]
 
110
  else:
111
+ return None, "Sorry, couldn't create the birth chart."
112
 
113
  except Exception as e:
114
+ return None, f"An error occurred: {str(e)}"
115
 
116
  # Create Gradio interface
117
+ with gr.Blocks() as demo:
118
+ gr.Markdown("# 🌟 Astrological Birth Chart Generator")
 
119
 
120
  with gr.Row():
121
  text_input = gr.Textbox(
122
+ label="Enter Your Birth Information",
123
+ placeholder="Example: My name is John Doe, I was born on May 5, 1990 at 15:30 in Istanbul, Turkey."
 
124
  )
125
 
126
  with gr.Row():
127
+ submit_btn = gr.Button("Generate Birth Chart")
128
 
129
  with gr.Row():
130
+ chart_output = gr.Image(label="Birth Chart")
131
+ report_output = gr.Textbox(label="Astrological Report", lines=10)
 
 
132
 
133
  submit_btn.click(
134
  fn=process_birth_chart,
135
  inputs=[text_input],
136
  outputs=[chart_output, report_output]
137
  )
 
 
 
 
 
 
 
 
 
 
138
 
139
  if __name__ == "__main__":
140
  demo.launch()
requirements.txt CHANGED
@@ -1,7 +1,5 @@
1
  markdownify
2
- smolagents>=1.5.0
3
- transformers
4
- torch
5
  requests
6
  duckduckgo_search
7
  pandas
 
1
  markdownify
2
+ smolagents
 
 
3
  requests
4
  duckduckgo_search
5
  pandas