Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,15 +8,36 @@ from langchain_community.llms import HuggingFaceHub
|
|
| 8 |
from langchain.prompts import ChatPromptTemplate
|
| 9 |
from dotenv import load_dotenv
|
| 10 |
import os
|
|
|
|
| 11 |
from datetime import datetime
|
| 12 |
from skyfield.api import load
|
| 13 |
import matplotlib.pyplot as plt
|
| 14 |
from io import BytesIO
|
| 15 |
from PIL import Image
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
# Load environment variables
|
| 18 |
load_dotenv()
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
DATA_PATH = "" # Specify the path to your file
|
| 21 |
PROMPT_TEMPLATE = """
|
| 22 |
Ответь на вопрос, используя только следующий контекст:
|
|
@@ -136,6 +157,25 @@ def process_query(query_text: str, vectorstore):
|
|
| 136 |
except Exception as e:
|
| 137 |
return f"Ошибка обработки запроса: {str(e)}", []
|
| 138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
def PLadder_ZSizes(date_time_iso: str):
|
| 140 |
"""
|
| 141 |
Calculate the planetary ladder and zone sizes for a given date and time.
|
|
@@ -238,22 +278,22 @@ def plot_pladder(PLadder):
|
|
| 238 |
matplotlib.figure.Figure: The generated plot
|
| 239 |
"""
|
| 240 |
fig, ax = plt.subplots()
|
| 241 |
-
#
|
| 242 |
-
ax.plot([0,
|
| 243 |
# Draw horizontal lines dividing height into three equal parts
|
| 244 |
ax.plot([0, 3], [1, 1], 'k--')
|
| 245 |
ax.plot([0, 3], [2, 2], 'k--')
|
| 246 |
-
# Define positions for planets 1 to 7
|
| 247 |
-
positions = [(0, 0), (0, 1), (0, 2), (
|
| 248 |
for i, pos in enumerate(positions):
|
| 249 |
symbol = planet_symbols[PLadder[i]]
|
| 250 |
-
ax.text(pos[0], pos[1], symbol, ha='center', va='center', fontsize=
|
| 251 |
ax.set_xlim(-0.5, 3.5)
|
| 252 |
ax.set_ylim(-0.5, 3.5)
|
| 253 |
ax.set_aspect('equal')
|
| 254 |
ax.axis('off')
|
| 255 |
return fig
|
| 256 |
-
|
| 257 |
def chat_interface(query_text):
|
| 258 |
"""
|
| 259 |
Handle user queries, either for planetary ladder or general RAG questions.
|
|
@@ -323,14 +363,31 @@ def chat_interface(query_text):
|
|
| 323 |
return f"Критическая ошибка: {str(e)}", None
|
| 324 |
|
| 325 |
# Define Gradio Interface
|
| 326 |
-
interface = gr.Interface(
|
| 327 |
-
fn=chat_interface,
|
| 328 |
-
inputs=gr.Textbox(lines=2, placeholder="Введите ваш вопрос здесь..."),
|
| 329 |
-
outputs=[gr.Textbox(), gr.Image()],
|
| 330 |
-
title="Чат с документами",
|
| 331 |
-
description="Задайте вопрос, и я отвечу на основе
|
| 332 |
-
"Для запроса планетарной лестницы используйте формат: PLadder
|
| 333 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
|
| 335 |
if __name__ == "__main__":
|
| 336 |
interface.launch()
|
|
|
|
| 8 |
from langchain.prompts import ChatPromptTemplate
|
| 9 |
from dotenv import load_dotenv
|
| 10 |
import os
|
| 11 |
+
import numpy as np
|
| 12 |
from datetime import datetime
|
| 13 |
from skyfield.api import load
|
| 14 |
import matplotlib.pyplot as plt
|
| 15 |
from io import BytesIO
|
| 16 |
from PIL import Image
|
| 17 |
+
from opentelemetry.sdk.trace import TracerProvider
|
| 18 |
+
from openinference.instrumentation.smolagents import SmolagentsInstrumentor
|
| 19 |
+
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
| 20 |
+
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
| 21 |
|
| 22 |
# Load environment variables
|
| 23 |
load_dotenv()
|
| 24 |
|
| 25 |
+
# Add the alias before instrumentation
|
| 26 |
+
smolagents.ApiModel = smolagents.HfApiModel
|
| 27 |
+
|
| 28 |
+
LANGFUSE_PUBLIC_KEY="pk-lf-133099c7-8644-49e8-8f6e-ec8bd6d543fd"
|
| 29 |
+
LF_SECRET_KEY = os.environ["LANGFUSE_SECRET_KEY"]
|
| 30 |
+
LANGFUSE_AUTH=base64.b64encode(f"{LANGFUSE_PUBLIC_KEY}:{LF_SECRET_KEY}".encode()).decode()
|
| 31 |
+
|
| 32 |
+
os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = "https://cloud.langfuse.com/api/public/otel" # EU data region
|
| 33 |
+
# os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = "https://us.cloud.langfuse.com/api/public/otel" # US data region
|
| 34 |
+
os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"Authorization=Basic {LANGFUSE_AUTH}"
|
| 35 |
+
|
| 36 |
+
trace_provider = TracerProvider()
|
| 37 |
+
trace_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter()))
|
| 38 |
+
|
| 39 |
+
SmolagentsInstrumentor().instrument(tracer_provider=trace_provider)
|
| 40 |
+
|
| 41 |
DATA_PATH = "" # Specify the path to your file
|
| 42 |
PROMPT_TEMPLATE = """
|
| 43 |
Ответь на вопрос, используя только следующий контекст:
|
|
|
|
| 157 |
except Exception as e:
|
| 158 |
return f"Ошибка обработки запроса: {str(e)}", []
|
| 159 |
|
| 160 |
+
# Function to parse date and time into ISO format
|
| 161 |
+
def parse_date_time(date_time_str):
|
| 162 |
+
try:
|
| 163 |
+
dt = parser.parse(date_time_str)
|
| 164 |
+
return dt.isoformat()
|
| 165 |
+
except ValueError:
|
| 166 |
+
return None
|
| 167 |
+
|
| 168 |
+
# Function to convert longitude to zodiac sign and degrees
|
| 169 |
+
def lon_to_sign(lon):
|
| 170 |
+
signs = ["Овен", "Телец", "Близнецы", "Рак", "Лев", "Дева",
|
| 171 |
+
"Весы", "Скорпион", "Стрелец", "Козерог", "Водолей", "Рыбы"]
|
| 172 |
+
sign_index = int(lon // 30)
|
| 173 |
+
sign = signs[sign_index]
|
| 174 |
+
degrees = int(lon % 30)
|
| 175 |
+
minutes = int((lon % 1) * 60)
|
| 176 |
+
return f"{sign} {degrees}°{minutes}'"
|
| 177 |
+
|
| 178 |
+
# Function to calculate PLadder and zone sizes
|
| 179 |
def PLadder_ZSizes(date_time_iso: str):
|
| 180 |
"""
|
| 181 |
Calculate the planetary ladder and zone sizes for a given date and time.
|
|
|
|
| 278 |
matplotlib.figure.Figure: The generated plot
|
| 279 |
"""
|
| 280 |
fig, ax = plt.subplots()
|
| 281 |
+
# Plot triangle with right angle on top: vertices at (0,0), (1.5,3), (3,0)
|
| 282 |
+
ax.plot([0, 1.5, 3, 0], [0, 3, 0, 0], 'k-')
|
| 283 |
# Draw horizontal lines dividing height into three equal parts
|
| 284 |
ax.plot([0, 3], [1, 1], 'k--')
|
| 285 |
ax.plot([0, 3], [2, 2], 'k--')
|
| 286 |
+
# Define positions for planets 1 to 7, adjusted to avoid overlap
|
| 287 |
+
positions = [(0.2, 0.2), (0.2, 1.2), (0.2, 2.2), (1.5, 3.2), (2.8, 2.2), (2.8, 1.2), (2.8, 0.2)]
|
| 288 |
for i, pos in enumerate(positions):
|
| 289 |
symbol = planet_symbols[PLadder[i]]
|
| 290 |
+
ax.text(pos[0], pos[1], symbol, ha='center', va='center', fontsize=24) # Doubled font size
|
| 291 |
ax.set_xlim(-0.5, 3.5)
|
| 292 |
ax.set_ylim(-0.5, 3.5)
|
| 293 |
ax.set_aspect('equal')
|
| 294 |
ax.axis('off')
|
| 295 |
return fig
|
| 296 |
+
|
| 297 |
def chat_interface(query_text):
|
| 298 |
"""
|
| 299 |
Handle user queries, either for planetary ladder or general RAG questions.
|
|
|
|
| 363 |
return f"Критическая ошибка: {str(e)}", None
|
| 364 |
|
| 365 |
# Define Gradio Interface
|
| 366 |
+
#interface = gr.Interface(
|
| 367 |
+
# fn=chat_interface,
|
| 368 |
+
# inputs=gr.Textbox(lines=2, placeholder="Введите ваш вопрос здесь..."),
|
| 369 |
+
# outputs=[gr.Textbox(), gr.Image()],
|
| 370 |
+
# title="Чат с документами",
|
| 371 |
+
# description="Задайте вопрос, и я отвечу на основе книги Павла Глобы "Планетарная Лестница". "
|
| 372 |
+
# "Для быстрого запроса трактовки планетарной лестницы используйте формат: PLadder DD-MM-YYYY HH:MM:SS место"
|
| 373 |
+
#)
|
| 374 |
+
|
| 375 |
+
# UI layout with Gradio Blocks
|
| 376 |
+
with gr.Blocks() as interface:
|
| 377 |
+
with gr.Row():
|
| 378 |
+
with gr.Column(scale=2):
|
| 379 |
+
output_text = gr.Textbox(label="Response", lines=10)
|
| 380 |
+
with gr.Column(scale=1):
|
| 381 |
+
output_image = gr.Image(label="Planetary Ladder Plot")
|
| 382 |
+
with gr.Row():
|
| 383 |
+
query_text = gr.Textbox(label="Query", placeholder="e.g., PLadder 2023-10-10 12:00")
|
| 384 |
+
location_lat = gr.Textbox(label="Latitude", placeholder="e.g., 37.7749")
|
| 385 |
+
location_lon = gr.Textbox(label="Longitude", placeholder="e.g., -122.4194")
|
| 386 |
+
|
| 387 |
+
query_text.submit(chat_interface,
|
| 388 |
+
inputs=[query_text, location_lat, location_lon],
|
| 389 |
+
outputs=[output_text, output_image])
|
| 390 |
+
|
| 391 |
|
| 392 |
if __name__ == "__main__":
|
| 393 |
interface.launch()
|