File size: 6,985 Bytes
bce3ea6
 
6805005
bce3ea6
 
 
 
 
 
 
 
6805005
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bce3ea6
 
 
 
 
 
 
 
 
 
4e4c288
 
bce3ea6
 
 
 
 
 
 
 
 
 
 
50c4da9
 
bce3ea6
 
 
50c4da9
 
bce3ea6
 
 
 
 
 
4e4c288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6805005
4e4c288
 
 
 
6805005
 
 
4e4c288
6805005
 
 
 
 
 
 
 
 
4e4c288
 
 
 
 
 
6805005
bce3ea6
50c4da9
 
bce3ea6
 
 
 
 
 
 
 
 
 
 
 
50c4da9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bce3ea6
 
 
 
 
 
 
1304839
bce3ea6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50c4da9
 
bce3ea6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50c4da9
bce3ea6
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import gradio as gr
import os
import csv

# --- Pr贸ba importu HRAssistant ---
try:
    from hr_assistant import HRAssistant
    hr_import_error = None
except ModuleNotFoundError as e:
    hr_import_error = str(e)

# --- Wczytywanie bibliografii ---
def load_bibliography(file_path="bibliografia.csv"):
    bibliography = {}
    try:
        with open(file_path, mode='r', encoding='utf-8') as csvfile:
            reader = csv.reader(csvfile, delimiter=';')
            for row in reader:
                if len(row) == 2:
                    # Klucz to nazwa pliku bez rozszerzenia, warto艣膰 to pe艂ny opis
                    bibliography[row[1].strip()] = row[0].strip()
    except FileNotFoundError:
        print(f"Plik {file_path} nie zosta艂 znaleziony.")
    except Exception as e:
        print(f"B艂膮d podczas wczytywania pliku {file_path}: {e}")
    return bibliography

bibliography_data = load_bibliography()

# --- Inicjalizacja asystenta ---
def initialize_assistant():
    if hr_import_error:
        return None
    
    try:
        api_key = os.getenv("OPENAI_API_KEY")
        if not api_key:
            print("Brak klucza OPENAI_API_KEY w zmiennych 艣rodowiskowych.")
            return None
        hr_assistant = HRAssistant(openai_api_key=api_key, pdf_directory="pdfs")
        return hr_assistant
    except Exception as e:
        print(f"B艂膮d podczas inicjalizacji asystenta HR: {e}")
        return None

assistant = initialize_assistant()

# --- Funkcja obs艂uguj膮ca zapytania ---
def respond_to_query(message, history):
    if not assistant:
        if hr_import_error:
            error_message = f"B艂膮d importu: {hr_import_error}\n\nAby uruchomi膰 aplikacj臋, zainstaluj brakuj膮cy modu艂:\n\npip install sentence-transformers"
            history.append({"role": "user", "content": message})
            history.append({"role": "assistant", "content": error_message})
            return history
        else:
            error_message = "Asystent HR nie jest dost臋pny. Sprawd藕, czy klucz API zosta艂 poprawnie skonfigurowany."
            history.append({"role": "user", "content": message})
            history.append({"role": "assistant", "content": error_message})
            return history

    response = assistant.ask(message)
    answer = response.get("answer", "Przepraszam, wyst膮pi艂 b艂膮d.")
    
    if response.get("sources"):
        answer += "\n\n**殴r贸d艂a:**"
        
        grouped_sources = {}
        for source_meta in response["sources"]:
            source_key = source_meta.get('source')
            if not source_key:
                continue

            if source_key not in grouped_sources:
                grouped_sources[source_key] = {
                    'type': 'url' if source_key.startswith('http') else 'pdf',
                    'meta': source_meta,
                    'pages': set()
                }
            
            if 'page' in source_meta and source_meta['page'] is not None:
                grouped_sources[source_key]['pages'].add(source_meta['page'])

        for key, data in grouped_sources.items():
            if data['type'] == 'pdf':
                file_stem = data['meta'].get('file_stem', os.path.splitext(os.path.basename(key))[0])
                display_name = bibliography_data.get(file_stem, os.path.basename(key))
                
                pages = sorted(list(data['pages']))
                pages_str = ""
                if pages:
                    if len(pages) == 1:
                        pages_str = f"str. {pages[0]}"
                    else:
                        pages_str = "str. " + ", ".join(map(str, pages))
                
                answer += f"\n- {display_name} ({pages_str})" if pages_str else f"\n- {display_name}"

            elif data['type'] == 'url':
                title = data['meta'].get('title', key)
                url = key
                date = data['meta'].get('added_date', '')
                date_str = f" (dodano: {date})" if date else ""
                answer += f"\n- [{title}]({url}){date_str}"

    
    history.append({"role": "user", "content": message})
    history.append({"role": "assistant", "content": answer})
    return history

# --- Funkcja do czyszczenia pola tekstowego ---
def clear_textbox():
    return gr.update(value="")

# --- Funkcja do flagowania ---
def flag_callback(history):
    if not history:
        gr.Warning("Brak wiadomo艣ci do oznaczenia.")
        return

    # Find the last user message and assistant response
    last_user_message = None
    last_assistant_message = None
    
    for i in range(len(history) - 1, -1, -1):
        msg = history[i]
        if msg.get("role") == "assistant" and last_assistant_message is None:
            last_assistant_message = msg.get("content", "")
        elif msg.get("role") == "user" and last_user_message is None:
            last_user_message = msg.get("content", "")
            break
    
    if not last_user_message or not last_assistant_message:
        gr.Warning("Nie mo偶na znale藕膰 ostatniej wymiany wiadomo艣ci.")
        return
    
    with open("flagged_responses.txt", "a", encoding="utf-8") as f:
        f.write(f"Zapytanie: {last_user_message}\nOdpowied藕: {last_assistant_message}\n")
        f.write("-" * 50 + "\n")
    gr.Info("Odpowied藕 zosta艂a oznaczona. Dzi臋kujemy za feedback!")

# --- Konfiguracja interfejsu Gradio ---
with gr.Blocks() as demo:
    gr.HTML("""
        <div style="display: flex; align-items: center; margin-bottom: 20px;">
            <img src="file/logo-korektor.png" alt="Logo" style="width: 150px; margin-right: 20px;" />
            <div>
                <h1>KoREKtor - Asystent HR</h1>
                <p>Tw贸j inteligentny partner w zatrudnianiu os贸b z niepe艂nosprawno艣ciami.</p>
            </div>
        </div>
        <img src="file/belka.png" alt="Belka" style="width: 100%; margin-bottom: 20px;" />
    """)
    
    if hr_import_error:
        gr.Markdown(f"**B艂膮d importu: {hr_import_error}**\n\nAby uruchomi膰 aplikacj臋, zainstaluj brakuj膮cy modu艂:\n\n`pip install sentence-transformers`")
    
    chatbot = gr.Chatbot(
        [],
        elem_id="chatbot",
        height=500,
        show_label=False,
        type="messages"
    )

    with gr.Row():
        msg = gr.Textbox(
            placeholder="Zadaj pytanie...",
            container=False,
            scale=9
        )
        submit = gr.Button("Wy艣lij", scale=1)

    flag = gr.Button("馃毄 Oznacz odpowied藕", scale=1)

    # Po wys艂aniu wiadomo艣ci, wywo艂aj chatbota, a nast臋pnie wyczy艣膰 pole tekstowe
    msg.submit(respond_to_query, [msg, chatbot], chatbot).then(clear_textbox, [], [msg])
    submit.click(respond_to_query, [msg, chatbot], chatbot).then(clear_textbox, [], [msg])
    
    # Flagowanie nie wymaga dodatkowych akcji po klikni臋ciu
    flag.click(flag_callback, [chatbot], None)

# --- Uruchomienie aplikacji ---
if __name__ == "__main__":
    demo.launch()