File size: 7,225 Bytes
7f8b26c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16ab811
7f8b26c
 
 
 
 
 
 
 
 
 
 
 
a72a624
 
 
 
 
 
 
 
7f8b26c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16ab811
7f8b26c
16ab811
 
 
 
 
 
 
 
 
7f8b26c
 
16ab811
7f8b26c
16ab811
 
 
 
 
 
 
 
7f8b26c
 
16ab811
7f8b26c
16ab811
 
 
 
 
 
7f8b26c
 
16ab811
7f8b26c
16ab811
 
 
 
 
 
 
 
 
7f8b26c
 
16ab811
7f8b26c
16ab811
 
 
 
 
 
7f8b26c
 
16ab811
7f8b26c
16ab811
 
 
 
 
7f8b26c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16ab811
7f8b26c
 
 
 
 
 
 
 
 
 
 
 
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
from typing import List, Dict, Tuple, Union, Optional, Any
import os

import gradio as gr

import requests
import backoff


class OrganizationNotFound(Exception):
    "No organization(s) found"


@backoff.on_exception(
    backoff.expo,
    (requests.exceptions.Timeout, requests.exceptions.ConnectionError),
    max_tries=5
)
def _get_json(route: str, **request_kwargs) -> Dict[str, Any] | str:
    r = requests.get(
        url=f"{os.getenv('LOI_API_URL')}/{route}",
        params=request_kwargs,
        headers={"x-api-key": os.getenv("LOI_API_KEY")},
        timeout=30
    )

    r.raise_for_status()
    return r.json().get("response")


@backoff.on_exception(
    backoff.expo,
    (requests.exceptions.Timeout, requests.exceptions.ConnectionError),
    max_tries=5
)
def _post_json(route: str, *, payload: Dict[str, Any]) -> Dict[str, Any] | str | int:
    r = requests.post(
        url=f"{os.getenv('LOI_API_URL')}/{route}",
        json=payload,
        headers={"x-api-key": os.getenv("LOI_API_KEY")},
        timeout=30
    )

    r.raise_for_status()
    return r.json().get("response")


def organization_pair_autofill(
    recipient_name: str,
    recipient_ein: str,
    funder_name: str,
    funder_ein: str
):
    recip_match = _get_json("/organization/search", name=recipient_name, ein=recipient_ein)
    if len(recip_match or []) == 0:
        # raise OrganizationNotFound()
        raise gr.Error("No matching recipient could be found")
    gr.Info(f"{recipient_name} found, auto-filling fields...")

    funder_match = _get_json("/organization/search", name=funder_name, ein=funder_ein)
    if len(funder_match or []) == 0:
        # raise OrganizationNotFound()
        raise gr.Error("No matching funder could be found")
    gr.Info(f"{funder_name} found, auto-filling fields...")

    data = _get_json(
        "/organization/autofill",
        recipient_candid_entity_id=recip_match[0]["candid_entity_id"],
        funder_candid_entity_id=funder_match[0]["candid_entity_id"],
    )

    return (
        data.get("recipient_data", {}).get("projects_text"),
        data.get("recipient_data", {}).get("capacity_text"),
        data.get("recipient_data", {}).get("contact_text"),
        data.get("recipient_data", {}).get("data_text"),  # accomplishments
        data.get("recipient_data", {}).get("mission_statement_text"),
        data.get("funder_data", {}).get("mission_statement_text"),
        data.get("funding_history_text"),
        data.get("recipient_data", {}).get("org_data"),
        recip_match[0]["candid_entity_id"],
        data.get("funder_data", {}).get("org_data"),
        funder_match[0]["candid_entity_id"],
    )


def cost_estimator(
    recipient_candid_entity_id: Union[int, str],
    recipient_data: Dict[str, Any],
    funder_data: Dict[str, Any],
    program_desc: Optional[str] = None
) -> str:
    estimate: str = _post_json(
        "budget",
        payload={
            "recipient_candid_entity_id": recipient_candid_entity_id,
            "program_description": program_desc,
            "recipient_data": recipient_data,
            "funder_data": funder_data,
        }
    )
    return estimate


def identify_vague_statements(text: str) -> Tuple[List[str], List[str], List[str]]:
    data = _get_json("/editorialai/vaguestatement", input_section=text)

    statements, alternatives, reasons = [], [], []
    for record in data:
        statements.append(record["vague_statement"])
        alternatives.append(record["alternative_text"])
        reasons.append(record["reason"])

    return statements, alternatives, reasons


def help_mission_statement(recipient_name: str, recipient_mission_info: str):
    return _get_json("/writerhelper/missionstatement", info=recipient_mission_info, org_name=recipient_name)


def draft_letter(
    recipient_name: str, funder_name: str, projects: str, amount: str,
    recipient_mission_statement: str = "", funder_mission_statement: str = "",
    project_name: str = "", project_purpose: str = "",
    prior_contact: str = "", connection: str = "",
    capacity: str = "", path_to_solution: str = "", recent_accomplishments: str = "",
    recipient_history: str = "", mutual_history: str = "",
    geo_pop_targets: str = "", project_data_stats: str = "",
    desired_objectives: str = "", major_activities: str = "", key_staff: str = "", standout_features: str = "",
    success_metric: str = "",
    other_funding_sources: str = "",
    contact_information: str = ""
):
    gr.Info("Writing the letter, please scroll to the top of the page.")
    opening: str = _post_json(
        "/writer/opening",
        payload=dict(
            funder_name=funder_name,
            recipient_name=recipient_name,
            project_name=project_name,
            project_purpose=project_purpose,
            amount=amount,
            prior_contact=prior_contact,
            connection=connection
        )
    )

    recipient_description: str = _post_json(
        "/writer/org",
            payload=dict(
            opening=opening,
            recipient_mission_statement=recipient_mission_statement,
            capacity=capacity,
            history=recipient_history,
            path=path_to_solution,
            accomplishment=recent_accomplishments
        )
    )

    need_statement: str  = _post_json(
        "/writer/need",
        payload=dict(
            recipient_desc=recipient_description,
            target=geo_pop_targets,
            data=project_data_stats,
            funder_mission_statement=funder_mission_statement
        )
    )

    project_description: str = _post_json(
        "/writer/project",
        payload=dict(
            need=need_statement,
            projects=projects,
            desired_objectives=desired_objectives,
            major_activities=major_activities,
            key_staff=key_staff,
            stand_out=standout_features,
            success=success_metric
        )
    )

    funding_request: str = _post_json(
        "/writer/fund",
        payload=dict(
            project_desc=project_description,
            amount=amount,
            funding_history=mutual_history,
            other_funding=other_funding_sources
        )
    )

    conclusion: str = _post_json(
        "/writer/conclusion",
        payload=dict(
            funding_request=funding_request,
            project_desc=project_description,
            follow_up=contact_information
        )
    )

    return (
        opening,
        recipient_description,
        need_statement,
        project_description,
        funding_request,
        conclusion
    )


def send_feedback(
    context: Dict[str, Any],
    letter: Dict[str, Any],
    relevance: int,
    coherence: int,
    fluency: int,
    overall_quality: int,
    comments: Optional[str] = None,
    email: Optional[str] = None
) -> int:
    count = _post_json(
        "feedback",
        payload={
            "context": context,
            "letter": letter,
            "relevance": relevance,
            "coherence": coherence,
            "fluency": fluency,
            "overall_quality": overall_quality,
            "comments": comments,
            "email": email
        }
    )
    return count